How to suppress the “Current Location” callout in map view

若如初见. 提交于 2019-12-03 10:37:47
jowie

There's a property on the annotation view you can change, once the user location has been updated:

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    MKAnnotationView *userLocationView = [mapView viewForAnnotation:userLocation];   
    userLocationView.canShowCallout = NO;
}    

You can set the title to blank to suppress the callout:

mapView.userLocation.title = @"";


Edit:
A more reliable way might be to blank the title in the didUpdateUserLocation delegate method:

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    userLocation.title = @"";
}

or in viewForAnnotation:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>) annotation
{
    if ([annotation isKindOfClass:[MKUserLocation class]])
    {
        ((MKUserLocation *)annotation).title = @"";
        return nil;
    }

    ...
}

Setting the title in the delegate methods lets you be certain you have a real userLocation instance to work with.

Swift 4

// MARK: - MKMapViewDelegate

func mapViewDidFinishLoadingMap(_ mapView: MKMapView) {
    if let userLocationView = mapView.view(for: mapView.userLocation) {
        userLocationView.canShowCallout = false
    }
}

Swift 4 - Xcode 9.2 - iOS 11.2

// MARK: - MKMapViewDelegate

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
  if let userLocation = annotation as? MKUserLocation {
    userLocation.title = ""
    return nil
  }
  // ...
}

SWIFT Version

We need to set the user MKAnnotationView property canShowCallout to false when mapView adds the user MKAnnotationView

func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
    for view in views {
        if view.annotation is MKUserLocation {
            view.canShowCallout = false
        }
    }
}

I have two ways to help you:

  1. suppress in the mapViewDidFinishLoadingMap

    func mapViewDidFinishLoadingMap(_ mapView: MKMapView) {
    mapView.showsUserLocation = true
    //suppress the title
    mapView.userLocation.title = "My Location"
    //suppress other params
    

    }

  2. suppress in the didUpdate

    func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
        //suppress the title
        mapView.userLocation.title = "My Location"
        //suppress other params
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!