有没有一种方法可以让MKMapView根据给定的地址放置一个图钉?而不使用坐标。
谢谢
这里是我在一个应用程序中使用的一小段代码。
-(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]];
NSArray *items = [locationStr componentsSeparatedByString:@","];
double lat = 0.0;
double lon = 0.0;
if([items count] >= 4 && [[items objectAtIndex:0] isEqualToString:@"200"]) {
lat = [[items objectAtIndex:2] doubleValue];
lon = [[items objectAtIndex:3] doubleValue];
}
else {
NSLog(@"Address, %@ not found: Error %@",addressStr, [items objectAtIndex:0]);
}
CLLocationCoordinate2D location;
location.latitude = lat;
location.longitude = lon;
return location;
}
这是我在一个应用程序中使用的代码片段:
[NSString stringWithContentsOfURL:]现已被弃用,您需要使用:
NSString *locationStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlStr] encoding:NSUTF8StringEncoding error:nil];
既然这个结果在谷歌搜索的第一页,我认为提供一个比谷歌地理编码(有限制)更好的新解决方案是很不错的。最好使用苹果地理编码器:
NSString *location = @"your address";
CLGeocoder *geocoder = [CLGeocoder new];
[geocoder geocodeAddressString:location
completionHandler:^(NSArray* placemarks, NSError* error){
if (error) {
NSLog(@"%@", error);
} else if ([placemarks count]) {
CLPlacemark *topResult = [placemarks firstObject];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(placemark.coordinate, 5000, 5000);
[self.mapView setRegion:region animated:YES];
[self.mapView addAnnotation:placemark];
}
}];
自从谷歌发布了新版本的地理编码API(升级说明),@Aaron Saunders提供的谷歌地图URL不再有效。此外,响应现在是json
或xml
,因此我已经对接受的响应进行了一些更改以解决这个问题。
- (CLLocationCoordinate2D)locationFromAddressString:(NSString*)addressString {
if (!addressString.length) {
ALog(@"provided an empty 'addressStr'");
return CLLocationCoordinate2DMake(0.0, 0.0);
}
NSString *urlStr = [NSString stringWithFormat:GOOGLE_MAPS_GEOCODING_URL_STR,
[addressString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSError *dataError;
NSError *jsonError;
NSData *responseData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]
options:NSDataReadingMappedAlways
error:&dataError];
NSDictionary *responseBody = [NSJSONSerialization JSONObjectWithData:responseData
options:NSJSONReadingMutableContainers
error:&jsonError];
if (!dataError && !jsonError && [responseBody[@"status"] isEqualToString:@"OK"]) {
NSDictionary *coords = responseBody[@"results"][0][@"geometry"][@"location"];
return CLLocationCoordinate2DMake([coords[@"lat"] doubleValue],
[coords[@"lng"] doubleValue]);
}
else {
ALog(@"Address [%@] not found. \nResponse [%@]. \nError [%@]",addressString, responseBody, jsonError);
return CLLocationCoordinate2DMake(0.0, 0.0);
}
}