在地圖上標註很多點之後,地圖的中心點可以設定,但是縮放層級用起來就有點囧了,
所以,就需要根據座標資料點所在的座標地區來動態計算,把所有點都剛好顯示到地圖的可視範圍內。
直接上代碼:
//清理座標資料的視圖和資料 [_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];
最後來張: