這次碰到的問題是根據云檢索,獲取到了很多組大頭針數據,并將它們在地圖上顯示。然后有時候我們的搜索條件會致使大頭針的數量不同,那么它在地圖上的分布就應該以所有大頭針都能包括的區域而動態改變地圖的等級。研究了下,發現了跟這個類有關系BMKCoordinateRegion。廢話不多說,上代碼~
在本地云檢索的代理方法onGetCloudPoiResult中,我們檢索大頭針的個數的常用代碼如下:
if (error == BMKErrorOk) {
BMKCloudPOIList* result = [poiResultList objectAtIndex:0];
NSLog(@"1111111");
for (int i = 0; i < result.POIs.count; i++) {
BMKCloudPOIInfo* poi = [result.POIs objectAtIndex:i];
BMKPointAnnotation* item = [[BMKPointAnnotation alloc] init];
CLLocationCoordinate2D pt = (CLLocationCoordinate2D){ poi.longitude,poi.latitude};
item.coordinate = pt;
item.title = poi.title;
[_mapView addAnnotation:item];
......//下面還有點,都是常見的,這里不寫了,這不是重點
}
一般如上代碼,我們可以得到我們需要在地圖上插得所有大頭針。我們既然要讓地圖按照大頭針的分布來自動縮放地圖,那么就得知道這么多大頭針中經緯度最大的和最小的,然后取個中點,就像矩形那樣,得到中間點,就好辦了~~~
思路:
我們可以創建兩個可變數組,用來分別存放所有的經度和緯度,然后取出最大的和最小的經緯度。OC中一個簡單的方法:[array valueForKeyPath:@"@min.floatValue"]] 取出數組中最小的,[array valueForKeyPath:@"@max.floatValue"]] 取出數組中最大的。
得到中心點后,要根據region的范圍,來顯示合適的視角。我下面寫的是0.06,大家可以根據自己需要調整,數字越小地圖等級越大,合適的就行了。
最后通過方法 region = [_mapView regionThatFits:region];
[_mapView setRegion:region animated:YES];
代碼如下:
if (error == BMKErrorOk) {
//創建兩個數組,用來存所有的經度和緯度
NSMutableArray *latArr = [[NSMutableArray alloc] init];
NSMutableArray *lonArr = [[NSMutableArray alloc] init];
BMKCloudPOIList* result = [poiResultList objectAtIndex:0];
NSLog(@"1111111");
for (int i = 0; i < result.POIs.count; i++) {
BMKCloudPOIInfo* poi = [result.POIs objectAtIndex:i];
BMKPointAnnotation* item = [[BMKPointAnnotation alloc] init];
CLLocationCoordinate2D pt = (CLLocationCoordinate2D){ poi.longitude,poi.latitude};
item.coordinate = pt;
item.title = poi.title;
//用經緯度數組分別存儲所有的經緯度
[latArr addObject:@(pt.latitude)];
[lonArr addObject:@(pt.longitude)];
[_mapView addAnnotation:item];
}
NSNumber *latMax = [latArr valueForKeyPath:@"@max.floatValue"];//最大緯度
NSNumber *latMin = [latArr valueForKeyPath:@"@min.floatValue"];//最小緯度
NSNumber *lonMax = [lonArr valueForKeyPath:@"@max.floatValue"];//最大經度
NSNumber *lonMin = [lonArr valueForKeyPath:@"@min.floatValue"];//最小經度
BMKCoordinateRegion region;
region.center.latitude = ([latMax doubleValue] + [latMin doubleValue]) / 2;
region.center.longitude = ([lonMax doubleValue] + [lonMin doubleValue]) / 2;
region.span.latitudeDelta = 0.06;
region.span.longitudeDelta = 0.06;
region = [_mapView regionThatFits:region];
[_mapView setRegion:region animated:YES];
NSLog(@"lat == %f, lon == %f, min1 == %f, min2 == %f", [latMax doubleValue], [latMin doubleValue], [lonMax doubleValue], [lonMin doubleValue]);
NSLog(@"2222222");
} else {
NSLog(@"error ==%d",error);
if (error == BMKErrorConnect) {
[Tool HUDShowAddedTo:self.view withTitle:@"網絡連接錯誤" delay:1.5];
} else if (error == BMKErrorResultNotFound) {
[Tool HUDShowAddedTo:self.view withTitle:@"搜索結果未找到" delay:1.5];
} else {
[Tool HUDShowAddedTo:self.view withTitle:@"檢索失敗" delay:1.5];
}
}
最后給看官們大致看一下效果圖
Paste_Image.png
地圖自動根據大頭針個數縮放~~
如果對百度地圖不了解的童鞋,可以看我這篇文章,http://www.lxweimin.com/p/19f960054fd0