vue-leaflet/Vue2Leaflet

[Question] How to fit all geoJson geometries on the view?

Closed this issue · 1 comments

I have a variable quantity of geoJsons (Polygons) layers on my map. How can I adjust the view to fit all geometries?

 <l-map ref="mapControl" :zoom="zoom" :center="center" :options="mapOptions">
      <l-tile-layer :url="url" :attribution="attribution"/>
      <l-control-zoom position="bottomright"/>

      <l-geo-json v-for="sector in geoSectors" :key="sector.id" :geojson="sector" :options="options" :options-style="styleFunction"/>

    <l-geo-json v-if="showBase" :geojson="geoBase" :options="options" :options-style="styleFunction"/>
</l-map>

I believe that I can access the fitBounds like this:

this.$refs.mapControl.mapObject.fitBounds(bounds);

But how can I get the bounds of the list of geoJsons?

Versions

  • Leaflet: ^1.6.0
  • Vue: ^2.6.11
  • Vue2Leaflet: ^2.5.2

I managed to solve it.

Here's the code:

//You need to import featureGroup from leaflet.
import { latLng, featureGroup } from "leaflet";

//After building your geoJson layers, just add this:
this.$nextTick().then(() => {
    var group = new featureGroup();

    this.$refs.mapControl.mapObject.eachLayer(function(layer) {
        if (layer.feature != undefined)
            group.addLayer(layer);
    });

    this.$refs.mapControl.mapObject.fitBounds(group.getBounds(), { padding: [20, 20] });
});