我使用以下代码在地图上显示我的所有注释:
MKMapRect zoomRect = MKMapRectNull;
for (id <MKAnnotation> annotation in mapView.annotations)
{
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 1000);
if (MKMapRectIsNull(zoomRect)) {
zoomRect = pointRect;
} else {
zoomRect = MKMapRectUnion(zoomRect, pointRect);
}
}
[mapView setVisibleMapRect:zoomRect animated:YES];但我的地图应用程序上也有一个“我的位置”按钮,当按下它时,它会显示我自己的位置。
如何将我的位置添加到MKMapRect中,以便它显示所有注释以及我自己的位置?
发布于 2011-12-12 02:08:08
您可以使用[myMapView setShowsUserLocation: YES];来显示用户的位置(我假设它是"my location“,并且您将地图视图命名为"myMapView")。
这将显示蓝点,就像地图应用程序一样。但是,它不会更改视图。
通过创建和设置跨越所有注释的最大和最小经度和纬度的新区域,可以使视图重新居中,以便所有注释都可见。代码应该是这样的。
// Get all the coordinates
NSArray *coordinates = [myMapView valueForKeyPath:@"annotations.coordinate"];
// Longitude and latitude max and min
CLLocationCoordinate2D maxCoord = {-90.0f, -180.0f};
CLLocationCoordinate2D minCoord = {90.0f, 180.0f};
for(NSValue *value in coordinates) {
CLLocationCoordinate2D coord = {0.0f, 0.0f};
// Unpack the NSValue to get the CLLocationCoordinate2D struct inside
[value getValue:&coord];
// Update max and min to
if(coord.longitude > maxCoord.longitude) {
maxCoord.longitude = coord.longitude;
}
if(coord.latitude > maxCoord.latitude) {
maxCoord.latitude = coord.latitude;
}
if(coord.longitude < minCoord.longitude) {
minCoord.longitude = coord.longitude;
}
if(coord.latitude < minCoord.latitude) {
minCoord.latitude = coord.latitude;
}
}
// Create a new region that covers all the annotations
MKCoordinateRegion region = {{0.0f, 0.0f}, {0.0f, 0.0f}};
region.center.longitude = (minCoord.longitude + maxCoord.longitude) / 2.0;
region.center.latitude = (minCoord.latitude + maxCoord.latitude) / 2.0;
region.span.longitudeDelta = (maxCoord.longitude - minCoord.longitude);
region.span.latitudeDelta = (maxCoord.latitude - minCoord.latitude);
region = [myMapView regionThatFits:region];
// Animate to the new region
[myMapView setRegion:region animated:YES]; 这是因为蓝色的用户位置点也是一个注释。因此,您可能需要更新注解代码的视图来说明这一点,例如。
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
MKAnnotationView *view = nil;
if (annotation != mapView.userLocation) {
// Your code here...
}
return view;
}但是,这不会随着用户位置的更新而更新。您将需要自己调用更新地图区域的代码。您可以仅在用户点击"My Location“按钮时执行此操作,也可以在用户移动足够多时使用Core Location获取事件。根据应用程序的不同,用户每次移动几百米时更新地图区域都会消耗大量的电池,而且可能是过度杀伤力。
https://stackoverflow.com/questions/8463867
复制相似问题