Mapbox GL JS: scale to filtered polygon?

I am using Mapbox GL JS to display a polygon layer. I would allow the user to select a name from the drop-down list, and then select and scale the corresponding polygon.

I already know how to select a matching polygon with map.setFilter, but I don't know how to zoom in to the corresponding polygons. This is my current code:

map.addLayer({
    'id': 'polygon_hover',
    'source': 'mysource',
    'source-layer': 'mylayer',
    'type': 'fill',
    'paint': {
        'fill-color': 'red',
        "fill-opacity": 0.6
    },
    "filter": ["==", 'CUSTNAME', ""]
});
// Get details from dropdown
custname.on("change", function(e) {
    // get details of name from select event
    map.setFilter('polygon_hover', ["==", 'CUSTNAME', name]);
    // Get bounds of filtered polygon somehow?
    // var bounds = ??;
    // map.fitBounds(bounds);
});

I examined the Mapbox window binding example , but it assumes that you already know what borders are.

Is there a way to get the polygon borders matching the map filter in Mapbox?

+6
source share
2 answers

. Leaflet polygon , , getBounds(), - -. Leaflet LngLat, LatLng. . Mapbox , .

var polygon = data.features[0].geometry.coordinates;
var fit = new L.Polygon(polygon).getBounds();
var southWest = new mapboxgl.LngLat(fit['_southWest']['lat'], fit['_southWest']['lng']);
var northEast = new mapboxgl.LngLat(fit['_northEast']['lat'], fit['_northEast']['lng']);
var center = new mapboxgl.LngLatBounds(southWest, northEast).getCenter();
// map.flyTo({center: center, zoom: 10});
map.fitBounds(new mapboxgl.LngLatBounds(southWest, northEast));
+1

Bounds Polygon:

var coordinates = f.geometry.coordinates[0];
var bounds = coordinates.reduce(function (bounds, coord) {
    return bounds.extend(coord);
}, new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));

map.fitBounds(bounds, {
    padding: 20
});

f - .

+1

Source: https://habr.com/ru/post/1015864/


All Articles