如何通过地理坐标检索Mapbox中对应区域的要素?
问题描述
我将上传至Mapbox Studio的GeoJSON文件中的MultiPolygon要素渲染到自定义地图样式中,希望判断用户当前位置是否处于这些要素内,并获取要素的id与属性。尝试使用queryRenderedFeatures方法,但返回success([])无结果,推测该方法需要画布/屏幕坐标,而我使用的是地理坐标。调用代码如下:
let features = map.queryRenderedFeatures( with: [CGPoint(x: 46.231944, y: 10.826111)], options: RenderedQueryOptions(layerIds: ["micro-regions"], filter: nil), // 打印返回`success([])` completion: { matches in print(matches) } ) // features 是 `MBXCancelableProxy`
样式设置如下:
解决方法
方法1:将地理坐标转换为屏幕坐标后查询
queryRenderedFeatures确实需要屏幕坐标(CGPoint),你可以通过Mapbox地图视图的convert(_:to:)方法把地理坐标(CLLocationCoordinate2D)转换成屏幕坐标,再执行查询:
// 定义用户的地理坐标 let userLocation = CLLocationCoordinate2D(latitude: 46.231944, longitude: 10.826111) // 转换为屏幕坐标 let screenPoint = mapView.convert(userLocation, to: .mapView) // 执行查询 let features = map.queryRenderedFeatures( with: [screenPoint], options: RenderedQueryOptions(layerIds: ["micro-regions"], filter: nil), completion: { matches in print(matches) // 遍历匹配结果获取id和属性 matches.forEach { feature in print("要素ID: \(feature.id),属性: \(feature.properties)") } } )
注意:这种方式依赖要素在当前地图视口中被渲染出来,如果缩放级别过低、要素超出屏幕范围,会查询不到结果。
方法2:直接查询数据源(更可靠)
如果只是判断点是否在多边形内,推荐使用querySourceFeatures直接查询数据源,该方法不依赖要素是否在屏幕上渲染,更适合空间判断场景:
// 构造空间过滤条件:判断点是否在多边形要素内 let filter = NSPredicate(format: "CONTAINS(%K, %@)", "$geometry", CLLocationCoordinate2D(latitude: 46.231944, longitude: 10.826111)) // 执行数据源查询,替换"your-source-id"为你在Mapbox Studio中上传的GeoJSON数据源ID map.querySourceFeatures( withIdentifier: "your-source-id", options: SourceQueryOptions(layerIds: ["micro-regions"], filter: filter), completion: { result in switch result { case .success(let matchedFeatures): print("匹配到的要素:\(matchedFeatures)") matchedFeatures.forEach { feature in print("要素ID: \(feature.id),属性: \(feature.properties)") } case .failure(let error): print("查询失败:\(error.localizedDescription)") } } )
你可以在Mapbox Studio的样式编辑器中找到数据源ID,对应你上传的GeoJSON数据源的标识。
内容的提问来源于stack exchange,提问作者Fez Vrasta
相关产品推荐
相关产品推荐

