最近公司要做一個類似與美團的東西,讓我用百度地圖來進行定位,并顯示地理信息.
那么我們要如何做呢,直接上代碼
-
先看看包結(jié)構(gòu),要把需要用到的庫都要引入進來.
注意:appdelegate.mm 后綴一定要加個m
不然的話編譯會不通過,好像是因為它的編譯原理是c++還是怎樣,要詳細(xì)了解的可以百度.
- 那么來看控制器代碼
_locService = [[BMKLocationService alloc]init];//定位功能的初始化
_locService.delegate = self;//設(shè)置代理位self
//啟動LocationService
[_locService startUserLocationService];//啟動定位服務(wù)
_geocodesearch = [[BMKGeoCodeSearch alloc] init];
//編碼服務(wù)的初始化(就是獲取經(jīng)緯度,或者獲取地理位置服務(wù))
_geocodesearch.delegate = self;//設(shè)置代理為self
這段代碼需要放在viewDidLoad里面
啟動定位服務(wù)后,_locService.userLocation.location.coordinate就應(yīng)該會有值了,也就是說經(jīng)度和緯度都可以獲取出來了.
- 開始定位的點擊事件,將剛剛定位的經(jīng)緯度取出來并設(shè)置lable的值
-(void)heheda:(UIButton *)btn{
NSLog(@"進入普通定位態(tài)");
NSLog(@"定位的經(jīng)度:%f,定位的緯度:%f",_locService.userLocation.location.coordinate.longitude,_locService.userLocation.location.coordinate.latitude);
self.lon.text = [NSString stringWithFormat:@"%f",_locService.userLocation.location.coordinate.longitude];
[self.lat setText:[NSString stringWithFormat:@"%f",_locService.userLocation.location.coordinate.latitude]];
}
- 獲取地址的點擊事件
-(void)onClickReverseGeocode //發(fā)送反編碼請求的.
{
isGeoSearch = false;
CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};//初始化
if (_locService.userLocation.location.coordinate.longitude!= 0
&& _locService.userLocation.location.coordinate.latitude!= 0) {
//如果還沒有給pt賦值,那就將當(dāng)前的經(jīng)緯度賦值給pt
pt = (CLLocationCoordinate2D){_locService.userLocation.location.coordinate.latitude,
_locService.userLocation.location.coordinate.longitude};
}
BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];//初始化反編碼請求
reverseGeocodeSearchOption.reverseGeoPoint = pt;//設(shè)置反編碼的店為pt
BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];//發(fā)送反編碼請求.并返回是否成功
if(flag)
{
NSLog(@"反geo檢索發(fā)送成功");
}
else
{
NSLog(@"反geo檢索發(fā)送失敗");
}
}
- 如果發(fā)送成功,百度將會返回東西給你,然后你可以在下面這個代理函數(shù)中處理
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
if (error == 0) {
BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
item.coordinate = result.location;
item.title = result.address;
NSString* titleStr;
NSString* showmeg;
titleStr = @"反向地理編碼";
showmeg = [NSString stringWithFormat:@"%@",item.title];
self.addr.text = showmeg;
UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:titleStr message:showmeg delegate:self cancelButtonTitle:nil otherButtonTitles:@"確定",nil];
[myAlertView show];
}
}
- 有不明白的還是可以到官網(wǎng)下載demo來看看
http://lbsyun.baidu.com/index.php?title=iossdk/sdkiosdev-download
如果喜歡請給個贊.