以前接触过百度地图,只是一些简单的基础地图,按照它给的Demo来自己重新实现一下。最近在做一个东西,需要从服务器中获取相应的点,这些点是有详情、经纬度和具体描述的,然后在地图上面用大头针显示出来。我是参照着网上的一个视频教程来改的。
1 显示地图
mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,SCREEN_HEIGHT)];
[self.view addSubview:mapView];
因为服务器传过来的数据相隔的比较近,所以用下面几行代码来约束一下经纬度的跨度范围,这样可以不会使大头针都重叠在一起。
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(30.446191, 114.271598);
BMKCoordinateSpan span = BMKCoordinateSpanMake(0.038325, 0.028045);
mapView.limitMapRegion = BMKCoordinateRegionMake(center, span);////限制地图显示范围
mapView.rotateEnabled = NO;//禁用旋转手势
2 定位
把自己的位置也显示在地图中。
- (void) startLocation
{
[locService startUserLocationService];
locService.distanceFilter = 10;
mapView.showsUserLocation = YES;
}
#pragma mark - BMKLocationService代理方法
- (void)willStartLocatingUser
{
NSLog(@"开始定位");
}
- (void)didFailToLocateUserWithError:(NSError *)error
{
NSLog(@"定位失败%@",error);
}
//定位成功,再次定位方法
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
//完成地理反编码
BMKReverseGeoCodeOption *reverseOption = [[BMKReverseGeoCodeOption alloc] init];
reverseOption.reverseGeoPoint = userLocation.location.coordinate;
//执行反向地理编码操作
[getCodeSearch reverseGeoCode:reverseOption];
}
#pragma mark - BMKGeoCodeSearch 代理方法
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc] init];
annotation.coordinate = result.location;
annotation.title = @"当前位置";
annotation.subtitle = result.address;
[mapView addAnnotation:annotation];
//使地图显示该位置
[mapView setCenterCoordinate:result.location animated:YES];
}
其中用到了反编码的使用方法,当定位成功后,就会获取当前位置的经纬度,然后用反编码方法来反编译出此时的地理位置,然后再把大头针标注在地图上面。
3 显示服务器传来的数据
- (void)addAnnotations
{
for (int i=0; i < _totalArray.count; i++) {
_abc.latitude = [[_totalArray[i] objectForKey:@"latitude"] doubleValue];
_abc.longitude = [[_totalArray[i] objectForKey:@"longitude"] doubleValue];
BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc] init];
annotation.coordinate = _abc;
annotation.title = [_totalArray[i] objectForKey:@"name"];
[mapView addAnnotation:annotation];
//使地图显示该位置
[mapView setCenterCoordinate:_abc animated:YES];
}
}
我把服务器中传来的数据放到了totalArray这个数组中,然后添加大头针的时候就直接从这个数组中读取数据,然后显示在地图上面。