c'è un modo per far sì che MKMapView inserisca un pin con un dato indirizzo? Senza usare le coordinateMKMapView con indirizzo
Grazie
c'è un modo per far sì che MKMapView inserisca un pin con un dato indirizzo? Senza usare le coordinateMKMapView con indirizzo
Grazie
: ecco un frammento di codice che ho usato in un'applicazione
-(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;
}
È necessario utilizzare un servizio di geocodifica per convertire il vostro indirizzo a coordinate. Google, penso, ne offre uno, insieme ad alcuni altri servizi.
Ecco un frammento di codice che ho usato in un'applicazione
[NSString stringWithContentsOfURL:] è deprecato per ora . Devi usare:
NSString *locationStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlStr] encoding:NSUTF8StringEncoding error:nil];
Dal momento che Google ha pubblicato una nuova versione del loro geocoding API (upgrade notes), l'URL di Google Maps fornito da @Aaron Saunders non è più valida. Inoltre, la risposta è ora json
o xml
quindi ho apportato alcune modifiche per risolvere questo problema nella risposta accettata.
- (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);
}
}
Sarebbe bello poter fornire anche un URL di esempio. –
Questo è un URL di esempio: http://maps.googleapis.com/maps/api/geocode/json?address=Mall+Road+Lahore+Pakistan&sensor=false –
Dal momento che questo risultato è in prima pagina quando si effettua una ricerca su Google, penso che sia buona per dare una soluzione più fresco rispetto alla geocoding di Google (limitato). E 'meglio utilizzare un geocoder di Apple:
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];
}
}];
Questa dovrebbe essere la risposta accettata. Ti consigliamo di utilizzare [segnaposto firstObject] anziché objectAtIndex e controllare lo stato degli errori. – Ben
Sì, hai ragione, cambio il codice, tieni presente che firstObject è disponibile solo pubblicamente su iOS7 e versioni successive – Climbatize
E' la pena di verificare i termini e le condizioni di geocodifica di Google (http://code.google.com/apis/maps/documentation/geocoding/), in particolare se si sta costruendo un'applicazione commerciale. –
Grazie mille per la risposta – SampathKumar
Nota che al momento (iOS7 è fuori), puoi usare la classe CLGeocoder, e inoltrare il codice a una stringa di indirizzo per ottenere le coordinate. Utilizzare il metodo: "geocodeAddressString: completionHandler:". In questo modo, non è necessario registrarsi al servizio di geocodifica di Google. – idStar