老板最近非得整百度地图,没办法找了些资料琢磨琢磨。使用百度地图API首先要去百度官网下载API,并申请Key(按照百度官网的提示就行了)。
申请了key后,把百度的Demo下载下来,把里面的key改成刚申请的,运行下试试。(提醒下,如果写自己的程序时,编译有很多错误的话,首先看看所需要的框架是否已全部加进去了,其次选择工程->Target-> build settings -> Linking -> other linker flags 添加-all_load)
定位主要用到的是BMKMapView委托的函数-(void)mapView:(BMKMapView *)mapView didUpdateLocation:(BMKUserLocation *)userLocation,通过这个函数可以获取到用户的当前经纬度。
可能经纬度并不能满足大家的要求,而是希望直接看到自己的位置是什么地名。这就要用到BMKSerarc的委托类BMKSearchDelegate,先调用BMKSerach的reverseGeocode函数,然后在BMKSearchDelegate的-(void) onGet
AddrResult: (BMKAddrInfo *)result errorCode: (int)error函数中获得结果。
以下贴几段关键代码:
- (void)mapView:(BMKMapView *)mapView didUpdateUserLocation:(BMKUserLocation *)userLocation
{
localLatitude = userLocation.coordinate.latitude; //保存获取的经纬度
localLongitude = userLocation.coordinate.longitude;
if (userLocation != nil)
{
NSLog(@"%f %f", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
}
[_mapView setCenterCoordinate:userLocation.coordinate animated:YES]; //使地图移动到定位的地方
BOOL flag = [_search reverseGeocode:pt]; //反地理编码 自动调用下面的委托函数获取结果
if (!flag) {
NSLog(@"search failed!");
}
}
- (void)onGetAddrResult:(BMKAddrInfo *)result errorCode:(int)error
{
NSLog(@"%@",result.strAddr);
cityStr = result.addressComponent.streetName; //得到的街道名称
cityStreetName = result.addressComponent.city; //所在城市名称
NSLog(@"%@",cityStreetName);
NSLog(@"%@",cityStr);
NSLog(@"%@",result.addressComponent.streetNumber); //输出所在城市街道门牌号
}
百度地图还是很强大的,现在仅仅是管中窥豹而已,后面继续添加功能。