开发者

iPhone Map Region Weirdness

iPhone Map Region Weirdness

The attached image is what happens开发者_运维百科 sometimes when I try to size a MKMapView to fit one or more placemarks. It's intermittent, but the display is always in exactly the same position.

Here is the code:

 // loc1 is always non-null, and is equal to one of the annotation locations

CLLocationCoordinate2D topLeftCoord = loc1.coordinate;
CLLocationCoordinate2D bottomRightCoord = loc1.coordinate;
for(UserPlacemark* annotation in self.mapView.annotations)
{
    topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
    topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);     
    bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
    bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
}

MKCoordinateRegion region;
double k = 0.01;
region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.25;
region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
region.span.latitudeDelta = k + fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.25; // Add a little extra space on the sides
region.span.longitudeDelta = k + fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.5; // Add a little extra space on the sides

 // only zoom if region doesn't fit, or too small
 CGRect newRect = [mapView convertRegion:region toRectToView:mapView];
 double MIN_SIZE_PIXELS = 50.0;
 double rectSizePixels = newRect.size.width+newRect.size.height;
 if (!CGRectContainsRect(mapView.bounds, newRect) || rectSizePixels < MIN_SIZE_PIXELS)
 {
      region = [mapView regionThatFits:region];
      [mapView setRegion:region animated:TRUE];
 }


The problem in the above code is that a MKUserAnnotation instance is placed in the placemark list by the Map framework. This does not always correspond with the user's actual position, at least in the simulator.

It's better to avoid iterating over the annotations list and instead compute the min/max boundaries of your placemark using your objects directly.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜