我有下面的快速代码,它绘制一个多边形并在 MKMapView 上添加注释。我想弄清楚如何识别注释的坐标是否在多边形内?
import UIKit
import MapKit
class ViewController: UIViewController {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
let initialLocation = CLLocation(latitude: 49.140838, longitude: -123.127886)
centerMapOnLocation(initialLocation)
addBoundry()
var annotation = MKPointAnnotation()
annotation.coordinate = point1
annotation.title = "Roatan"
annotation.subtitle = "Honduras"
mapView.addAnnotation(annotation)
}
var points = [CLLocationCoordinate2DMake(49.142677, -123.135139),
CLLocationCoordinate2DMake(49.142730, -123.125794),
CLLocationCoordinate2DMake(49.140874, -123.125805),
CLLocationCoordinate2DMake(49.140885, -123.135214)]
var point1 = CLLocationCoordinate2DMake(49.141821, -123.131577)
func addBoundry() {
let polygon = MKPolygon(coordinates: &points, count: points.count)
mapView.addOverlay(polygon)
}
let regionRadius: CLLocationDistance = 1000
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius * 2.0, regionRadius * 2.0)
mapView.setRegion(coordinateRegion, animated: true)
}
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if overlay is MKPolygon {
let polygonView = MKPolygonRenderer(overlay: overlay)
polygonView.strokeColor = UIColor.magentaColor()
return polygonView
}
return nil
}
}
我创建了 @StefanS 答案的 Swift 版本,并通过从此移植代码使其更易于阅读answer
func isPoint(point: MKMapPoint, insidePolygon poly: MKPolygon) -> Bool {
let polygonVerticies = poly.points()
var isInsidePolygon = false
for i in 0..<poly.pointCount {
let vertex = polygonVerticies[i]
let nextVertex = polygonVerticies[(i + 1) % poly.pointCount]
// The vertices of the edge we are checking.
let xp0 = vertex.x
let yp0 = vertex.y
let xp1 = nextVertex.x
let yp1 = nextVertex.y
if ((yp0 <= point.y) && (yp1 > point.y) || (yp1 <= point.y) && (yp0 > point.y))
{
// If so, get the point where it crosses that line. This is a simple solution
// to a linear equation. Note that we can't get a division by zero here -
// if yp1 == yp0 then the above if be false.
let cross = (xp1 - xp0) * (point.y - yp0) / (yp1 - yp0) + xp0
// Finally check if it crosses to the left of our test point. You could equally
// do right and it should give the same result.
if cross < point.x {
isInsidePolygon = !isInsidePolygon
}
}
}
return isInsidePolygon
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)