Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - MKMapView place annotation by using address instead of lat / long

I am able to place annotations on my MKMapView by using latitude and longitude, however, my feed coming in that I need to use location for is using street addresses instead of Lat and Long. e.g 1234 west 1234 east, San Francisco, CA ...

Would this have something to do with the CLLocationManager?

Has anyone attempted this before?

like image 226
Romes Avatar asked Mar 07 '12 17:03

Romes


3 Answers

Based on psoft's excellent information, I was able to achieve what I was looking for with this code.

NSString *location = @"some address, state, and zip";
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
            [geocoder geocodeAddressString:location 
                 completionHandler:^(NSArray* placemarks, NSError* error){
                     if (placemarks && placemarks.count > 0) {
                         CLPlacemark *topResult = [placemarks objectAtIndex:0];
                         MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];

                         MKCoordinateRegion region = self.mapView.region;
                         region.center = placemark.region.center;
                         region.span.longitudeDelta /= 8.0;
                         region.span.latitudeDelta /= 8.0;

                         [self.mapView setRegion:region animated:YES];
                         [self.mapView addAnnotation:placemark];
                     }
                 }
             ];
like image 169
Romes Avatar answered Nov 14 '22 20:11

Romes


Refactored Swift version:

let location = "some address, state, and zip"
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(location) { [weak self] placemarks, error in
    if let placemark = placemarks?.first, let location = placemark.location {
        let mark = MKPlacemark(placemark: placemark)

        if var region = self?.mapView.region {
            region.center = location.coordinate
            region.span.longitudeDelta /= 8.0
            region.span.latitudeDelta /= 8.0
            self?.mapView.setRegion(region, animated: true)
            self?.mapView.addAnnotation(mark)
        }
    }
}
like image 37
NatashaTheRobot Avatar answered Nov 14 '22 22:11

NatashaTheRobot


What you're after is called geocoding or forward-geocoding. Reverse-geocoding is the process of converting a lat/long pair to street address.

iOS5 provides the CLGeocoder class for geocoding. MKPlacemark supports reverse-goecoding in iOS >= 3.0. The data involved of course is very large, so your app will generally need network access to the functionality.

A good place to start is Apple's Location Awareness Programming Guide. Also, there are LOTS of questions about this here on SO. https://stackoverflow.com/search?q=geocoding

Good luck!

like image 11
QED Avatar answered Nov 14 '22 21:11

QED