I am trying to display the current location of the user and have the region set to their current location.
Here is my code.
#IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
let userLocation = locations.last
let viewRegion = MKCoordinateRegionMakeWithDistance((userLocation?.coordinate)!, 600, 600)
self.mapView.setRegion(viewRegion, animated: true)
}
What happens:
Map loads
Map region is set to current location
Map region will keep updating to the current location
Current location gets printed to the console
What doesn't work:
"Blue" current location indicator does not appear.
If you know what I need to do to make the "Blue" current location indicator appear it will be much appreciated.
You need to set
mapView.showsUserLocation = true
In viewDidLoad
Related
If I am running my code the rounded blue point isn't shown up on the map. user location visible on the map does not work. I can't find the problem for that. Anyone who can find the issue?
import UIKit
import MapKit
import CoreLocation
class GPSNewBin: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var mapView: MKMapView!
#IBOutlet weak var zurueckButton: UIButton!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
let locValue: CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
let userLocation = locations.last
let viewRegion = MKCoordinateRegion(center: (userLocation?.coordinate)!, latitudinalMeters: 600, longitudinalMeters: 600)
self.mapView.setRegion(viewRegion, animated: true)
}
}
Thanks a lot :)
You can enable user location from a storyboard:
OR
You can also enable it using code:
mapView.showsUserLocation = true
You must include following properties in Info.plist, without it your request for authorization will not work.
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Message for AlwaysAndWhenInUseUsageDescription</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Message for AlwaysUsageDescription</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Message for WhenInUseUsageDescription</string>
Use following method for requesting authorization in viewDidLoad, it also takes in account when location services is denied to the app.
func checkLocationAuthorization(authorizationStatus: CLAuthorizationStatus? = nil) {
switch (authorizationStatus ?? CLLocationManager.authorizationStatus()) {
case .authorizedAlways, .authorizedWhenInUse:
mapView.showsUserLocation = true
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
default:
print("Location Servies: Denied / Restricted")
}
}
checkLocationAuthorization in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
self.checkLocationAuthorization()
}
You must also update the authorization status, when a CLLocationManagerDelegate.locationManager(_:didChangeAuthorization:) is occurred, you can re-use above method, like so:
extension GPSNewBin: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
self.checkLocationAuthorization(authorizationStatus: status)
}
}
When updating location in didUpdateLocations, use the updated user location sent in userLocation.coordinate, like so:
extension GPSNewBin: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
let region = MKCoordinateRegion(center: userLocation.coordinate, latitudinalMeters: 600, longitudinalMeters: 600)
mapView.setRegion(region, animated: true)
}
}
I am trying to show annotation pin for current location. For that I have written following code
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
mapView.layer.cornerRadius = 8.0
imageView.layer.cornerRadius = 8.0
//mapview settings
mapView.mapType = MKMapType.standard
mapView.isZoomEnabled = true
mapView.isZoomEnabled = true
// Or, if needed, we can position map in the center of the view
mapView.center = view.center
mapView.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
determineCurrentLocation()
}
func determineCurrentLocation()
{
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
//locationManager.startUpdatingHeading()
locationManager.startUpdatingLocation()
}
}
//Mapview Delegate methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
// Call stopUpdatingLocation() to stop listening for location updates,
// other wise this function will be called every time when user location changes.
//manager.stopUpdatingLocation()
let center = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
mapView.setRegion(region, animated: true)
// Drop a pin at user's Current Location
let myAnnotation: MKPointAnnotation = MKPointAnnotation()
myAnnotation.coordinate = CLLocationCoordinate2DMake(userLocation.coordinate.latitude, userLocation.coordinate.longitude);
myAnnotation.title = "Current location"
mapView.addAnnotation(myAnnotation)
}
func locationManager(manager: CLLocationManager, didFailWithError error: Error)
{
print("Error \(error)")
}
But, its nothing showing in mapview. Any suggestions?
You need to add NSLocationAlwaysUsageDescription key in Info.plist with a message to be displayed in the prompt.
I have been trying to implement google maps in my application. The first step what I want to do is to simply get is:
1. Get the app to ask permission to use current location
2. Find the users current location and have a blue dot marker to mark it.
3. Update and centre the map around the users current location.
I have tried various methods to get this working but always end up with an error or doesn't work. Initially when I simulated the code below, it did come up with the dialog about requesting current location permission and a blue dot but in the following simulations this seems to have disappeared and when changing my current location in simulator (by going to edit schemes and changing default location) , the new current location did not update. I have a feeling that the code isn't working beyond viewDidLoad. where am I going wrong?
Please can I get some advice on how to rectify these problems and get the above points working (as well as the simulator to always ask for permission for current location). Currently the code runs with no errors but only shows me a map of the UK. (I have already added NSLocationWhenInUse and NSLocationAlwaysUsage.... into info.plist. And I have disabled all breakpoints. I have also tried resetting simulator)
import UIKit
import GoogleMaps
class FirstViewController: UIViewController,CLLocationManagerDelegate {
#IBOutlet weak var googlemaps: GMSMapView!
//this is the connection from the storyboard to the view controller
override func viewDidLoad() {
super.viewDidLoad()
let camera = GMSCameraPosition.camera(withLatitude: 51.508742, longitude: -0.087891, zoom: 8.0)
let viewMap = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
view = viewMap
viewMap.isMyLocationEnabled = true
let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
}
override func loadView() {
super.viewDidLoad()
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
// verification of granted permission while app in use
let locationManager = CLLocationManager()
let mapView = GMSMapView()
if status == .authorizedWhenInUse {
locationManager.startUpdatingLocation()
// if permission granted- starting updating location
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
//this is suppose to be button that is added when tapped centers to users location
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
mapView.camera = GMSCameraPosition.camera(withTarget: location.coordinate, zoom: 20)
self.view = mapView
locationManager.stopUpdatingLocation()
}
}
}
}
}
Thanks in advance! I have spent days trying to work this out with no success :(
I was able to solve this problem by updating Cocoapods and ensuring that GoogleMaps is in my Podfile. Then in my viewController I had the following code which executed perfectly.
import UIKit
import GoogleMaps
class FirstViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var mapView: GMSMapView!
var locationManager = CLLocationManager()
var vwGMap = GMSMapView()
override func viewDidLoad() {
super.viewDidLoad()
let camera: GMSCameraPosition = GMSCameraPosition.camera(withLatitude: 22.300000, longitude: 70.783300, zoom: 10.0)
vwGMap = GMSMapView.map(withFrame: self.view.frame, camera: camera)
vwGMap.camera = camera
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
locationManager.distanceFilter = 500
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
self.view = vwGMap
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if (status == CLAuthorizationStatus.authorizedWhenInUse)
{
vwGMap.isMyLocationEnabled = true
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let newLocation = locations.last
vwGMap.camera = GMSCameraPosition.camera(withTarget: newLocation!.coordinate, zoom: 15.0)
vwGMap.settings.myLocationButton = true
self.view = self.vwGMap
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(newLocation!.coordinate.latitude, newLocation!.coordinate.longitude)
marker.map = self.vwGMap
}
}
I'm trying to display the user's current location on a google map but in the case below, the map doesn't even get displayed. What should I change to fix this?
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//user location stuff
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error" + error.description)
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation = locations.last
let center = CLLocationCoordinate2D(latitude: userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude)
let camera = GMSCameraPosition.cameraWithLatitude(userLocation!.coordinate.latitude,
longitude: userLocation!.coordinate.longitude, zoom: 8)
let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
mapView.myLocationEnabled = true
self.view = mapView
let marker = GMSMarker()
marker.position = center
marker.title = "Current Location"
marker.snippet = "XXX"
marker.map = mapView
locationManager.stopUpdatingLocation()
}
You can try this bellow code its working fine
import UIKit
import GoogleMaps
import GooglePlaces
class SearchMapsViewController: UIViewController,
UINavigationBarDelegate, GMSAutocompleteFetcherDelegate,
LocateOnTheMap, UISearchBarDelegate, CLLocationManagerDelegate
{
#IBOutlet var googleMapsContainerView: UIView!
var searchResultController: SearchResultsController!
var resultsArray = [String]()
var googleMapsView:GMSMapView!
var gmsFetcher: GMSAutocompleteFetcher!
var locationManager = CLLocationManager()
override func viewDidAppear(animated: Bool) {
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
self.googleMapsView = GMSMapView (frame: self.googleMapsContainerView.frame)
self.googleMapsView.settings.compassButton = true
self.googleMapsView.myLocationEnabled = true
self.googleMapsView.settings.myLocationButton = true
self.view.addSubview(self.googleMapsView)
searchResultController = SearchResultsController()
searchResultController.delegate = self
gmsFetcher = GMSAutocompleteFetcher()
gmsFetcher.delegate = self
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print("Error" + error.description)
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let userLocation = locations.last
let center = CLLocationCoordinate2D(latitude: userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude)
let camera = GMSCameraPosition.cameraWithLatitude(userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude, zoom: 15);
self.googleMapsView.camera = camera
self.googleMapsView.myLocationEnabled = true
let marker = GMSMarker(position: center)
print("Latitude :- \(userLocation!.coordinate.latitude)")
print("Longitude :-\(userLocation!.coordinate.longitude)")
marker.map = self.googleMapsView
marker.title = "Current Location"
locationManager.stopUpdatingLocation()
}
do requier setting on infoPlist and then try this
#IBOutlet weak var your "name of view which show map": GMSMapView!
override func viewDidLoad(){
super.viewDidLoad()
placesClient = GMSPlacesClient.shared()
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
locationManager.distanceFilter = 500
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
mapView.settings.myLocationButton = true
mapView.settings.zoomGestures = true
mapView.animate(toViewingAngle: 45)
mapView.delegate = self }
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let newLocation = locations.last // find your device location
mapView.camera = GMSCameraPosition.camera(withTarget: newLocation!.coordinate, zoom: 14.0) // show your device location on map
mapView.settings.myLocationButton = true // show current location button
var lat = (newLocation?.coordinate.latitude)! // get current location latitude
var long = (newLocation?.coordinate.longitude)! //get current location longitude
}
The problem is that you are setting the mapView's frame to CGRectZero. This causes the map to have zero height and zero width, no wonder it does not show!
Try setting it to CGRectMake(0,0,200,200) for example, this will give you a map at the left top of the screen with a size of 200 x 200.
I have never used Swift before, so the syntax might be a little different for CGRectMake()
It seems that your creation of the map isn't in your viewDidLoad function. You may want to try moving that there and see what happens.
Add the appropriate properties into the info.plist.
You should put make sure you have the NS properties of locationalwaysusagedescription and wheninuseusagedescription in the information properties list. This allows for the permissions of the current location to be asked.
import UIKit
import GoogleMaps
import GooglePlaces
import CoreLocation
class MapsViewController: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate {
var mapView = GMSMapView()
var locationManager = CLLocationManager()
let marker = GMSMarker()
override func viewDidLoad(){
super.viewDidLoad()
mapView.frame = self.view.bounds
self.view.addSubview(mapView)
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 10
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
mapView.settings.myLocationButton = true
mapView.settings.zoomGestures = true
mapView.animate(toViewingAngle: 45)
mapView.delegate = self
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let newLocation = locations.last // find your device location
mapView.camera = GMSCameraPosition.camera(withTarget: newLocation!.coordinate, zoom: 14.0) // show your device location on map
mapView.settings.myLocationButton = true // show current location button
let lat = (newLocation?.coordinate.latitude)! // get current location latitude
let long = (newLocation?.coordinate.longitude)! //get current location longitude
marker.position = CLLocationCoordinate2DMake(lat,long)
marker.map = mapView
print("Current Lat Long - " ,lat, long )
}
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
mapView.clear()
DispatchQueue.main.async {
let position = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude)
self.marker.position = position
self.marker.map = mapView
self.marker.icon = UIImage(named: "default_marker")
print("New Marker Lat Long - ",coordinate.latitude, coordinate.longitude)
}
}
}
I am learning how to use the new Swift language (only Swift, no Objective-C). To do it, I want to do a simple view with a map (MKMapView). I want to find and update the location of the user (like in the Apple Map app).
I tried this, but nothing happened:
import MapKit
import CoreLocation
class MapView : UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var map: MKMapView!
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
if (CLLocationManager.locationServicesEnabled())
{
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
}
Could you please help me?
You have to override CLLocationManager.didUpdateLocations (part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last{
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)
}
}
NOTE: If your target is iOS 8 or above, you must include the NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription key in your Info.plist to get the location services to work.
100% working, easy steps and tested
Import libraries:
import MapKit
import CoreLocation
set delegates:
CLLocationManagerDelegate,MKMapViewDelegate
Take variable:
let locationManager = CLLocationManager()
write this code on viewDidLoad():
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
mapView.delegate = self
mapView.mapType = .standard
mapView.isZoomEnabled = true
mapView.isScrollEnabled = true
if let coor = mapView.userLocation.location?.coordinate{
mapView.setCenter(coor, animated: true)
}
Write delegate method for location:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
mapView.mapType = MKMapType.standard
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegion(center: locValue, span: span)
mapView.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = locValue
annotation.title = "Javed Multani"
annotation.subtitle = "current location"
mapView.addAnnotation(annotation)
//centerMap(locValue)
}
Do not forgot to set permission in info.plist
<key>NSLocationWhenInUseUsageDescription</key>
<string>This application requires location services to work</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This application requires location services to work</string>
It's look like:
For swift 3 and XCode 8 I find this answer:
First, you need set privacy into info.plist. Insert string NSLocationWhenInUseUsageDescription with your description why you want get user location. For example, set string "For map in application".
Second, use this code example
#IBOutlet weak var mapView: MKMapView!
private var locationManager: CLLocationManager!
private var currentLocation: CLLocation?
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
// Check for Location Services
if CLLocationManager.locationServicesEnabled() {
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
}
// MARK - CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
defer { currentLocation = locations.last }
if currentLocation == nil {
// Zoom to user location
if let userLocation = locations.last {
let viewRegion = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 2000, 2000)
mapView.setRegion(viewRegion, animated: false)
}
}
}
Third, set User Location flag in storyboard for mapView.
MyLocation
is a Swift iOS Demo.
You can use this demo for the following:
Show the current location.
Choose other location: in this case stop tracking the location.
Add a push pin to a MKMapView(iOS) when touching.
Hi Sometimes setting the showsUserLocation in code doesn't work for some weird reason.
So try a combination of the following.
In viewDidLoad()
self.mapView.showsUserLocation = true
Go to your storyboard in Xcode, on the right panel's attribute inspector tick the User location check box, like in the attached image. run your app and you should be able to see the User location
Swift 5.1
Get Current Location and Set on MKMapView
Import libraries:
import MapKit
import CoreLocation
set delegates:
CLLocationManagerDelegate , MKMapViewDelegate
Declare variable:
let locationManager = CLLocationManager()
Write this code on viewDidLoad():
self.locationManager.requestAlwaysAuthorization()
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
mapView.delegate = self
mapView.mapType = .standard
mapView.isZoomEnabled = true
mapView.isScrollEnabled = true
if let coor = mapView.userLocation.location?.coordinate{
mapView.setCenter(coor, animated: true)
}
Write delegate method for location:
func locationManager(_ manager: CLLocationManager, didUpdateLocations
locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
mapView.mapType = MKMapType.standard
let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
let region = MKCoordinateRegion(center: locValue, span: span)
mapView.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = locValue
annotation.title = "You are Here"
mapView.addAnnotation(annotation)
}
Set permission in info.plist *
<key>NSLocationWhenInUseUsageDescription</key>
<string>This application requires location services to work</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This application requires location services to work</string>
For Swift 2, you should change it to the following:
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.01, longitudeDelta: 0.01))
self.map.setRegion(region, animated: true)
}
You just need to set the userTrackingMode of the MKMapView. If you only want to display and track the user location and implement the same behaviour as the Apple Maps app uses, there is no reason for writing additional code.
mapView.userTrackingMode = .follow
See more at https://developer.apple.com/documentation/mapkit/mkmapview/1616208-usertrackingmode .
you have to override CLLocationManager.didUpdateLocations
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
locationManager.stopUpdatingLocation()
let location = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
let span = MKCoordinateSpanMake(0.5, 0.5)
let region = MKCoordinateRegion (center: location,span: span)
mapView.setRegion(region, animated: true)
}
you also have to add NSLocationWhenInUseUsageDescription and NSLocationAlwaysUsageDescription to your plist setting Result as value
In Swift 4, I had used the locationManager delegate function as defined above ..
func locationManager(manager: CLLocationManager!,
didUpdateLocations locations: [AnyObject]!) {
.. but this needed to be changed to ..
func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]) {
This came from .. https://github.com/lotfyahmed/MyLocation/blob/master/MyLocation/ViewController.swift - thanks!
mapView.showsUserLocation = true
Create UIButton and add this action
#IBAction func showCurrentLocation(_ sender: Any) {
let coordinate = mapView.userLocation.coordinate
let center = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
}