iosswiftmapkitmkmapitem

Latitude and longitude from MKMapItem in Swift?


Using MKLocalSearchRequest() I get an array of MKMapItem.

All I need is the latitude and longitude from the item. It seems like it should be easy.

let search = MKLocalSearch(request: request)
search.startWithCompletionHandler { (response, error) in
    for item in response.mapItems {

    }
}

I have tried println(item.latitude). The console output is nil.

Using item.placemark to get the lat/longitude doesn't seem to be an option either because 'placemark' is unavailable: APIs deprecated as of iOS 7 and earlier are unavailable in Swift

Why is item.latitude nil? Why can't I reach into placemark?

The console output for println(item) is something like this:

<MKMapItem: 0x17086a900> {
isCurrentLocation = 0;
name = "Random University";
phoneNumber = "+1000000000";
placemark = "Random University, 400 Address Ave, City, NJ  01010-0000, United States @ <+34.74264816,-84.24657106> +/- 0.00m, region CLCircularRegion (identifier:'<+34.74279563,-84.24621513> radius 514.96', center:<+34.74279563,-84.24621513>, radius:514.96m)";
url = "http://www.shu.edu";
}

I can see the latitude and longitude right there! Why can't I get it?


Solution

  • The response.mapItems array is declared in the API as of type [AnyObject]!.

    The for loop isn't explicitly saying that res is of type MKMapItem (or that response.mapItems is actually [MKMapItem]).

    So res is treated like an instance of AnyObject which isn't defined as having a placemark property.

    This is why you get the compiler error 'placemark' is unavailable....

    To fix this, cast res as an MKMapItem and then the placemark property will become visible.

    Use this code for getting placemark

    for res in response.mapItems {
        if let mi = res as? MKMapItem {
            self.userSearch.append(mi.placemark)
        }
    }
    

    Also, this line after the for loop:

    self.userSearch = response.mapItems.placemark
    

    For more Info refer THIS answer.