我正在寻找一种方法来检测用户是在荷兰还是在比利时。我不想调用 API 或使用用户电话服务,所以一切都需要在本地完成,并且应该是简单快捷的小检查。我每秒都有用户的位置,并且想每分钟检查一次。
目标:
用户正在使用我们的应用程序旅行,我想在他/她到达比利时/荷兰时展示不同的 View 。
我从 http://www.diva-gis.org/datadown 中找到了两个形状文件与荷兰和比利时。这些文件非常小,现在我正在寻找一种方法来创建这个方法:
- (BOOL)isUserInNetherlands:(CLLocation)location;
应该检查位置是否在 shapefile 的内容中。
荷兰的 shapefile 如下所示:
我可以将 shapefile 转换为 sqlLite 数据库,但不知道下一步该做什么。
有任何想法吗?
最佳答案
一种方法是:
1)将shapefile转换为geoJson
2)在您的代码中加载geoJson文件数据。
3)从这些gps点创建多边形(注意:CountryDetectorController是我的 Controller 类)
+ (MKPolygon *)overlaysFromPolygons:(NSArray *)polygons title:(NSString *)title;
{
NSMutableArray *interiorPolygons = [NSMutableArray arrayWithCapacity:[polygons count] - 1];
for (int i = 1; i < [polygons count]; i++) {
[interiorPolygons addObject:[CountryDetectorController polygonFromPoints:polygons[i] interiorPolygons:nil]];
}
MKPolygon *overlayPolygon = [CountryDetectorController polygonFromPoints:polygons[0] interiorPolygons:interiorPolygons];
overlayPolygon.title = title;
return overlayPolygon;
}
+ (MKPolygon *)polygonFromPoints:(NSArray *)points interiorPolygons:(NSArray *)polygons;
{
NSInteger numberOfCoordinates = [points count];
CLLocationCoordinate2D *polygonPoints = malloc(numberOfCoordinates * sizeof(CLLocationCoordinate2D));
NSInteger index = 0;
for (NSArray *pointArray in points) {
polygonPoints[index] = CLLocationCoordinate2DMake([pointArray[1] floatValue], [pointArray[0] floatValue]);
index++;
}
MKPolygon *polygon;
if (polygons) {
polygon = [MKPolygon polygonWithCoordinates:polygonPoints count:numberOfCoordinates interiorPolygons:polygons];
} else {
polygon = [MKPolygon polygonWithCoordinates:polygonPoints count:numberOfCoordinates];
}
free(polygonPoints);
return polygon;
}
4)从多边形创建一个CGPath
+ (CGPathRef)pathForPolygon:(MKPolygon*)aPolygon;
{
CGMutablePathRef mpr = CGPathCreateMutable();
MKMapPoint *polygonPoints = aPolygon.points;
size_t nCount = aPolygon.pointCount;
for (int p = 0; p < nCount; p++)
{
MKMapPoint mp = polygonPoints[p];
if (p == 0)
CGPathMoveToPoint(mpr, NULL, mp.x, mp.y);
else
CGPathAddLineToPoint(mpr, NULL, mp.x, mp.y);
}
return mpr; //Keep in memory;
}
5) 检查坐标是否在 CGPath 中(pathsBelgium 是一个 NSValue 为 CGPaths 的数组)
- (void)checkCoordinate:(CLLocationCoordinate2D)coordinate;
{
MKMapPoint mapPoint = MKMapPointForCoordinate(coordinate);
CGPoint mapPointAsCGP = CGPointMake(mapPoint.x, mapPoint.y);
BOOL userIsInBelgium = FALSE;
for(NSValue *valuePathBE in pathsBelgium)
{
CGPathRef pathBe;
[valuePathBE getValue:&pathBe];
BOOL pointInBelgium = CGPathContainsPoint(pathBe, NULL, mapPointAsCGP, FALSE);
if(pointInBelgium)
{
userIsInBelgium = TRUE;
break;
}
}
NSLog(@"User is in Belgium: %i", userIsInBelgium);
}
关于ios - 检查 CLLocation 是否处于形状中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27783855/