开发者

MKMapView with address

开发者 https://www.devze.com 2023-01-09 14:42 出处:网络
is there a way to make the MKMapView place a pin with a given 开发者_运维知识库address? Without using the Coordinates

is there a way to make the MKMapView place a pin with a given 开发者_运维知识库address? Without using the Coordinates

Thanks


here is a snippet of code I used in an application

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


here is a snippet of code I used in an application

[NSString stringWithContentsOfURL:] is deprecated for now. You have to use:

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


Since this result is in the first page when you make a Google search, I think it's good to give a fresher solution than the Google geocoding (limited). It's better to use an Apple geocoder:

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


Since google posted a new version to their geocoding API (upgrade notes), the Google Maps URL provided by @Aaron Saunders is no longer valid. Additionally, the response is now either json or xml so I have made some changes to address this in the accepted response.

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


You need to use a geocoding service to convert your address to coordinates. Google, I think, offers one, along with a few other services.

0

精彩评论

暂无评论...
验证码 换一张
取 消