1.閱讀百度地圖官方文檔
2.配置調(diào)用百度地圖的環(huán)境
3.實現(xiàn)地圖的調(diào)用
4.下面的代碼主要實現(xiàn)了傳入省市,能定位到選擇的省市區(qū)域 ,可設置蒙版,然后點擊地圖上的一個建筑物能拿到點擊的地理位置。
5.得到的就是選擇的地址。
NSString *address = [NSString stringWithFormat:@"%@%@",self.addressText,self.addressText1];
代碼
// 百度地圖
// 要使用百度地圖,請先啟動BaiduMapManager
_mapManager = [[BMKMapManager alloc]init];
// 如果要關注網(wǎng)絡及授權(quán)驗證事件,請設定 generalDelegate參數(shù)
BOOL ret = [_mapManager start:BaiduAppKey generalDelegate:nil];
if (!ret) {
NSLog(@"manager start failed!");
}
@interface LogingMapViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate,BMKDistrictSearchDelegate,BMKGeoCodeSearchDelegate>
{
BMKLocationService * _locService;
}
@property (nonatomic,strong)NSString *cityText;//傳入地圖的省
@property (nonatomic,strong)NSString *provinceText;//傳入地圖的市
@property (nonatomic, strong) BMKMapView *mapView; // 地圖
@property (nonatomic, strong) BMKLocationService *locService; // 位置
@property (nonatomic, strong) BMKDistrictSearch *districtSearch; // 檢索
@property (nonatomic, strong) BMKPointAnnotation *pointAnnotation;
@property (nonatomic, strong) BMKReverseGeoCodeOption *reGeo;
@property (nonatomic, strong) BMKGeoCodeSearch *searchAddress;
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[_mapView viewWillAppear];
_mapView.delegate = self;
_districtSearch.delegate = self; // 此處記得不用的時候需要置nil,否則影響內(nèi)存的釋放
}
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[_mapView viewWillDisappear];
_mapView.delegate = nil;
_districtSearch.delegate = nil; // 不用時,置nil
}
#pragma mark ****************百度地圖相關****************```
- (void)setupMapView
{
/* 地圖 */
_mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(20 *kScale, 230 *kScale, 710 *kScale, 784 *kScale)];
[self.view addSubview:_mapView];
// _mapView.mapType = BMKMapTypeNone;
_mapView.showMapScaleBar = YES;//顯示比例尺
_mapView.zoomLevel=17;//地圖顯示的級別
/* 檢索 */
//適配ios7
if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0)) {
// self.edgesForExtendedLayout=UIRectEdgeNone;
self.navigationController.navigationBar.translucent = NO;
}
_districtSearch = [[BMKDistrictSearch alloc] init];
/* 位置 */
_locService = [[BMKLocationService alloc]init];
_locService.delegate = self;
_searchAddress = [[BMKGeoCodeSearch alloc] init];
_searchAddress.delegate = self;
}
/**
*用戶位置更新后,會調(diào)用此函數(shù)
*@param userLocation 新的用戶位置
*/
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
BMKCoordinateRegion region;
region.center.latitude = userLocation.location.coordinate.latitude;
region.center.longitude = userLocation.location.coordinate.longitude;
region.span.latitudeDelta = 0;
region.span.longitudeDelta = 0;
JMLog(@"當前的坐標是:%f,%f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
[_mapView updateLocationData:userLocation];
[_locService stopUserLocationService];//取消定位 這個一定要寫,不然無法移動定位了
_mapView.centerCoordinate = userLocation.location.coordinate;
JMLog(@" _mapView.centerCoordinate------%f-----%f", _mapView.centerCoordinate.latitude, _mapView.centerCoordinate.longitude);
if (_messageView == nil && _locationView == nil) {
}
}
/** ==================================標注======================================== **/
/**
*點中底圖空白處會回調(diào)此接口
*@param mapView 地圖View
*@param coordinate 空白處坐標點的經(jīng)緯度
*/
-(void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate
{
NSLog(@"onClickedMapBlank-latitude==%f,longitude==%f",coordinate.latitude,coordinate.longitude);
NSString* showmeg = [NSString stringWithFormat:@"您點擊了地圖空白處(blank click).\r\n當前經(jīng)度:%f,當前緯度:%f,\r\nZoomLevel=%d;RotateAngle=%d;OverlookAngle=%d", coordinate.longitude,coordinate.latitude,(int)_mapView.zoomLevel,_mapView.rotation,_mapView.overlooking];
// 點擊之前刪除所有標注
NSArray * arrAnimation = [[NSArray alloc] initWithArray:_mapView.annotations];
[_mapView removeAnnotations:arrAnimation];
// 取消編輯
// [_cityTF resignFirstResponder];
// [_provinceTF resignFirstResponder];
// 添加標注
[self addPointAnnotation:coordinate];
}
/**
* 點擊地圖上面建筑物標記事件,有建筑物的位置點擊事件
*/
-(void)mapView:(BMKMapView *)mapView onClickedMapPoi:(BMKMapPoi *)mapPoi
{
self.addressText1 = mapPoi.text;
JMLog(@"點擊onClickedMapPoi---%@",mapPoi.text);
CLLocationCoordinate2D coordinate = mapPoi.pt;
// 點擊之前刪除所有標注
NSArray * arrAnimation = [[NSArray alloc] initWithArray:_mapView.annotations];
[_mapView removeAnnotations:arrAnimation];
//添加標注
[self addPointAnnotation:coordinate];
}
#pragma mark 添加標注
-(void)addPointAnnotation:(CLLocationCoordinate2D)coordinate
{
// 添加一個PointAnnotation
_pointAnnotation = [[BMKPointAnnotation alloc]init];
CLLocationCoordinate2D coor;
coor.latitude = coordinate.latitude;
coor.longitude = coordinate.longitude;
_pointAnnotation.coordinate = coor;
_pointAnnotation.title = @"地址:";
[_mapView addAnnotation:_pointAnnotation];
///反geo檢索信息類
_reGeo = [[BMKReverseGeoCodeOption alloc]init];
_reGeo.reverseGeoPoint = coor;
[_searchAddress reverseGeoCode:_reGeo];
BOOL flag = [_searchAddress reverseGeoCode:_reGeo];
if (!flag) {
NSLog(@"search failed!");
}
}
/** ==================================檢索======================================== **/
#pragma mark ************點擊檢索***************
- (void)clickdistrictSearch
{
[self.view endEditing:YES];
BMKDistrictSearchOption *option = [[BMKDistrictSearchOption alloc] init];
// 傳入檢索條件 省市text
option.city = _provinceText;
option.district = _cityText;
BOOL flag = [_districtSearch districtSearch:option];
if (flag) {
NSLog(@"district檢索發(fā)送成功");
} else {
NSLog(@"district檢索發(fā)送失敗");
}
}
/**
*返回行政區(qū)域搜索結(jié)果
*@param searcher 搜索對象
*@param result 搜索結(jié)BMKDistrictSearch果
*@param error 錯誤號,@see BMKSearchErrorCode
*/
- (void)onGetDistrictResult:(BMKDistrictSearch *)searcher result:(BMKDistrictResult *)result errorCode:(BMKSearchErrorCode)error {
NSLog(@"onGetDistrictResult error: %d", error);
NSArray *overlayArray = [NSArray arrayWithArray:_mapView.overlays];
[_mapView removeOverlays:overlayArray];
if (error == BMK_SEARCH_NO_ERROR) {
NSLog(@"\nname:%@\ncode:%d\ncenter latlon:%lf,%lf", result.name, (int)result.code, result.center.latitude, result.center.longitude);
BOOL flag = YES;
for (NSString *path in result.paths) {
BMKPolygon* polygon = [self transferPathStringToPolygon:path];
if (polygon) {
[_mapView addOverlay:polygon]; // 添加overlay
if (flag) {
[self mapViewFitPolygon:polygon];
flag = NO;
}
}
}
}
}
#pragma mark - ***********設置選中地的蒙版*********** 可注釋掉
//- (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)overlay
//{
// if ([overlay isKindOfClass:[BMKPolygon class]]) {
// BMKPolygonView *polygonView = [[BMKPolygonView alloc] initWithOverlay:overlay];
// polygonView.strokeColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.6];
// polygonView.fillColor = [UIColor colorWithRed:1 green:1 blue:0 alpha:0.4];
// polygonView.lineWidth = 1;
// polygonView.lineDash = YES;
// return polygonView;
// }
// return nil;
//}
//根據(jù)polygone設置地圖范圍
- (void)mapViewFitPolygon:(BMKPolygon *) polygon {
CGFloat leftTopX, leftTopY, rightBottomX, rightBottomY;
if (polygon.pointCount < 1) {
return;
}
BMKMapPoint pt = polygon.points[0];
// 左上角頂點
leftTopX = pt.x;
leftTopY = pt.y;
// 右下角頂點
rightBottomX = pt.x;
rightBottomY = pt.y;
for (int i = 1; i < polygon.pointCount; i++) {
BMKMapPoint pt = polygon.points[i];
leftTopX = pt.x < leftTopX ? pt.x : leftTopX;
leftTopY = pt.y < leftTopY ? pt.y : leftTopY;
rightBottomX = pt.x > rightBottomX ? pt.x : rightBottomX;
rightBottomY = pt.y > rightBottomY ? pt.y : rightBottomY;
}
BMKMapRect rect;
rect.origin = BMKMapPointMake(leftTopX, leftTopY);
rect.size = BMKMapSizeMake(rightBottomX - leftTopX, rightBottomY - leftTopY);
UIEdgeInsets padding = UIEdgeInsetsMake(30, 0, 100, 0);
BMKMapRect fitRect = [_mapView mapRectThatFits:rect edgePadding:padding];
[_mapView setVisibleMapRect:fitRect];
}
- (BMKPolygon*)transferPathStringToPolygon:(NSString*) path {
if (path == nil || path.length < 1) {
return nil;
}
NSArray *pts = [path componentsSeparatedByString:@";"];
if (pts == nil || pts.count < 1) {
return nil;
}
BMKMapPoint *points = new BMKMapPoint[pts.count];
NSInteger index = 0;
for (NSString *ptStr in pts) {
if (ptStr && [ptStr rangeOfString:@","].location != NSNotFound) {
NSRange range = [ptStr rangeOfString:@","];
NSString *xStr = [ptStr substringWithRange:NSMakeRange(0, range.location)];
NSString *yStr = [ptStr substringWithRange:NSMakeRange(range.location + range.length, ptStr.length - range.location - range.length)];
if (xStr && xStr.length > 0 && [xStr respondsToSelector:@selector(doubleValue)]
&& yStr && yStr.length > 0 && [yStr respondsToSelector:@selector(doubleValue)]) {
points[index] = BMKMapPointMake(xStr.doubleValue, yStr.doubleValue);
index++;
}
}
}
BMKPolygon *polygon = nil;
if (index > 0) {
polygon = [BMKPolygon polygonWithPoints:points count:index];
}
delete [] points;
return polygon;
}
/** ==================================街道======================================== **/
#pragma mark 根據(jù)經(jīng)緯度返回點擊的位置的名稱
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
// 得到點擊的位置
JMLog(@"%@",result.address);
self.addressText = result.address;
_pointAnnotation.subtitle = result.address;
// UIAlertController * alert = [UIAlertController alertControllerWithTitle:result.address message:nil preferredStyle:UIAlertControllerStyleAlert];
// UIAlertAction * action = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleCancel handler:nil];
// [alert addAction:action];
// [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark 店家annotation彈出的泡泡時,調(diào)用
-(void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view
{
NSLog(@"點擊泡泡");
}