我使用的是Google API來獲取地理座標。我一直在使用至今一直是代碼如下在地圖視圖中使用CLGeocoder代替私有API
-(CLLocationCoordinate2D) getLocationFromAddressString:(NSString*) addressStr {
NSString *urlStr = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv",
[addressStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *locationStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlStr] encoding:NSStringEncodingConversionAllowLossy error:nil];
NSArray *items = [locationStr componentsSeparatedByString:@","];
double latitude = 0.0;
double longitude = 0.0;
//NSLog(@"items array %@", items);
if([items count] >= 4 && [[items objectAtIndex:0] isEqualToString:@"200"]) {
latitude = [[items objectAtIndex:2] doubleValue];
longitude = [[items objectAtIndex:3] doubleValue];
}
else {
//NSLog(@"Address, %@ not found: Error %@",addressStr, [items objectAtIndex:0]);
}
CLLocationCoordinate2D location;
location.latitude = latitude;
location.longitude = longitude;
return location;
}
我希望用CLGeocoder
在谷歌API的地方,從一個地址字符串獲得位置座標。
我一直在使用CLGeocoder
從網上的例子。我發現與CLGeocoder
合作有點困難。我嘗試使用CLGeocoder
,而沒有更改我以前的代碼,這樣我就不必對現有代碼進行大的更改。
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:addressStr completionHandler:^(NSArray *placemarks, NSError *error) {
self.placemarksArray = placemarks;
CLPlacemark *placeInfo = [placemarks objectAtIndex:0];
NSString *latitudeString = [NSString stringWithFormat:@"%f",placeInfo.location.coordinate.latitude ];
NSString *longitudeString = [NSString stringWithFormat:@"%f",placeInfo.location.coordinate.longitude ];
NSLog(@"latitudeString %@", latitudeString);
NSLog(@"longitudeString %@", longitudeString);
_latitudes = placeInfo.location.coordinate.latitude;
_longitudes = placeInfo.location.coordinate.longitude;
}];
location.latitude = _latitudes;
location.longitude = _longitudes;
return location;
但是會發生什麼,地圖視圖會在塊被執行之前被加載。在這種情況下,該位置的確切值不會返回。
我的問題是:
- 是否有可能使用
CLGeocoder
,未做太大的變化,以我以前的代碼。或者我需要改變整個結構。 - 從我試過的第二塊代碼中,我做錯了什麼,我該如何糾正它?
編輯:上述方法是從viewDidLoad
CLLocationCoordinate2D mapCenter = [self getLocationFromAddressString:fullAddress];
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init];
[annotationPoint setCoordinate:mapCenter];
[annotationPointsArray addObject:annotationPoint];
addAnnotation = [[[MyAddressAnnotation alloc] initWithCoordinate:mapCenter title:firstName SubTitle:lastName]autorelease];
[mapView addAnnotation:addAnnotation];
這被執行稱爲從getGeoLocation方法得到CLLocationCoordinate2D
緯度和經度值之後。
好吧,看起來你正在從'getLocationFromAddressString'中取得'location'並創建一個註解。你應該(a)改變'getLocationFromAddressString'返回'void',然後(b)將創建註釋的代碼放到'geocodeAddressString'完成塊中。 – Rob 2013-03-20 12:53:50
我和你建議的方式一樣。 – 2013-03-20 14:02:01