将 CLLocation 对象转换为 MKMapPoint 结构

Posted

技术标签:

【中文标题】将 CLLocation 对象转换为 MKMapPoint 结构【英文标题】:Converting CLLocation objects to MKMapPoint structs 【发布时间】:2012-02-16 10:44:30 【问题描述】:

我想创建一个MKPolygon 以显示在MKMapView 上。我的问题是我不知道该怎么做。

我知道要创建MKPolygon,我必须创建一堆MKMapPoint 结构并将它们放入一个数组并调用类方法polygonWithPoints

我的问题是我有一个 NSArray 包含 CLLocation 具有 coordinate.latitudecoordinate.longitude 属性的对象。

如何将其一一转换为MKMapPoint 结构?

【问题讨论】:

【参考方案1】:

如果您有一个包含坐标的对象NSArray,则使用polygonWithCoordinates:count: 方法而不是polygonWithPoints:count: 会更容易。

polygonWithCoordinates:count: 方法接受 CLLocationCoordinate2D 结构的 C 数组。 CLLocation 对象中的 coordinate 属性也是 CLLocationCoordinate2D

如果您仍想使用polygonWithPoints:count:,可以使用MKMapPointForCoordinate 函数将CLLocation 中的coordinate 属性转换为MKMapPoint

使用任一方法,您首先创建一个适当结构的 C 数组,循环遍历 NSArray 以设置 C 数组中的每个项目。然后拨打polygonWithCoordinatespolygonWithPoints

This answer 有一个使用polygonWithCoordinates 的代码示例。在该示例中,您可以将 for 循环中的两行更改为:

CLLocation *coordObj = (CLLocation *)[coordinateData objectAtIndex:i];
coords[i] = coordObj.coordinate;

不要忘记实现 viewForOverlay 委托方法(并确保已设置地图视图的 delegate 属性)。

【讨论】:

以上是关于将 CLLocation 对象转换为 MKMapPoint 结构的主要内容,如果未能解决你的问题,请参考以下文章

如何将位置:[CLLocation] 转换为 Coordinate2D?

将 CLLocation 或 CLLocationCoordinate2D 转换为 CGPoint

快速将 PFGeoPoint Lat 和 Long 从 Parse 转换为 CLLocation Lat 和 Long

在 Swift 中将 CLLocationCoordinate2D 转换为 CLLocation 时出错

在 CoreData 中保存 Swift CLLocation

在 Swift 中将 CLLocation 转换为 MKMapItem