Showing Specific Region Using MapKit

后端 未结 2 598
谎友^
谎友^ 2020-12-05 22:07

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

相关标签:
2条回答
  • 2020-12-05 22:27

    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:

    enter image description here

    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.

    0 讨论(0)
  • 2020-12-05 22:35

    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];
    }
    
    0 讨论(0)
提交回复
热议问题