MKMapView与地址配合使用

13

有没有一种方法可以让MKMapView根据给定的地址放置一个图钉?而不使用坐标。

谢谢

5个回答

21

这里是我在一个应用程序中使用的一小段代码。

-(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;
}

1
值得一提的是,如果你正在开发商业应用程序,尤其是构建与 Google 地理编码相关的应用程序,那么最好检查一下 Google 地理编码的条款和条件(http://code.google.com/apis/maps/documentation/geocoding/)。 - Colin Pickard
1
请注意,目前(已经发布了iOS7),您可以使用CLGeocoder类,并将地址字符串转发到该类以获取坐标。使用方法:“geocodeAddressString:completionHandler:”。这样,您就不必注册Google的地理编码服务。 - idStar

5

这是我在一个应用程序中使用的代码片段:

[NSString stringWithContentsOfURL:]现已被弃用,您需要使用:

NSString *locationStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlStr] encoding:NSUTF8StringEncoding error:nil];

5

既然这个结果在谷歌搜索的第一页,我认为提供一个比谷歌地理编码(有限制)更好的新解决方案是很不错的。最好使用苹果地理编码器:

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];
                 }
             }];

1
这真的应该是被接受的答案。我建议使用[placemarks firstObject]而不是objectAtIndex,并检查错误状态。 - Ben
是的,你说得对,我编辑了代码,但请记住,firstObject仅在iOS7及以上版本中公开可用。 - Climbatize

2

自从谷歌发布了新版本的地理编码API(升级说明),@Aaron Saunders提供的谷歌地图URL不再有效。此外,响应现在是jsonxml,因此我已经对接受的响应进行了一些更改以解决这个问题。

- (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);
    }
}

如果您能提供一个示例URL,那就太好了。 - Adil Malik

0
你需要使用地理编码服务将你的地址转换为坐标。我想谷歌提供了一个,还有一些其他的服务。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接