检查用户位置是否在形状内
我做了这个方法来检查用户位置是否在地图视图(mapkit)的多边形内。 我传递给当前用户位置(CLLocationCoordinate2D)的方法并返回一个布尔值,只是为了知道用户是否在多边形中。
func userInsidePolygon(userlocation: CLLocationCoordinate2D ) -> Bool{ // get every overlay on the map let o = self.mapView.overlays // loop every overlay on map for overlay in o { // handle only polygon if overlay is MKPolygon{ let polygon:MKPolygon = overlay as! MKPolygon let polygonPath:CGMutablePathRef = CGPathCreateMutable() // get points of polygon let arrPoints = polygon.points() // create cgpath for (var i:Int=0; i < polygon.pointCount; i++){ let mp:MKMapPoint = arrPoints[i] if (i == 0){ CGPathMoveToPoint(polygonPath, nil, CGFloat(mp.x), CGFloat(mp.y)) } else{ CGPathAddLineToPoint(polygonPath, nil, CGFloat(mp.x), CGFloat(mp.y)) } } let mapPointAsCGP:CGPoint = self.mapView.convertCoordinate(userlocation, toPointToView: self.mapView) return CGPathContainsPoint(polygonPath , nil, mapPointAsCGP, false) } } return false }
我真的不明白为什么,但是在测试之后用户永远不会在多边形内。 (而且我很确定他是)
我认为对于x,y我可能有lat / long的逻辑问题。
有没有人有这样的工作?
提前感谢所有建议。
干杯
问题是您正在将userLocation
从地图坐标转换为视图坐标,但在构建路径时,不会将点转换为视图坐标。
您需要将MKMapPoint
转换为CLLocationCoordinate2D
然后转换为CGPoint
。
let polygonMapPoint: MKMapPoint = arrPoints[i] let polygonCoordinate = MKCoordinateForMapPoint(polygonPoint) let polygonPoint self.mapView.convertCoordinate(polygonPointAsCoordinate, toPointToView: self.mapView)
然后在构建路径时使用polygonPoint
CGPathMoveToPoint(polygonPath, nil, polygonPoint.x, polygonPoint.y)
Swift 3,Xcode 8回答:
func userInsidePolygon(userlocation: CLLocationCoordinate2D ) -> Bool { var containsPoint: Bool = false // get every overlay on the map let o = self.mapView.overlays // loop every overlay on map for overlay in o { // handle only polygon if overlay is MKPolygon{ let polygon:MKPolygon = overlay as! MKPolygon let polygonPath:CGMutablePath = CGMutablePath() // get points of polygon let arrPoints = polygon.points() // create cgpath for i in 0..