Showing Specific Region Using MapKit

风格不统一 提交于 2019-11-26 20:45:56

问题


I want to know is it possible to show only specific region on map not the full world map using Map Kit. Like if i want to show Asia map in my application then map kit hides remaining part of the map.


回答1:


To handle the "map kit hides remaining part of the map" requirement, one thing you can do is create a black polygon overlay that covers the whole world with a cutout over Asia (or wherever you like).

For example, where you initialize the map (eg. in viewDidLoad):

CLLocationCoordinate2D asiaCoords[4] 
    = { {55,60}, {55,150}, {0,150}, {0,60} };
      //change or add coordinates (and update count below) as needed 
self.asiaOverlay = [MKPolygon polygonWithCoordinates:asiaCoords count:4];

CLLocationCoordinate2D worldCoords[4] 
    = { {90,-180}, {90,180}, {-90,180}, {-90,-180} };
MKPolygon *worldOverlay 
    = [MKPolygon polygonWithCoordinates:worldCoords 
                 count:4 
                 interiorPolygons:[NSArray arrayWithObject:asiaOverlay]];
                   //the array can have more than one "cutout" if needed

[myMapView addOverlay:worldOverlay];

and implement the viewForOverlay delegate method:

-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay
{
    if ([overlay isKindOfClass:[MKPolygon class]])
    {
        MKPolygonView *pv = [[[MKPolygonView alloc] initWithPolygon:overlay] autorelease];
        pv.fillColor = [UIColor blackColor];
        pv.alpha = 1.0;
        return pv;
    }

    return nil;
}

This looks like this:

If you also want to restrict the user from scrolling beyond Asia or zooming too far out, then you'll need to do that manually as well. One possible way is described in Restrict MKMapView scrolling. Replace theOverlay in that answer with asiaOverlay.




回答2:


You can specify the region as an MKCoordinateRegion and then tell an MKMapView instance to only show that region using the setRegion and regionThatFits message.

Alternatively you could use the visibleMapRect property instead of the region. This might better fit your needs.

In short read the MKMapView Class Reference document from Apple.

Lifting from some code I've done in the past that assumes a mapView and a given location called locationToShow I used an MKCoordinateRegion.

- (void) goToLocation {

    MKCoordinateRegion region;
    MKCoordinateSpan span;
    span.latitudeDelta=0.01;
    span.longitudeDelta=0.01;

    region.span=span;
    region.center=locationToShow;
    [mapView setRegion:region animated:TRUE];
    [mapView regionThatFits:region];
}


来源:https://stackoverflow.com/questions/8679499/showing-specific-region-using-mapkit

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