How to Center a Map on User Location IOS 9 SWIFT - ios

Hi I have the below code which is finding the user location the radius within 1 mile:
let initialLocation = CLLocation(latitude: 51.5001524, longitude: -0.1262362)
let regionRadius: CLLocationDistance = 1000
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
func centerMapOnLocation(location:CLLocation) {
let coordianteRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2.0, regionRadius * 2.0)
mapView.setRegion(coordianteRegion, animated: true)
}
// Do any additional setup after loading the view, typically from a nib.
centerMapOnLocation(initialLocation)
}
This is perfect as gets a decent radius for user location, however i want to know, how do you center map on user location?
i have tried a lot of methods but i do not seem to be able to get the map to center on user location.
Any help would be much appreciated!
Thanks

MKMapView has a built in solution by using the userTrackingMode property.
mapView.userTrackingMode = .follow

I think this might help you
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
let location = locations.last as CLLocation
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.map.setRegion(region, animated: true)
}

Related

Mapkit - Swift4 - How to disable Auto zooming

Apologies for the absurdely junior question but for some reason I can't grasp how to stop this from happening.
When I run the app, and I pinch to zoom into the map (or out, or navigate away from my position) the app will always pull me back to a set height and to my location. I'd like to not have this happen and just have the experience of zooming to whatever level and moving around without being interrupted.
Any ideas?
Here's the code snip from my VC:
let regionRadius: CLLocationDistance = 2000
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius, regionRadius)
mapView.setRegion(coordinateRegion, animated: true)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
let center = location.coordinate
let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
let region = MKCoordinateRegion(center: center, span: span)
mapView.setRegion(region, animated: true)
mapView.showsUserLocation = true
}
Thanks for any help
Location Manager delegate methods can be called very frequently and at any time. So you need to stop updating locations.
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
manager.stopUpdatingLocation()
manager.delegate = nil
let location = locations[0]
...
}

Retain map zoom level while there is a change in location

I am using a MKMapView application. but when zoom into the map to the current user location, the map zooms well. But when there is a change in current location, the map automatically zooms out to the original position where it all started. How can I retain the same level of zoom even when the location changes. Thank you.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let latestlocation:CLLocation = locations[locations.count-1]
let a = latestlocation.coordinate.latitude
let b = latestlocation.coordinate.longitude
let center = CLLocationCoordinate2D(latitude: a, longitude: b)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpanMake(0.05, 0.05))
self.mapView.setRegion(region, animated: false)
mapView.setUserTrackingMode(.follow, animated: true)
self.mapView.showsUserLocation = true
}

Swift User Location Issue

I had working mapview on users location at the start of my project but now it wont zoom in on the user at startup. Any idea how to fix this? the code i use:
In Class
class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate
var Locationmanager = CLLocationManager()
In viewdidload
self.Locationmanager.delegate = self
self.Locationmanager.desiredAccuracy = kCLLocationAccuracyBest
self.Locationmanager.requestWhenInUseAuthorization()
self.Locationmanager.startUpdatingLocation()
self.Mapview.showsUserLocation = true
Mapview.setCenterCoordinate(Mapview.userLocation.coordinate, animated: true)
In function
func locationManager(manager: CLLocationManager, didUpdateLocations locations:[MKUserLocation]) {
let latitude = Locationmanager.location?.coordinate.latitude
let longitude = Locationmanager.location?.coordinate.longitude
let center = CLLocationCoordinate2D (latitude: latitude!, longitude: longitude!)
let region = MKCoordinateRegion (center: center, span: MKCoordinateSpan (latitudeDelta: 0.02, longitudeDelta: 0.02))
self.Mapview.setRegion(region, animated: true)
self.Locationmanager.stopUpdatingLocation()
And in info.plist
NSLocationWhenInUseUsageDescription
If your goal is to make a map view display the user's location, there is no need, and no point, to tell the location manager to do anything. Get rid of all that code - it is actually doing you harm here. Just set the map view's userTrackingMode to .follow and stand back.

Show several annotations in iOS Map

I am trying to show user's current location and users nearby the area.
I am doing to show user's
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude:location!.coordinate.latitude ,longitude : location!.coordinate.longitude )
let span = MKCoordinateSpanMake(0.01,0.01 )
let region = MKCoordinateRegion(center: center, span: span)
self.mapView.setRegion(region, animated: true)
self.manager.stopUpdatingLocation()
}
Plotting near by users
plotUsersonGraph(lat,longitude:long,title:"Apple HQ",subtitle:"Welcome to Apple")
func plotUsersonGraph(latitude:Double,longitude:Double,title:String,subtitle:String){
let HQlocation = CLLocationCoordinate2DMake(latitude, longitude)
let span = MKCoordinateSpanMake(0.01, 0.01)
let region = MKCoordinateRegion(center: HQlocation, span: span)
// self.mapView.setRegion(region, animated: true)**THIS IS CAUSING PROBLEM**
let annotation = MKPointAnnotation()
annotation.coordinate = HQlocation
annotation.title = title
annotation.subtitle = subtitle
self.mapView.addAnnotation(annotation)
}
I am able to view both the locations individually but I am unable to merge both of them together. plotUsersonGraph will add multiple users on the graph simultaneously.
This is how I achieved it
Added
self.mapView.showsUserLocation = true
inside
func plotUsersonGraph(latitude:Double,longitude:Double,title:String,subtitle:String){
}

Saving map pins to array, Swift

I am creating a map type application, once the user presses a button a pin is dropped to the map at their current location. I am trying to save map pins to an array so that they remain once the app is closed.
Here is my code so far:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.004, longitudeDelta: 0.004))
self.placesMap?.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print("Error code: " + error.localizedDescription)
}
// Add button action
#IBAction func addButton(sender: AnyObject) {
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: self.placesMap.userLocation.coordinate.latitude, longitude: self.placesMap.userLocation.coordinate.longitude)
self.placesMap.addAnnotation(annotation)
self.locationManager.startUpdatingLocation()
}
How can I save the pin information to an array which is reloaded each time the app is opened?
If you want to persist data between application launches, and you are not storing much data, the easy way is to use NSUserDefaults. You can do this by saying something like:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.004, longitudeDelta: 0.004))
self.placesMap?.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
let locationDictionary:[String:Double] = ["latitude":center.latitude,"longitude":center.longitude]
var locationArray = [[String:Double]]()
if NSUserDefaults.standardUserDefaults().objectForKey("locationArray") != nil {
locationArray = NSUserDefaults.standardUserDefaults().objectForKey("locationArray") as! [[String:Double]]
}
locationArray.append(locationDictionary)
NSUserDefaults.standardUserDefaults().setObject(locationArray, forKey: "locationArray")
NSUserDefaults.standardUserDefaults().synchronize()
}
You will then need to read out those locations when the app relaunches. You can do that in viewDidLoad. For example:
override func viewDidLoad(){
super.viewDidLoad()
if NSUserDefaults.standardUserDefaults().objectForKey("locationArray") != nil {
for dictionary in NSUserDefaults.standardUserDefaults().objectForKey("locationArray") as! [[String:Double]]{
let center = CLLocationCoordinate2D(latitude: dictionary["latitude"]!, longitude: dictionary["longitude"]!)
let annotation = MKPointAnnotation()
annotation.coordinate = center
self.placesMap.addAnnotation(annotation)
}
}
}
If you want to remove all of the stored locations you can say something like:
func removeStoredLocations(){
NSUserDefaults.standardUserDefaults().removeObjectForKey("locationArray")
NSUserDefaults.standardUserDefaults().synchronize()
}

Resources