mapboxmapbox-ios

How can I retrieve the features a given coordinate point sits in?


I'm rendering a set of MultiPolygon features from a GeoJSON file uploaded to Mapbox Studio to my custom map style.

I would like to know if the user is currently located within one of those features and retrieve its id and properties.

I found queryRenderedFeatures but this doesn't work, it returns success([]) with no results. I suspect it expects canvas/screen coordinates but I need to use geo coordinates.

This is how I'm calling it:

let features = map.queryRenderedFeatures(
  with: [CGPoint(x: 46.231944, y: 10.826111)],
  options: RenderedQueryOptions(layerIds: ["micro-regions"], filter: nil),
  // this print returns `success([])`
  completion: { matches in print(matches) }
)      

// features is `MBXCancelableProxy`

This is how I setup the style: enter image description here


Solution

  • If you have geographic coordinates and need to convert them to screen coordinates, you should be able to use points() in the MapboxMap class.

    https://docs.mapbox.com/ios/maps/api/10.16.2/Classes/MapboxMap.html#/s:10MapboxMaps0A3MapC6points3forSaySo7CGPointVGSaySo22CLLocationCoordinate2DVG_tF

    See if this helps your queryRenderedFeatures call return the correct features.

    Another option is the Tilequery API, which you can pass a geographic point to. It will return features that are near that point for any tileset, and include a distance value in the response. If the distance to a polygon is 0, it means the point lies within the polygon.

    https://docs.mapbox.com/api/maps/tilequery/