MapKit zoom to user current location - ios

I am trying to simply show user's location on the map, but I need to when app launches, the map should zoom to current location ,but I don't know why map doesn't zoom at all and it's like this :
Here is the code :
class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
mapView.showsUserLocation = true
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.delegate = self
DispatchQueue.main.async {
self.locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
let location = locations.last as! CLLocation
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
var region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1))
region.center = mapView.userLocation.coordinate
mapView.setRegion(region, animated: true)
}

I faced similar issue and wasted 4 days thinking whats going wrong. Finally resolved with creating these lines of code in viewDidLoad Method :
//Zoom to user location
let noLocation = CLLocationCoordinate2D()
let viewRegion = MKCoordinateRegionMakeWithDistance(noLocation, 200, 200)
mapView.setRegion(viewRegion, animated: false)
mapView.showsUserLocation = true
In ViewDidLoad Method add these new changes code :
override func viewDidLoad() {
super.viewDidLoad()
let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
// Check for Location Services
if (CLLocationManager.locationServicesEnabled()) {
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
}
//Zoom to user location
if let userLocation = locationManager.location?.coordinate {
let viewRegion = MKCoordinateRegionMakeWithDistance(userLocation, 200, 200)
mapView.setRegion(viewRegion, animated: false)
}
self.locationManager = locationManager
DispatchQueue.main.async {
self.locationManager.startUpdatingLocation()
}
}
Hope this helps to resolve your issue. Feel free to post comment if any further issue. Thanks

Here's another approach for Swift 3, XCode 8.2. First, write out a helper function:
let homeLocation = CLLocation(latitude: 37.6213, longitude: -122.3790)
let regionRadius: CLLocationDistance = 200
func centerMapOnLocation(location: CLLocation)
{
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2.0, regionRadius * 2.0)
mapView.setRegion(coordinateRegion, animated: true)
}
Then, call in in viewDidLoad()
mapView.showsUserLocation = true
centerMapOnLocation(location: homeLocation)
This will start the app with the location specified in the variable zoomed in.

In Swift 4.2 there has been changes with this code. Here is how it works now:
import UIKit
import MapKit
import CoreLocation
class MapVC: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
let authorizationStatus = CLLocationManager.authorizationStatus()
let regionRadius: Double = 1000
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
locationManager.delegate = self
configureLocationServices()
}
func centerMapOnUserLocation() {
guard let coordinate = locationManager.location?.coordinate else {return}
let coordinateRegion = MKCoordinateRegion(center: coordinate, latitudinalMeters: regionRadius, longitudinalMeters: regionRadius)
mapView.setRegion(coordinateRegion, animated: true)
}
func configureLocationServices() {
if authorizationStatus == .notDetermined {
locationManager.requestAlwaysAuthorization()
} else {
return
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
centerMapOnUserLocation()
}
}

Code:
import UIKit
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet weak var mapview: MKMapView!
let locationmanager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
mapview.mapType = MKMapType.standard
let location = CLLocationCoordinate2DMake(22.4651, 70.0771)
let span = MKCoordinateSpanMake(0.5, 0.5)
let region = MKCoordinateRegionMake(location, span)
mapview.setRegion(region, animated: true)
let annonation = MKPointAnnotation()
annonation.coordinate = location
annonation.title = "Chandi Bazar"
annonation.subtitle = "Jamnagar"
//
mapview.addAnnotation(annonation)
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)")
locationmanager.stopUpdatingLocation()
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?
{
if (annotation is MKUserLocation)
{
return nil
}
let annotationidentifier = "Annotationidentifier"
var annotationview:MKAnnotationView
annotationview = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationidentifier)
let btn = UIButton(type: .detailDisclosure)
btn.addTarget(self, action: #selector(ViewController.hirenagravat(sender:)), for: .touchUpInside)
annotationview.rightCalloutAccessoryView = btn
annotationview.image = UIImage(named: "images (4).jpeg")
annotationview.canShowCallout = true
return annotationview
}
func hirenagravat(sender:UIButton)
{
let fvc = storyboard?.instantiateViewController(withIdentifier: "secondViewController") as? secondViewController
self.navigationController?.pushViewController(fvc!, animated: true)
}

In swift 4.1. To change the Zoom level you need to change the span value i.e MKCoordinateSpan(latitudeDelta: 0.95, longitudeDelta: 0.95)
let lat = "33.847105"
let long = "-118.2673272"
let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: Double(lat)!, longitude: Double(long)!), span: MKCoordinateSpan(latitudeDelta: 0.95, longitudeDelta: 0.95))
DispatchQueue.main.async {
self.mapView.setRegion(region, animated: true)
}
Swift 5.0
let span = MKCoordinateSpan.init(latitudeDelta: 0.01, longitudeDelta:
0.01)
let coordinate = CLLocationCoordinate2D.init(latitude: 21.282778, longitude: -157.829444) // provide you lat and long
let region = MKCoordinateRegion.init(center: coordinate, span: span)
mapView.setRegion(region, animated: true)

when you set region -> you cannot zoom the map anymore. below to fix that
func yourFuncName() {
//this is global var
regionHasBeenCentered = false
if !self.regionHasBeenCentered {
let span: MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
let userLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(_cllocationOfUserCurrentLocation!.coordinate.latitude, _cllocationOfUserCurrentLocation!.coordinate.longitude)
let region: MKCoordinateRegion = MKCoordinateRegionMake(userLocation, span)
self.mapView.setRegion(region, animated: true)
self.regionHasBeenCentered = true
}
self.mapView.showsUserLocation = true
}

Try with MKMapViewDelegate func:
var isInitiallyZoomedToUserLocation: Bool = false
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
if !isInitiallyZoomedToUserLocation {
isInitiallyZoomedToUserLocation = true
mapView.showAnnotations([userLocation], animated: true)
}
}

func animateToUserLocation() {
if let annoation = mapView.annotations.filter ({ $0 is MKUserLocation }).first {
let coordinate = annoation.coordinate
let viewRegion = MKCoordinateRegion(center: coordinate, latitudinalMeters: 200, longitudinalMeters: 200)
mapView.setRegion(viewRegion, animated: true)
}
}

Related

MKLocalSearch (search.start)always goes in the error flow. (SWIFT)

I've been trying to learn swift for the past few days and just started my own project! As part of the project I wanted to show nearby cocktail bars on a map, I was able to find some nice info online and have been able to show a map with my current location. I also found info on how to find nearby locations: https://developer.apple.com/documentation/mapkit/mklocalsearch/request
Unfortunately this last one never seems to work, it just goes out of the function and does not return any locations, could anyone help me further? Below is the code of my viewcontroller with the function getNearbyLandmarks which doesn't work as intended.
class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet var mapView: MKMapView!
let manager = CLLocationManager()
private var landmarks: [Landmark] = [Landmark]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.delegate = self
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
manager.stopUpdatingLocation()
render(location)
}
}
func render(_ location: CLLocation){
let coordinate = CLLocationCoordinate2D(latitude: location.coordinate.latitude,
longitude: location.coordinate.longitude)
let span = MKCoordinateSpan(latitudeDelta: 0.01,
longitudeDelta: 0.01)
let region = MKCoordinateRegion(center: coordinate,
span: span)
mapView.delegate = self
mapView.setRegion(region,
animated: true)
let pin = MKPointAnnotation()
pin.coordinate = coordinate
pin.title = "Current location"
mapView.addAnnotation(pin)
self.getNearByLandmarks()
updateAnnotations(from: mapView)
}
func mapView(_ mapViewIcon: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
var annotationView = mapViewIcon.dequeueReusableAnnotationView(withIdentifier: "custom")
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation,
reuseIdentifier: "custom")
annotationView?.canShowCallout = true
}else{
annotationView?.annotation = annotation
}
annotationView?.image = UIImage(named: "User")
return annotationView
}
private func getNearByLandmarks(){
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = "coffee"
request.region = mapView.region
let search = MKLocalSearch(request: request)
search.start{(response, error) in
if let response = response {
let mapItems = response.mapItems
self.landmarks = mapItems.map{
Landmark(placemark: $0.placemark)
}
}
}
}
private func updateAnnotations(from mapView: MKMapView){
let annotations = self.landmarks.map(LandmarkAnnotation.init)
mapView.addAnnotations(annotations)
}
}
You call getNearByLandmarks, and then immediately try to update the annotations:
self.getNearByLandmarks()
updateAnnotations(from: mapView)
but getNearByLandmarks is asynchronous, and takes some time to complete. You need to update the annotations whenever private var landmarks changes, one way is to update it in all the places that set that, like where you say
self.landmarks = mapItems.map{
Landmark(placemark: $0.placemark)
}
note you don't call updateAnnotations(from: mapView) there.
Or you could add a didSet property observer to landmarks itself so that updateAnnotations is called whenever it changes.

How to get nearby gas station and show direction to user with swift?

For a school project, I'm trying to get all nearby gas stations and create annotations for them and when the user click on one of these, I would like to get him the direction to go there.
this is the Maps controller that I implement by searching on internet and tutoriels:
import UIKit
import MapKit
import CoreLocation
protocol MapsControllerDelegate : class {
func mapsViewControllerDidSelectAnnotation(mapItem :MKMapItem)
}
class MapsController : UIViewController {
#IBOutlet weak var maps: MKMapView!
weak var delegate :MapsControllerDelegate!
let locationManager = CLLocationManager()
let regionInMeters: Double = 1000
override func viewDidLoad() {
super.viewDidLoad()
checkLocationServices()
}
func setupLocationManager(){
locationManager.delegate = self as! CLLocationManagerDelegate
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
func centerViewOnUserLocation(){
if let location = locationManager.location?.coordinate{
let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
maps.setRegion(region, animated: true)
}
}
func checkLocationServices(){
if CLLocationManager.locationServicesEnabled(){
//setup the location manager.
setupLocationManager()
checkLocationAuthorization()
}
else{
//Show alert let the user know how to do it.
}
}
func checkLocationAuthorization(){
switch CLLocationManager.authorizationStatus(){
case .authorizedWhenInUse:
maps.showsUserLocation = true
centerViewOnUserLocation()
locationManager.startUpdatingLocation()
case .denied:
break
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
case .restricted:
break
case .authorizedAlways:
break
}
}
func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
let annotationView = views.first!
if let annotation = annotationView.annotation {
if annotation is MKUserLocation {
centerViewOnUserLocation()
populateNearByPlaces()
}
}
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
let annotation = view.annotation as! PlaceAnnotation
self.delegate.mapsViewControllerDidSelectAnnotation(mapItem: annotation.mapItem)
}
func populateNearByPlaces(){
print("Im heeeeeerrrrreeeeeee")
if let location = locationManager.location?.coordinate{
let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = "Gas Station"
request.region = region
let search = MKLocalSearch(request: request)
search.start { (response, error) in
guard let response = response else {
return
}
for item in response.mapItems {
print("I'm here")
print(item)
let annotation = PlaceAnnotation()
annotation.coordinate = item.placemark.coordinate
annotation.title = item.name
annotation.mapItem = item
DispatchQueue.main.async {
self.maps.addAnnotation(annotation)
}
}
}
}
}
}
extension MapsController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else {return}
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion.init(center: center, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
maps.setRegion(region, animated: true)
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
checkLocationAuthorization()
}
}
}
I don't have any errors or the app stops working but I'm not getting the results expected. In the Maps scene I'm just getting the user's actual location on the map and that's it.

Why does user location in MKMapView shows latitude 0.0 and longitude 0.0?

All the questions on stack overflow that are similar to this seem to be for Java and Android.
I have the following code using a MKMapView control.
override func viewDidLoad() {
super.viewDidLoad()
mapView.showsUserLocation = true
mapView.setUserTrackingMode(.followWithHeading, animated: true)
let locationCoordinate = CLLocationCoordinate2D(latitude: mapView.userLocation.coordinate.latitude, longitude: mapView.userLocation.coordinate.longitude)
currentLocationCoordinateRegion = MKCoordinateRegion(center: locationCoordinate, latitudinalMeters: 200, longitudinalMeters: 200)
mapView.setRegion(currentLocationCoordinateRegion, animated: true)
print("latitude:", mapView.userLocation.coordinate.latitude, "longitude:", mapView.userLocation.coordinate.longitude)
}
I am using an actual device, so the map view should show my current location and the print statement should print my current location, but instead I see blue on the map view, and the print results show a latitude of 0.0 and a longitude of 0.0 in the debug window:
latitude: 0.0 longitude: 0.0
Why is it doing this and what should I do to fix this?
I also have a bar button item on a toolbar with the following code:
#IBAction func actionShow(_ sender: UIBarButtonItem) {
print("latitude:", mapView.userLocation.coordinate.latitude, "longitude:", mapView.userLocation.coordinate.longitude)
let locationCoordinate = CLLocationCoordinate2D(latitude: mapView.userLocation.coordinate.latitude, longitude: mapView.userLocation.coordinate.longitude)
currentLocationCoordinateRegion = MKCoordinateRegion(center: locationCoordinate, latitudinalMeters: 200, longitudinalMeters: 200)
mapView.setRegion(currentLocationCoordinateRegion, animated: true)
}
That yields the same results.
You must ask for permission to access user location, this is the first action you perform in viewDidLoad and then proceed to show user location once you have the permission, following UIViewController will get you going
class ViewController: UIViewController {
#IBOutlet var mapView: MKMapView!
var locationManager: CLLocationManager?
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
mapView.setUserTrackingMode(.followWithHeading, animated: true)
self.checkLocationAuthorization()
}
func checkLocationAuthorization(authorizationStatus: CLAuthorizationStatus? = nil) {
switch (authorizationStatus ?? CLLocationManager.authorizationStatus()) {
case .authorizedAlways, .authorizedWhenInUse:
mapView.showsUserLocation = true
case .notDetermined:
if locationManager == nil {
locationManager = CLLocationManager()
locationManager!.delegate = self
}
locationManager!.requestWhenInUseAuthorization()
default:
print("Location Servies: Denied / Restricted")
}
}
}
extension ViewController: MKMapViewDelegate, CLLocationManagerDelegate {
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
let region = MKCoordinateRegion(center: userLocation.coordinate, latitudinalMeters: 200, longitudinalMeters: 200)
mapView.setRegion(region, animated: true)
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
self.checkLocationAuthorization(authorizationStatus: status)
}
}
You must also include following properties in Info.plist, without these locationManager will just not proceed to request authorization.
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Message for AlwaysAndWhenInUseUsageDescription</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Message for AlwaysUsageDescription</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Message for WhenInUseUsageDescription</string>

How to change MapKit's pin color in Swift 3/4?

So, I am creating an app with MapKit. So, I need some help of changing the maps pin color from red to any color possible. I tried every way, I can't just not find a solution. Can any one check my code, and help me apply it to my code below of changing the map's pin tintColor. Thanks in advance.
Here is my code:
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
locationManager.requestWhenInUseAuthorization()
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if locations.count > 0 {
let location = locations.last!
print("Accuracy: \(location.horizontalAccuracy)")
if location.horizontalAccuracy < 100 {
manager.stopUpdatingLocation()
let span = MKCoordinateSpan(latitudeDelta: 0.014, longitudeDelta: 0.014)
let region = MKCoordinateRegion(center: location.coordinate, span: span)
mapView.region = region
let location = CLLocation(latitude: latitude, longitude: longitude)
let place = Place(location: location, reference: reference, name: name, address: address)
self.places.append(place)
let annotation = MyHome(location: place.location!.coordinate, title: place.placeName)
DispatchQueue.main.async {
self.mapView.addAnnotation(annotation)
}
}
}
}
}
}
}
}
}
MyHome CLass
import Foundation
import MapKit
class MyHome: NSObject, MKAnnotation {
let coordinate: CLLocationCoordinate2D
let title: String?
init(location: CLLocationCoordinate2D, title: String) {
self.coordinate = location
self.title = title
super.init()
}
}
MapView
fileprivate var locationManager = CLLocationManager()
fileprivate var heading: Double = 0
fileprivate var interactionInProgress = false
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)
{
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required public init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
open override func viewDidLoad()
{
super.viewDidLoad()
self.mapView.isRotateEnabled = false
if let annotations = self.annotations
{
addAnnotationsOnMap(annotations)
}
locationManager.delegate = self
}
open override func viewDidAppear(_ animated: Bool)
{
super.viewDidAppear(animated)
locationManager.startUpdatingHeading()
}
open override func viewDidDisappear(_ animated: Bool)
{
super.viewDidDisappear(animated)
locationManager.stopUpdatingHeading()
}
open func addAnnotations(_ annotations: [ARAnnotation])
{
self.annotations = annotations
if self.isViewLoaded
{
addAnnotationsOnMap(annotations)
}
}
fileprivate func addAnnotationsOnMap(_ annotations: [ARAnnotation])
{
var mapAnnotations: [MKPointAnnotation] = []
for annotation in annotations
{
if let coordinate = annotation.location?.coordinate
{
let mapAnnotation = MKPointAnnotation()
mapAnnotation.coordinate = coordinate
let text = String(format: "%#, AZ: %.0f, VL: %i, %.0fm", annotation.title != nil ? annotation.title! : "", annotation.azimuth, annotation.verticalLevel, annotation.distanceFromUser)
mapAnnotation.title = text
mapAnnotations.append(mapAnnotation)
}
}
mapView.addAnnotations(mapAnnotations)
mapView.showAnnotations(mapAnnotations, animated: false)
}
open func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading)
{
heading = newHeading.trueHeading
if(!self.interactionInProgress && CLLocationCoordinate2DIsValid(mapView.centerCoordinate))
{
let camera = mapView.camera.copy() as! MKMapCamera
camera.heading = CLLocationDirection(heading);
self.mapView.setCamera(camera, animated: false)
}
}
open func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool)
{
self.interactionInProgress = true
}
open func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool)
{
self.interactionInProgress = false
}
}
you have to change its color in MKMapViewDelegate delegate method
#IBOutlet weak var customMap: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
let anoot = MKPointAnnotation()
anoot.coordinate = CLLocationCoordinate2D.init(latitude: lat, longitude: lng)
customMap.addAnnotation(anoot)
customMap.delegate = self
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin")
annotationView.pinTintColor = UIColor.green
return annotationView
}
you can do it in your code like this
class ViewController: UIViewController {
var locationManager = CLLocationManager()
#IBOutlet weak var yourMap: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
yourMap.delegate = self
let anoot = MKPointAnnotation()
anoot.coordinate = CLLocationCoordinate2D.init(latitude: 23.0225, longitude: 72.5714)
yourMap.addAnnotation(anoot)
yourMap.delegate = self
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
locationManager.requestWhenInUseAuthorization()
}
}
extension ViewController: CLLocationManagerDelegate, MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin")
annotationView.pinTintColor = UIColor.green
return annotationView
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if locations.count > 0 {
let location = locations.last!
print("Accuracy: \(location.horizontalAccuracy)")
if location.horizontalAccuracy < 100 {
manager.stopUpdatingLocation()
let span = MKCoordinateSpan(latitudeDelta: 0.014, longitudeDelta: 0.014)
let region = MKCoordinateRegion(center: location.coordinate, span: span)
yourMap.region = region
// let location = CLLocation(latitude: latitude, longitude: longitude)
// let place = Place(location: location, reference: reference, name: name, address: address)
// self.places.append(place)
//
// let annotation = MyHome(location: place.location!.coordinate, title: place.placeName)
//
// DispatchQueue.main.async {
//
// self.mapView.addAnnotation(annotation)
// }
}
}
}
}

MapKit View not zooming in to users location

In my application I have a MKMapKit view and when my application starts, if the user allows location services, I want the Map to zoom into the user's location. The code I wrote is:
override func viewDidLoad() {
super.viewDidLoad()
mapKitView.delegate = self
mapKitView.showsUserLocation = true
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
if (CLLocationManager.locationServicesEnabled()) {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
}
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
}
DispatchQueue.main.async {
self.locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
let noLocation = CLLocationCoordinate2D()
let viewRegion = MKCoordinateRegionMakeWithDistance(noLocation, 200, 200)
mapKitView.setRegion(viewRegion, animated: false)
}
In my app, it shows the users location, but does not animate and zoom in.
Use the user's location to calculate the view region and change the animated parameter to true:
if let location = mapKitView.userLocation.location {
let viewRegion = MKCoordinateRegionMakeWithDistance(location, 200, 200)
mapKitView.setRegion(viewRegion, animated: true)
}
In Swift 3.0, try my code in your didUpdateLocation method.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
//get location cordinate
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print(locValue)
//set updating location stop
locationManager.stopUpdatingLocation()
let location = locations.last! as CLLocation//create object of CLLocation
//get location cordinate
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
//set map zooming using region
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
}
I hope it's work #Rahul Bir
In Swift 3.0 you should use this code if you want to zoom map Kit on the starting view of the map view.
var zoomIn = false
var zoomAnnotation:MKAnnotation
func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
if let annotation = zoomAnnotation where zoomIn == true {
let region = MKCoordinateRegion(center: zoomAnnotation.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.075, longitudeDelta: 0.075))
mapView.setRegion(region, animated: true)
zoomIn = false
}
}

Resources