MKMapView with address

后端 未结 5 1903
梦毁少年i
梦毁少年i 2021-02-05 15:25

is there a way to make the MKMapView place a pin with a given address? Without using the Coordinates

Thanks

5条回答
  •  孤独总比滥情好
    2021-02-05 16:11

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

提交回复
热议问题