Mapbox SDK v10 Filter Layer with Swift

291 Views Asked by At

i working on map project with swift . i created a dataset,tileset and style on studio and its working perfectly fine right now. ı need to add some filters on map so i create 2 layer for ac and dc. but i couldnt change layers with button. i tried this.

func showACStationLayer() { guard let style = mapView.style else { return }

    // Hide DC Station layer
    if let dcStationLayer = style.layer(withIdentifier: dcStationLayerIdentifier) {
        dcStationLayer.isVisible = false
    }

    // Show AC Station layer
    if let acStationLayer = style.layer(withIdentifier: acStationLayerIdentifier) {
        acStationLayer.isVisible = true
    } else {
        let acStationSource = VectorSource(identifier: "acStationSource", configuration: ["url": "your-source-url"])
        let acStationLayer = FillLayer(identifier: acStationLayerIdentifier, source: acStationSource)
        acStationLayer.fillColor = .red
        style.addLayer(acStationLayer)
    }
}

but there are some problems. idk can i explain my problem.

Or how can i filter my layer with button? Thank you so muchmapboxStudioLayers

1

There are 1 best solutions below

4
OdNairy On

You have to call mapView.mapboxMap.style.updateLayer(withId:type:update:) to update layer properties. The direct assignment has no effect. Take a look at the official sample code ShowHideLayerExample.

To filter POIs source data you have to set Layer.filter expression. Here is the sample that filters data by class property:

func filterPOILayer(for types: [String]) throws {
    try mapView.mapboxMap.style.updateLayer(withId: "poi-label", type: SymbolLayer.self) { layer in
        layer.filter = Exp(.match) {
            Expression(operator: .get, arguments: [.string("class")])
            types
            true
            false
        }
    }
}

I would recommend you to test expressions in the Mapbox Studio first. There you also can learn what types and classes of POIs are exist. For example, to show only Food POIs there is a food_and_drink class.