2015-08-21 64 views
5

此時,我正試圖弄清楚MKMapView上的座標是否在提前繪出的緯度/經度MKPolygon內。確定緯度/經度點是否在Mapview中的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 
    } 
+0

哎你會不會使用「假」(獲取纏繞風格的路徑)..最後一個參數CGPathContainsPoint。 – Fattie

+0

我已經嘗試了真假,但無濟於事。 :( –

回答

3

你是混亂CGPoints,這是X和Y座標對點的位置對你的看法,與CLLocationCoordinate2Ds,這是地球上的座標。

對於CGPathContainsPoint,你想在你polygonRenderer路徑傳遞和當前位置(從多邊形的viewDidLoad()創建)是這樣的:

let polygonRenderer = MKPolygonRenderer(polygon: polygon) 
let currentMapPoint: MKMapPoint = MKMapPointForCoordinate(locationManager.location?.coordinate) 
let polygonViewPoint: CGPoint = polygonRenderer.pointForMapPoint(currentMapPoint) 

if CGPathContainsPoint(polygonRenderer.path, nil, polygonViewPoint, true) { 
    print("Your location was inside your polygon.") 
} 

所以,你要想想,你應該把這個代碼,因爲你目前擁有它的地方是在MKOverlay在屏幕上繪製時被調用的函數內部,並且與此完全無關。

2

更新了斯威夫特3

let polygonRenderer = MKPolygonRenderer(polygon: polygon) 
let mapPoint: MKMapPoint = MKMapPointForCoordinate(coordinate) 
let polygonViewPoint: CGPoint = polygonRenderer.point(for: mapPoint) 

if polygonRenderer.path.contains(polygonViewPoint) 
{ 
    print("Your location was inside your polygon.") 
} 
相關問題