此刻,我试图弄清楚 MKMapView 上的坐标是否在提前绘制的具有纬度/经度的 MKPolygon 内。
我正在使用 CGPathContainsPoint 来确定坐标是否在地图上的多边形内,但无论我选择什么坐标,它总是返回 false。
谁能解释一下到底出了什么问题?下面是我在 Swift 中的代码。
class ViewController: UIViewController, MKMapViewDelegate
@IBOutlet weak var mapView: MKMapView!
let initialLocation = CLLocation(latitude: 43.656734, longitude: -79.381576)
let point = CGPointMake(43.656734, -79.381576)
let regionRadius: CLLocationDistance = 500
let point1 = CLLocationCoordinate2D(latitude: 43.656734, longitude: -79.381576)
var points = [CLLocationCoordinate2DMake(43.655782, -79.382094),
CLLocationCoordinate2DMake(43.657499, -79.382310),
CLLocationCoordinate2DMake(43.656656, -79.380497),
CLLocationCoordinate2DMake(43.655782, -79.382094)]
override func viewDidLoad() {
super.viewDidLoad()
centerMapOnLocation(initialLocation)
let polygon = MKPolygon(coordinates: &points, count: points.count)
mapView.addOverlay(polygon)
var annotation = MKPointAnnotation()
annotation.coordinate = point1
annotation.title = "Test"
annotation.subtitle = "Test"
mapView.addAnnotation(annotation)
self.mapView.delegate = self
}
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.redColor()
if CGPathContainsPoint(polygonView.path, nil, CGPointMake(43.656734, -79.381576), true) {
print("True!!!!!")
} else {
println("False")
}
return polygonView
}
return nil
}