這兩天項(xiàng)目需要用到高德地圖,一直在搗鼓,其中一個(gè)需求是:需要商家用戶,能夠在地圖上選擇自己的店鋪位置,然后把這個(gè)位置記錄下來(lái)傳給服務(wù)器.
第一次用,各種踩坑,問(wèn)來(lái)問(wèn)去,決定還是自己研究,幸好,搞出來(lái)了,方法分享如下:
思路有兩種:
1.大頭針不動(dòng),讓用戶移動(dòng)地圖,然后實(shí)時(shí)獲取大頭針?biāo)谖恢玫慕?jīng)緯度信息.
2.固定地圖,移動(dòng)大頭針,然后取到大頭針落點(diǎn)的位置.
我用的第一種方法,感覺要好操作一點(diǎn):
首先:在地圖中心放一個(gè)UIImageView,添加一個(gè)大頭針的圖片我用的是系統(tǒng)自帶的圖片(redPin.png),這里有個(gè)坑,系統(tǒng)自帶的大頭針圖片都放在AMap.bundle里面,但是我們?cè)谙螺dSDK的時(shí)候,貌似不會(huì)下載這個(gè),我也是看了官方demo,才找到這個(gè)AMap.bundle.所以,(關(guān)于demo,一定要多看,特別是沒思路的時(shí)候,挺有幫助的).
然后:從demo中取出AMap.bundle,拖進(jìn)自己的項(xiàng)目,即可.注意:這里又有一個(gè)坑,導(dǎo)入以后,點(diǎn)開看會(huì)發(fā)現(xiàn),文件夾是藍(lán)色的,我第一次給添加圖片,直接就imageView.image = [UIImage imageNamed:@"redPin"];但是,運(yùn)行發(fā)現(xiàn),圖片并沒有顯示.所有,需要我們手動(dòng)把redPin.png和2x,3x的圖片拖到AMap.bundle外面的目錄,這樣,圖片就顯示出來(lái)了.
最后,就是導(dǎo)入相關(guān)的SDK(此處用的2D地圖SDK),調(diào)用代理方法了,
在viewController.m 導(dǎo)入:
#import? <MAMaoKit/MAMapKit.h>?
#import? <AMapFoundationKit/AMaoFoundationKit>
#import.h <AMapSearchKit/AMapSearchKit.h> //這個(gè)在進(jìn)行坐標(biāo)轉(zhuǎn)地址時(shí)用到
聲明屬性:
@property(nonatomic,strong)MAMapView * mapView;
@property(nonatomic,strong)AMapSearchAPI * search;
@property(nonatomic,strong)AMapReGeocodeSearchRequest *regeo ;
加入代理
- (void)viewDidLoad {
///地圖需要v4.5.0及以上版本才必須要打開此選項(xiàng)(v4.5.0以下版本漱贱,需要手動(dòng)配置info.plist)
[AMapServices sharedServices].enableHTTPS = NO;//默認(rèn)開啟HTTPS
///初始化地圖
_mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT*0.5)];
[self.view addSubview:_mapView];
_mapView.delegate = self;
[_mapView setZoomLevel:13.5 animated:YES];//改變地圖的縮放級(jí)別
//_mapView.showsUserLocation = YES;? ? //顯示定位小藍(lán)點(diǎn)
//自定義大頭針
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 60)];
imageView.center = _mapView.center;
imageView.image = [UIImage imageNamed:@"redPin"];? //添加大頭針,使它固定在屏幕中心
[_mapView addSubview:imageView];
_search = [[AMapSearchAPI alloc]init];
_search.delegate = self;
}
#pragma mark - MAMapViewDelegate
//地圖區(qū)域改變完成后調(diào)用的接口
- (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
NSLog(@"%f",mapView.region.center.latitude); //拿到中心點(diǎn)的經(jīng)緯度
NSLog(@"%f\n",mapView.region.center.longitude);
//如果將坐標(biāo)轉(zhuǎn)為地址,需要進(jìn)行逆地理編碼
//設(shè)置逆地理編碼查詢參數(shù) ,進(jìn)行逆地編碼時(shí)槐雾,請(qǐng)求參數(shù)類為 AMapReGeocodeSearchRequest,location為必設(shè)參數(shù)幅狮。
_regeo = [[AMapReGeocodeSearchRequest alloc] init];
_regeo.location = [AMapGeoPoint locationWithLatitude:mapView.region.center.latitude longitude:mapView.region.center.longitude];
_regeo.requireExtension = YES;
[_search AMapReGoecodeSearch:_regeo];
}
#pragma mark -? AMapSearchDelegate
/* 逆地理編碼回調(diào). */
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
if (response.regeocode != nil)
{
//解析response獲取地址描述募强,具體解析見 Demo
//位置信息
NSLog(@"reGeocode:%@", response.regeocode.formattedAddress);//獲得的中心點(diǎn)地址
}
}