开发者

Go to/zoom to current location function (MapKit)

开发者 https://www.devze.com 2023-03-27 20:51 出处:网络
I\'ve got a mapView which zooms to the current location using viewDidLoad : #define METERS_PER_MILE 1609.344

I've got a mapView which zooms to the current location using viewDidLoad :

#define METERS_PER_MILE 1609.344

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];

    mapView.showsUserLocation=TRUE;

    // zoom to  a specific area
    CLLocationCoordinate2D zoomLocation;
    zoomLocation.latitude = -28.994167;
    zoomLocation.longitude = 134.866944;

    MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 1900*METERS_PER_MILE开发者_如何学C, 1900*METERS_PER_MILE);
    MKCoordinateRegion adjustedRegion = [mapView regionThatFits:viewRegion];    

    // make sure the Google water mark is always visible
    mapView.autoresizingMask =
    (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);

    [mapView setRegion:adjustedRegion animated:YES];        

    mapView.delegate=self;

    searchBar.delegate = self;
}

This works fine. I've added a search bar and a function to jump to a specific address location. This works fine, too. I now want to add a button to jump back to the current location. Can you give me a hand, please?

Cheers


You need to set the center of your map to the current location on tap of that button. Say, like this:

- (IBAction)showCurrentLocation {        
    [mapView setCenterCoordinate:mapView.userLocation.location.coordinate animated:YES];
}


you can also try:

mapView.userTrackingMode=YES;
mapView.userTrackingMode=NO;


You can link this IBAction to your UIButton, it's going to move the map on the current location and zoom on it.

@IBOutlet weak var mapView: MKMapView!

@IBAction func zoomToUserCurrentLocation(sender: AnyObject) {
    if self.mapView != nil {
        self.mapView.setRegion(MKCoordinateRegionMake(
            self.mapView.userLocation.coordinate, 
            MKCoordinateSpanMake(0.1, 0.1)
        ), animated: true)
    }
}

MKCoordinateSpan defines the area spanned by a map region, smaller these values are, closer you zoom on the map.


- (void)showCurrentLocation{

    MKMapPoint annotationPoint = MKMapPointForCoordinate(self.mapView.userLocation.coordinate);
    MKMapRect zoomRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.0, 0.0);
    [self.mapView setVisibleMapRect:zoomRect animated:YES];
}


FOR SWIFT

Add this line in button action yourMKMapView.setUserTrackingMode(.follow, animated: true)

make sure you add yourMKMapView.showsUserLocation = true in viewDidLoad()

0

精彩评论

暂无评论...
验证码 换一张
取 消