我有一个算法,可以计算包含一组给定坐标的地图的边界框的大小和位置。虽然它完美地工作,但它产生的界限并不总是适应我放置在坐标上的推针,它通常位于边界框的边缘:
......而且,它在大多数情况下产生了可接受的结果:
我已经仔细研究了一段时间,但我还没有想到一种方法来修改我的算法以确保推针总是在边界框内。我的算法如下所示,任何建议都将非常感谢。 :)
MKMapPoint *points = malloc([coordinates count] * sizeof(MKMapPoint));
MKMapPoint upperRightCorner;
MKMapPoint lowerLeftCorner;
for(int i = 0; i < [coordinates count]; i++)
{
CLLocation *location = [coordinates objectAtIndex:i];
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(herp.coordinate.latitude, herp.coordinate.longitude);
MKMapPoint point = MKMapPointForCoordinate(coordinate);
points[i] = point;
if (i == 0) {
upperRightCorner = point;
lowerLeftCorner = point;
}
else {
if (point.x > upperRightCorner.x) upperRightCorner.x = point.x;
if (point.y > upperRightCorner.y) upperRightCorner.y = point.y;
if (point.x < lowerLeftCorner.x) lowerLeftCorner.x = point.x;
if (point.y < lowerLeftCorner.y) lowerLeftCorner.y = point.y;
}
}
MKMapRect boundingBox = MKMapRectMake(lowerLeftCorner.x, lowerLeftCorner.y,
upperRightCorner.x - lowerLeftCorner.x,
upperRightCorner.y - lowerLeftCorner.y);
答案 0 :(得分:3)
我认为可能会迟到,但这是一个适合我的解决方案,与你的相似,我最后在最后添加了一个填充。
- (MKCoordinateRegion)boundingBoxForAnnotations:(NSArray *)annotations {
CLLocationCoordinate2D topLeftCoord;
topLeftCoord.latitude = -90;
topLeftCoord.longitude = 180;
CLLocationCoordinate2D bottomRightCoord;
bottomRightCoord.latitude = 90;
bottomRightCoord.longitude = -180;
for (id<MKAnnotation> annotation in 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;
region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1;
region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1;
return region;
}