Get Location from Center of Screen Swift Mapkit

Get Location From Center of Screen Swift MapKit

You can use the regionDidChangeAnimated delegate method and call mapView.centerCoordinate. It will look like the following:

 func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
var center = mapView.centerCoordinate
}

Also make sure that your Class is extending MKMapViewDelegate and you are calling
self.mapView.delegate = self in your viewDidLoad() function.

Get center coordinates from MapKit and display in UILabel

Declare var center = "" at the top of your class with other declarations. In the method below, it should automatically change the value of center:

func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
center = mapView.centerCoordinate
}

When you press your button set the value of your label to the value of center.

self.yourLabelName.text = center

To display as "Latitude: ... Longitude: ..." do as follows:

func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
let mapLatitude = mapView.centerCoordinate.latitude
let mapLongitude = mapView.centerCoordinate.longitude
center = "Latitude: \(mapLatitude) Longitude: \(mapLongitude)"
print(center)
self.yourLabelName.text = center
}

If you want to format the coordinates to display a little more friendly:

center = "\(String(format: "%.5f", mapLatitude)), \(String(format: "%.5f", mapLongitude))"

Adjust the %.5f according to your preference of number of decimal places.

How I can center the map on user's location in swift?

The problem with your code is that you're trying to point the map to the user's location when the user gives location permission, you're not waiting for the CoreLocation to give you the actual user location.
You need to use the CLLocationManagerDelegate method locationManager(_:didUpdateLocations:) to be notified of when you get the user's actual location, and there you can set the map to point to the user's location.

class ViewController: UIViewController, CLLocationManagerDelegate {

@IBOutlet var mapView: MKMapView!
var locationManager: CLLocationManager?

override func viewDidLoad() {
super.viewDidLoad()

locationManager = CLLocationManager()
locationManager!.delegate = self

if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
locationManager!.startUpdatingLocation()
} else {
locationManager!.requestWhenInUseAuthorization()
}
}

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {


switch status {
case .NotDetermined:
print("NotDetermined")
case .Restricted:
print("Restricted")
case .Denied:
print("Denied")
case .AuthorizedAlways:
print("AuthorizedAlways")
case .AuthorizedWhenInUse:
print("AuthorizedWhenInUse")
locationManager!.startUpdatingLocation()
}
}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

let location = locations.first!
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 500, 500)
mapView.setRegion(coordinateRegion, animated: true)
locationManager?.stopUpdatingLocation()
locationManager = nil
}

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Failed to initialize GPS: ", error.description)
}
}

update center of screen with current location

Use userTrackningMode which causes the map view to center the map on that location and begin tracking the user’s location. If the map is zoomed out, the map view automatically zooms in on the user’s location, effectively changing the current visible region.

To use it

mapView.setUserTrackingMode(.follow, animated:true)

Button to center view to user location using MapKit

This way runs well (Swift), and you can customize the button:

class YourViewController{
...
@IBOutlet weak var mapView:MKMapView
...

override func viewDidLoad() {
super.viewDidLoad()
...
addMapTrackingButton()
}

func addMapTrackingButton(){
let image = UIImage(named: "trackme") as UIImage?
let button = UIButton(type: UIButtonType.System) as UIButton
button.frame = CGRectMake(5, 5, 35, 35)
button.setImage(image, forState: .Normal)
button.backgroundColor = .clearColor()
button.addTarget(self, action: #selector(YourViewController.centerMapOnUserButtonClicked), forControlEvents:.TouchUpInside)
self.mapView.addSubview(button)
}

func centerMapOnUserButtonClicked() {
self.mapView.setUserTrackingMode( MKUserTrackingMode.Follow, animated: true)
}
...
}

Swift 4:

func addMapTrackingButton(){
let image = UIImage(named: "trackme") as UIImage?
let button = UIButton(type: UIButtonType.custom) as UIButton
button.frame = CGRect(origin: CGPoint(x:5, y: 25), size: CGSize(width: 35, height: 35))
button.setImage(image, for: .normal)
button.backgroundColor = .clear
button.addTarget(self, action: #selector(ViewController.centerMapOnUserButtonClicked), for:.touchUpInside)
mapView.addSubview(button)
}

@objc func centerMapOnUserButtonClicked() {
mapView.setUserTrackingMode(MKUserTrackingMode.follow, animated: true)
}


Related Topics



Leave a reply



Submit