在地圖上標注很多點之后,地圖的中心點可以設置,但是縮放級別用起來就有點囧了,
所以,就需要根據坐標數據點所在的坐標區域來動態計算,把所有點都剛好顯示到地圖的可視范圍內。
直接上代碼:
//清理坐標數據的視圖和數據 [_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];
最后來張效果圖:
新聞熱點
疑難解答