检查用户位置是否在形状内 [英] Check if user location is inside a shape
问题描述
我使用此方法检查用户位置是否在地图视图(mapkit)的多边形内。
我传递给当前用户位置(CLLocationCoordinate2D)的方法并返回一个布尔值,只是为了知道用户是否在多边形中。
I made this method to check if an user location is inside a polygon on a map view (mapkit). I pass to the method the current user location (CLLocationCoordinate2D) and return a boolean just to know if the user is in a polygon or not.
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
}
我不知道我真的明白为什么,但用户永远不会在里面此测试后的多边形。 (而且我很确定他是)
I don't really understand why, but the user is never inside a polygon after this test. (and i'm pretty sure he is)
我认为我可能有针对x,y的纬度/经度的逻辑问题。
I think it's possible that i have a logic problem with lat/long against x,y.
有没有人有这样的工作?
Does anybody already have work with like this ?
提前感谢所有建议。
干杯
推荐答案
问题是您将 userLocation
从地图坐标转换为视图坐标,但在构建路径时,你没有将点转换为视图坐标。
The problem is that you are converting the userLocation
from the map coordinates to the view coordinates but when you build the path, you don't convert the points to the views coordinates.
你需要将 MKMapPoint
转换成a CLLocationCoordinate2D
然后到 CGPoint
。
You'll need to convert the MKMapPoint
to a CLLocationCoordinate2D
then to a CGPoint
.
let polygonMapPoint: MKMapPoint = arrPoints[i]
let polygonCoordinate = MKCoordinateForMapPoint(polygonPoint)
let polygonPoint self.mapView.convertCoordinate(polygonPointAsCoordinate, toPointToView: self.mapView)
然后在构建路径时使用 polygonPoint
Then use polygonPoint
when building the path
CGPathMoveToPoint(polygonPath, nil, polygonPoint.x, polygonPoint.y)
这篇关于检查用户位置是否在形状内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!