简体   繁体   English

Swift中MKMapItem的经度和纬度?

[英]Latitude and longitude from MKMapItem in Swift?

Using MKLocalSearchRequest() I get an array of MKMapItem . 使用MKLocalSearchRequest()得到一个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) . 我已经尝试过println(item.latitude) The console output is nil . 控制台输出为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 使用item.placemark来获取经度/纬度似乎也不是一个选择,因为'placemark' is unavailable: APIs deprecated as of iOS 7 and earlier are unavailable in Swift

Why is item.latitude nil? 为什么item.latitude为零? Why can't I reach into placemark ? 为什么我无法进入placemark

The console output for println(item) is something like this: println(item)的控制台输出是这样的:

<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? 我为什么不能得到它?

The response.mapItems array is declared in the API as of type [AnyObject]! API中声明了[AnyObject]!类型的response.mapItems数组[AnyObject]! .

The for loop isn't explicitly saying that res is of type MKMapItem (or that response.mapItems is actually [MKMapItem] ). for循环未明确指出res属于MKMapItem类型(或者response.mapItems实际上是[MKMapItem] )。

So res is treated like an instance of AnyObject which isn't defined as having a placemark property. 因此,将res视为AnyObject的实例,该实例未定义为具有地标属性。

This is why you get the compiler error ' placemark ' is unavailable.... 这就是为什么您得到编译器错误“ placemark ”不可用的原因。

To fix this, cast res as an MKMapItem and then the placemark property will become visible. 要解决此问题, MKMapItem res MKMapItemMKMapItem ,然后地标属性将变为可见。

Use this code for getting placemark 使用此代码获取placemark

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

Also, this line after the for loop: 另外,在for循环之后的这一行:

self.userSearch = response.mapItems.placemark

For more Info refer THIS answer. 有关更多信息,请参考答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM