在地图上标注很多点之后,地图的中心点可以设置,但是缩放级别用起来就有点囧了,
所以,就需要根据坐标数据点所在的坐标区域来动态计算,把所有点都刚好显示到地图的可视范围内。
直接上代码:
//清理坐标数据的视图和数据 [_bMapView removeAnnotations:_mapAnnotations]; [_mapAnnotations removeAllObjects]; [_carPointArray removeAllObjects]; //声明解析时对坐标数据的位置区域的筛选,包括经度和纬度的最小值和最大值 CLLocationDegrees minLat; CLLocationDegrees maxLat; CLLocationDegrees minLon; CLLocationDegrees maxLon; //解析数据 for (int i=0; i<rows.count; i++) { NSDictionary *row = [rows objectAtIndex:i]; 坐标模型类 *item = [[坐标模型类 alloc] initWithJson:row]; if (item.vehicleNo && [item.vehicleNo length]>0) { 标注模型类 *annotation = [[标注模型类 alloc] init]; annotation.coordinate = item.baiduCoordinate; annotation.item = item; [_mapAnnotations addObject:annotation]; [_bMapView addAnnotation:annotation]; [annotation release]; if (i==0) { //以第一个坐标点做初始值 minLat = item.baiduCoordinate.latitude; maxLat = item.baiduCoordinate.latitude; minLon = item.baiduCoordinate.longitude; maxLon = item.baiduCoordinate.longitude; }else{ //对比筛选出最小纬度,最大纬度;最小经度,最大经度 minLat = MIN(minLat, item.baiduCoordinate.latitude); maxLat = MAX(maxLat, item.baiduCoordinate.latitude); minLon = MIN(minLon, item.baiduCoordinate.longitude); maxLon = MAX(maxLon, item.baiduCoordinate.longitude); } [_carPointArray addObject:item]; } [item release]; } //动态的根据坐标数据的区域,来确定地图的显示中心点和缩放级别 if (_carPointArray.count > 0) { //计算中心点 CLLocationCoordinate2D centCoor; centCoor.latitude = (CLLocationDegrees)((maxLat+minLat) * 0.5f); centCoor.longitude = (CLLocationDegrees)((maxLon+minLon) * 0.5f); BMKCoordinateSpan span; //计算地理位置的跨度 span.latitudeDelta = maxLat - minLat; span.longitudeDelta = maxLon - minLon; //得出数据的坐标区域 BMKCoordinateRegion region = BMKCoordinateRegionMake(centCoor, span); //百度地图的坐标范围转换成相对视图的位置 CGRect fitRect = [_bMapView convertRegion:region toRectToView:_bMapView]; //将地图视图的位置转换成地图的位置 BMKMapRect fitMapRect = [_bMapView convertRect:fitRect toMapRectFromView:_bMapView]; //设置地图可视范围为数据所在的地图位置 [_bMapView setVisibleMapRect:fitMapRect animated:YES]; }
补充:
MKMapRect zoomRect = MKMapRectNull; for (id <MKAnnotation> annotation in mapView.annotations) { MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate); MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0); if (MKMapRectIsNull(zoomRect)) { zoomRect = pointRect; } else { zoomRect = MKMapRectUnion(zoomRect, pointRect); } } [mapView setVisibleMapRect:zoomRect animated:YES];
最后来张效果图: