首先蘋果獲取經緯度是
[plain]
if ([CLLocationManager locationServicesEnabled]) {//判斷手機是否可以定位
locationManager = [[CLLocationManager alloc] init];//初始化位置管理器
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];//設置精度
locationManager.distanceFilter = 1000.0f;//設置距離篩選器
[locationManager startUpdatingLocation];//啟動位置管理器
}
然後根據其代理獲取經緯度
[plain]
#pragma mark - CLLocationManager Delegate Methods
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation;
{
location=[newLocation coordinate];//當前經緯度
lat=location.latitude;
lon=location.longitude;
MKCoordinateSpan theSpan;
theSpan.latitudeDelta=0.01f;
theSpan.longitudeDelta=0.01f;
theRegion.center=location;//定義地圖顯示范圍
theRegion.span=theSpan;
}
根據經緯度解析成位置目前有2種。第一個是調用系統的CLGeocoder類的 reverseGeocodeLocation方法
[plain]
//根據經緯度解析成位置
CLGeocoder *geocoder=[[[CLGeocoder alloc]init]autorelease];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemark,NSError *error)
{
CLPlacemark *mark=[placemark objectAtIndex:0];
place.title=@"沒有當前位置的詳細信息";
place.subTitle=@"詳細信息請點擊‘附近’查看";
place.title=[NSString stringWithFormat:@"%@%@%@",mark.subLocality,mark.thoroughfare,mark.subThoroughfare];
place.subTitle=[NSString stringWithFormat:@"%@",mark.name];//獲取subtitle的信息
[self.myMapView selectAnnotation:place animated:YES];
} ];
第二種是調用google的api
----http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=true
網上有人說系統的方法有時候解析不出來位置。第二種google,國內有時候訪問不了google服務器,所以都有缺點。
有人建議國內的地圖可以使用高德地圖(以後摸索下)
PS1:網上有一個比較流行的查找附近功能,是根據google的api搜索的
#define SEARCH_GOOGLE @"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=1000&types=%@&sensor=true&key=AIzaSyALaqx0MfPsp2aldbZbzEQAq64SwgQfZ0c"
調用的話就是這樣
jsonString = [NSString stringWithFormat:SEARCH_GOOGLE,location.coordinate.latitude,location.coordinate.longitude,@"food"];
jsonString = [NSString stringWithFormat:SEARCH_GOOGLE,location.coordinate.latitude,location.coordinate.longitude,@"bus_station"];
jsonString = [NSString stringWithFormat:SEARCH_GOOGLE,location.coordinate.latitude,location.coordinate.longitude,@"hospital"];
PS2:有個功能,如果長時間按住地圖上某個地方,如何獲取其經緯度,進而對其顯示位置呢?
----
[plain]
//開始點擊長按,不然會執行2次。
if (sender.state==UIGestureRecognizerStateBegan) {
//isLongPress=YES;
CGPoint touchPoint=[sender locationInView:self.myMapView];
CLLocationCoordinate2D touchCoordinate=[self.myMapView convertPoint:touchPoint toCoordinateFromView:self.myMapView];//將觸摸點轉換經緯度
//反向解析長按時的大頭針的信息
location =[[CLLocation alloc]initWithLatitude:touchCoordinate.latitude longitude:touchCoordinate.longitude];