Map View always center map on my location

谁说我不能喝 提交于 2019-12-19 04:26:12

问题


I use the following code to get my location when a user presses a button

 [mapview setShowsUserLocation:YES];

and then the follwoing to center the map to te user's location

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation      
{
   [mapView setCenterCoordinate:mapView.userLocation.location.coordinate animated:YES];
} 

My question is how to prevent the map from always centering on my location? I want to allow the user to pan the map.


回答1:


I think it came in with iOS5, you can now drop the delegate stuff and just set the userTrackingMode of the MKMapView. Set it to MKUserTrackingModeFollow to make the make move along with the user and then when they start panning the map around it'll turn off the tracking mode automatically, you then just need to provide a button to turn it back on.




回答2:


Center on the location only the first time you show the map. Here is some pseudo code...

    - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation      
    {

       if(shouldCenterLocation){
           [mapView setCenterCoordinate:mapView.userLocation.location.coordinate animated:YES];
           shouldCenterLocation = FALSE;

        }
        //do all your other stuff here
    }

shouldCenterLocation is a boolean flag that you can set to TRUE the first time the map is shown, then set it to FALSE until you exit the view (or any other condition you have for showing the center location).

edit: you can toggle the state of shouldCenterLocation in the same method that you handle the button press.




回答3:


On swift 3 I prefer use animated method:

mapView.setUserTrackingMode(.follow, animated: true)

but set property good worked:

mapView.userTrackingMode = .follow


来源:https://stackoverflow.com/questions/9637737/map-view-always-center-map-on-my-location

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!