功能描述:
(1)我们在项目中往往会需要根据经纬度在地图中定位一个地点,在哪里插个大头针展示下;
(2)当经纬度没有的时候,可以根据具体的地址信息去获取经纬度在地图上插个大头针展示下。
具体的工程:
(1)根据官方文档导入百度地图的FrameWork,根据官方文档先处理好所有需要的配置。
(2)我这里给出的我的代码其实在百度的Demo中是可以找到的,我这里只是总结下我的步骤;
代码:
(1)需要的代理:BMKLocationServiceDelegate、BMKMapViewDelegate、BMKGeoCodeSearchDelegate
(2)声明的成本变量、属性
BMKLocationService * _locService;
BMKGeoCodeSearch* _geocodesearch;
因为界面使用了xib所以就直接在xib上使用了MapView
@property (strong, nonatomic) IBOutlet BMKMapView *baiduMapView;
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
//注意这里需要在这里重新设置delegate
self.backScrollView.delegate = self;
//这个方法去除了导航下面的线、这个方法是一个比较好的移除导航条下面的一个线的方法
[self.navigationController.navigationBar setShadowImage:[UIImage new]];
[_baiduMapView viewWillAppear];
_baiduMapView.delegate = self;
_locService.delegate = self;
_geocodesearch.delegate = self;
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
//这里一定要把Scrollview的代理设置为nil否则会影响到下一个界面的导航
self.backScrollView.delegate = nil;
[self.navigationController.navigationBar lt_reset];
[_baiduMapView viewWillDisappear];
// 此处记得不用的时候需要置nil,否则影响内存的释放
_baiduMapView.delegate = nil;
_locService.delegate = nil;
_geocodesearch.delegate = nil;
}
- (void)dealloc{
if(_geocodesearch != nil){
_geocodesearch = nil;
}
if(_baiduMapView){
_baiduMapView = nil;
}
}
- (void)initUI{
_locService = [[BMKLocationService alloc]init];
_geocodesearch = [[BMKGeoCodeSearch alloc]init];
_locService.delegate = self;
_baiduMapView.delegate = self;
[_locService startUserLocationService];
_baiduMapView.zoomLevel = 14;
[self.navigationController.navigationBar lt_setBackgroundColor:[UIColor clearColor]];
[self createNavButton];
[self refreshView];
}
//刷新界面
- (void)refreshView{
//这里可以把这个延迟去掉不要
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// 2秒后异步执行这里的代码...
if(self.createHouseModel.latitude.integerValue == 0){
// //如果检索失败就应该让查看周边的按钮不可点击,箭头也隐藏掉
BMKGeoCodeSearchOption *geocodeSearchOption = [[BMKGeoCodeSearchOption alloc]init];
if([self.createHouseModel.address rangeOfString:@"市"].location != NSNotFound){
NSArray * array = [self.createHouseModel.address componentsSeparatedByString:@"市"];
geocodeSearchOption.city =array[0];
}else{
geocodeSearchOption.city= @"";
}
geocodeSearchOption.address = self.createHouseModel.address;
BOOL flag = [_geocodesearch geoCode:geocodeSearchOption];
if(flag)
{
NSLog(@"geo检索发送成功");
}
else
{
NSLog(@"geo检索发送失败");
}
}
else{
CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};
pt = (CLLocationCoordinate2D){[self.createHouseModel.latitude floatValue], [self.createHouseModel.longitude floatValue]};
BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
reverseGeocodeSearchOption.reverseGeoPoint = pt;
BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
if(flag)
{
NSLog(@"反geo检索发送成功");
}
else
{
NSLog(@"反geo检索发送失败");
}
}
});
}
//根据anntation生成对应的View
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id)annotation{
NSString *AnnotationViewID = @"annotationViewID";
//根据指定标识查找一个可被复用的标注View,一般在delegate中使用,用此函数来代替新申请一个View
BMKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
if (annotationView == nil) {
annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
}
annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
annotationView.annotation = annotation;
annotationView.canShowCallout = YES;
return annotationView;
}
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
NSArray* array = [NSArray arrayWithArray:_baiduMapView.annotations];
[_baiduMapView removeAnnotations:array];
array = [NSArray arrayWithArray:_baiduMapView.overlays];
[_baiduMapView removeOverlays:array];
if (error == 0) {
self.locationFailRemarkView.hidden = YES;
BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
item.coordinate = result.location;
item.title = self.createHouseModel.esidentialquarters;//标题是小区的名称;
[_baiduMapView addAnnotation:item];
_baiduMapView.centerCoordinate = result.location;
self.createHouseModel.latitude = [NSString stringWithFormat:@"%f",item.coordinate.latitude];
self.createHouseModel.longitude = [NSString stringWithFormat:@"%f",item.coordinate.longitude];
}else{
self.locationFailRemarkView.hidden = NO;
}
}
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
NSArray* array = [NSArray arrayWithArray:_baiduMapView.annotations];
[_baiduMapView removeAnnotations:array];
array = [NSArray arrayWithArray:_baiduMapView.overlays];
[_baiduMapView removeOverlays:array];
if (error == 0) {
self.locationFailRemarkView.hidden = YES;
BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
item.coordinate = result.location;
item.title = self.createHouseModel.esidentialquarters;//标题是小区的名称;
[_baiduMapView addAnnotation:item];
_baiduMapView.centerCoordinate = result.location;
}else{
self.locationFailRemarkView.hidden = NO;
}
}
//代理方法
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation{
[_baiduMapView updateLocationData:userLocation];
}
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
[_baiduMapView updateLocationData:userLocation];
}
这里的检索代码在百度的Demo中也是可以找到的。这里我做了一点点的修改。不过还存在一个问题,当点击搜索“地铁”的时候无法出现
#import "NeighbourViewController.h"
#import "SliderView.h"
@interface NeighbourViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate,SliderViewDelegate,BMKPoiSearchDelegate>{
NSString * searchSign;
BMKLocationService * _locService;
BMKPoiSearch* _poisearch;
}
@property (nonatomic,strong) BMKMapView * baiduMapView;
@property (nonatomic,strong) SliderView * sliderView;
@property (nonatomic,strong) UIButton * rightButton;
@end
@implementation NeighbourViewController
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.baiduMapView viewWillAppear];
self.baiduMapView.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放
_locService.delegate = self;
_poisearch.delegate = self;
}
- (void)viewDidLoad {
[super viewDidLoad];
_poisearch = [[BMKPoiSearch alloc]init];
_locService = [[BMKLocationService alloc]init];
[_locService startUserLocationService];
self.view.backgroundColor = [UIColor whiteColor];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self.baiduMapView viewWillDisappear];
_poisearch.delegate = nil; // 不用时,置nil
self.baiduMapView.delegate = nil; // 不用时,置nil
_locService.delegate = nil;
}
- (void)initData{
}
- (void)initUI{
[self createRightButton];
[self goBackBtn];
[self createBaiduMapView];
[self createBottomView];
[self startLocation];//开始定位
}
- (void)createRightButton{
self.rightButton = [self createRightItemAction:@selector(rightButtonClick:)];
[self.rightButton setTitle:@"导航" forState:UIControlStateNormal];
self.rightButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
self.rightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
self.rightButton.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -10);
}
//导航按钮的点击
- (void)rightButtonClick:(UIButton *)button{
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://map/"]])
{
double m_wd = _locService.userLocation.location.coordinate.latitude;
double m_jd = _locService.userLocation.location.coordinate.longitude;
NSString *urlString = [NSString stringWithFormat:@"baidumap://map/direction?origin=%f,%f&destination=%f,%f&mode=driving&src=webapp.navi.yourCompanyName.yourAppName",m_wd,m_jd,self.latFloat,self.logFloat];
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlString]];
}else{
[SVProgressHUD showErrorWithStatus:@"您没有安装百度地图,无法为你导航"];
}
}
- (void)createBaiduMapView{
self.baiduMapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 50)];
// 设置地图级别
[self.baiduMapView setZoomLevel:13];
[self.view addSubview:self.baiduMapView];
}
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation{
[self.baiduMapView updateLocationData:userLocation];
}
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
[self.baiduMapView updateLocationData:userLocation];
}
#pragma mark 开始定位
- (void)startLocation{
CLLocationCoordinate2D coordinate;
coordinate.latitude = self.latFloat;
coordinate.longitude = self.logFloat;
[_locService startUserLocationService];
self.baiduMapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
[self.baiduMapView setShowsUserLocation:YES];
BMKPointAnnotation* annotation = [[BMKPointAnnotation alloc]init];
annotation.coordinate = coordinate;
annotation.title = self.titleStr;
[self.baiduMapView addAnnotation:annotation];
self.baiduMapView.centerCoordinate = coordinate;
}
- (void)createBottomView{
NSMutableArray * titleArray = [[NSMutableArray alloc]initWithObjects:@"银行",@"公交",@"地铁",@"教育",@"医院",@"休闲",@"购物",@"健身",@"美食",nil];
self.sliderView = [[SliderView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 50, SCREEN_WIDTH, 50) titleArray:titleArray];
self.sliderView.sliderDelegate = self;
[self.view addSubview:self.sliderView];
}
- (void)itemButtonClick:(UIButton *)button{
NSString * searchTitle = button.titleLabel.text;
searchSign = searchTitle;
BMKNearbySearchOption * nearSearch = [[BMKNearbySearchOption alloc]init];
CLLocationCoordinate2D coordinate;
coordinate.latitude = self.latFloat;
coordinate.longitude = self.logFloat;
nearSearch.pageIndex = 1;
nearSearch.pageCapacity = 20;
nearSearch.location = coordinate;
nearSearch.radius = 3000;
nearSearch.keyword = searchTitle;
BOOL flag = [_poisearch poiSearchNearBy:nearSearch];
if(flag)
{
NSLog(@"城市内检索发送成功");
}
else
{
NSLog(@"城市内检索发送失败");
}
}
- (void)dealloc {
if (_poisearch != nil) {
_poisearch = nil;
}
if (_baiduMapView) {
_baiduMapView = nil;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/**
*根据anntation生成对应的View
*@param mapView 地图View
*@param annotation 指定的标注
*@return 生成的标注View
*/
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id )annotation
{
NSString *AnnotationViewID = @"xidanMark";
BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
// 缓存没有命中,自己构造一个,一般首次添加annotation代码会运行到此处
if (newAnnotationView == nil) {
newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
((BMKPinAnnotationView*)newAnnotationView).pinColor = BMKPinAnnotationColorRed;
// 设置重天上掉下的效果(annotation)
((BMKPinAnnotationView*)newAnnotationView).animatesDrop = YES;
}
newAnnotationView.pinColor = BMKPinAnnotationColorPurple;
newAnnotationView.animatesDrop = YES;// 设置该标注点动画显示
newAnnotationView.annotation=annotation;
if([searchSign isEqualToString:@"银行"]){
newAnnotationView.image = [UIImage imageNamed:@"location_bank"];
}else if([searchSign isEqualToString:@"公交"]){
newAnnotationView.image = [UIImage imageNamed:@"location_transit"];
}else if([searchSign isEqualToString:@"银行"]){
newAnnotationView.image = [UIImage imageNamed:@"location_bank"];
}else if([searchSign isEqualToString:@"地铁"]){
newAnnotationView.image = [UIImage imageNamed:@"location_subWay"];
}else if([searchSign isEqualToString:@"教育"]){
newAnnotationView.image = [UIImage imageNamed:@"location_eductation"];
}else if([searchSign isEqualToString:@"医院"]){
newAnnotationView.image = [UIImage imageNamed:@"location_hospital"];
}else if([searchSign isEqualToString:@"休闲"]){
newAnnotationView.image = [UIImage imageNamed:@"location_casual"];
}else if([searchSign isEqualToString:@"购物"]){
newAnnotationView.image = [UIImage imageNamed:@"location_shopping"];
}else if([searchSign isEqualToString:@"健身"]){
newAnnotationView.image = [UIImage imageNamed:@"location_physical"];
}else if([searchSign isEqualToString:@"美食"]){
newAnnotationView.image = [UIImage imageNamed:@"location_food"];
}
// newAnnotationView.image = [UIImage imageNamed:@"home_push.jpg"]; //把大头针换成别的图片
newAnnotationView.size = CGSizeMake(28, 35);
return newAnnotationView;
}
- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view
{
[mapView bringSubviewToFront:view];
[mapView setNeedsDisplay];
}
- (void)mapView:(BMKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
NSLog(@"didAddAnnotationViews");
}
#pragma mark -
#pragma mark implement BMKSearchDelegate
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult*)result errorCode:(BMKSearchErrorCode)error
{
[SVProgressHUD show];
// 清楚屏幕中所有的annotation
NSMutableArray* array = [NSMutableArray arrayWithArray:_baiduMapView.annotations];
for(int i = 0; i < array.count; i++){
BMKPointAnnotation * annotation = array[i];
if([annotation.title isEqualToString:self.titleStr]){
[array removeObject:annotation];
}
}
[_baiduMapView removeAnnotations:array];
if (error == BMK_SEARCH_NO_ERROR) {
NSMutableArray *annotations = [NSMutableArray array];
for (int i = 0; i < result.poiInfoList.count; i++) {
BMKPoiInfo* poi = [result.poiInfoList objectAtIndex:i];
BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
item.coordinate = poi.pt;
item.title = poi.name;
[annotations addObject:item];
}
[_baiduMapView addAnnotations:annotations];
[_baiduMapView showAnnotations:annotations animated:YES];
} else if (error == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR){
NSLog(@"起始点有歧义");
} else {
// 各种情况的判断。。。
}
[SVProgressHUD dismiss];
}
@end