I have a FillLayer with polygons generated from a local geojson file. I want to add interactivity to these polygons but am not sure how to do it with the iOS SDK. I found an example that is able to do something similar to what I need to do but in the Mapbox-GL-JS environment:
https://docs.mapbox.com/mapbox-gl-js/example/polygon-popup-on-click/
You can add a gesture recognizer to the map in the iOS SDK like this
mapView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.mapClickedFunction)))
but you can't seem to add a gesture recognizer to the layer or the polygons inside the layer. Any help on this would be much appreciated!
Use the tap point received from the gesture recognizer to query the map for rendered features at the given point within the layer specified.
@objc public func findFeatures(_ sender: UITapGestureRecognizer) {
let tapPoint = sender.location(in: mapView)
mapView.mapboxMap.queryRenderedFeatures(
with: tapPoint,
options: RenderedQueryOptions(layerIds: ["US-states"], filter: nil)) { [weak self] result in
switch result {
case .success(let queriedfeatures):
if let firstFeature = queriedfeatures.first?.feature.properties,
case let .string(stateName) = firstFeature["STATE_NAME"] {
self?.showAlert(with: "You selected \(stateName)")
}
case .failure(let error):
self?.showAlert(with: "An error occurred: \(error.localizedDescription)")
}
}
}
This is a chunk of code from MapBox examples. The logic is to put the gesture recognizer on the map view. When a tap gesture is received you get the location where user tapped as CGPoint
coordinate inside the map view. Then you send it to MapboxMap
in order to get a list o features that contain that point.
I recommend you to take a look at the official Mapbox repository that contains a lot of ways of doing things: https://github.com/mapbox/mapbox-maps-ios/tree/main/Apps/Examples
Have a nice day!