Hamish Johnson Hamish Johnson - 1 month ago 17
iOS Question

How should I find the correct location data using userLocation in Mapbox for iOS SDK? (Swift)

I'm trying to find the latitude and longitude of the user's location so that I can center the map on the user in viewdidload.

I've implemented what seems to be the right code but the values of userLat (latitude) and userLon (longitude) are way off.

N.B. Somebody else had the same problem as me but his answer was never resolved:
Mapbox iOS8 Swift mapView.showUsersLocation

import Mapbox

class ViewController: UIViewController, MGLMapViewDelegate, CLLocationManagerDelegate {

// let locationManager = CLLocationManager()

@IBOutlet weak var mapView: MGLMapView!

override func viewDidLoad() {
super.viewDidLoad()

// Initalise map's center coordinate as vancouver
mapView.setCenterCoordinate(CLLocationCoordinate2D(latitude: 49.283382,
longitude: -123.117394),
zoomLevel: 15, animated: false)
view.addSubview(mapView)

// Set the delegate property of our map view to self after instantiating it.
mapView.delegate = self

// User location
mapView.showsUserLocation = true

let userLoc = mapView.userLocation!
userLoc.title = "Hello"
userLoc.subtitle = "I am here!"

let userLat = userLoc.coordinate.latitude
let userLon = userLoc.coordinate.longitude

print(userLat, userLon)

/*
self.locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}*/

}

func mapView(mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
return true
}

}


Resulting print:

3.40282346638529e+38 3.40282346638529e+38


The strange thing is that the annotation works fine, and when I click my location I get the title and subtitle.

Answer

The easiest way to center the map on the user's location is to set mapView.userTrackingMode = .Follow (MGLUserTrackingModeFollow in Objective C). This will automatically move the map when a location is available.

The reason why you're seeing bogus numbers for mapView.userLocation is that the user's location typically isn't available yet in viewDidLoad. Use the mapView:didUpdateUserLocation: delegate method to be notified when the user's location becomes available and when it updates.

Comments