Vue2leaflet: fitBounds to markers

Created on 17 Dec 2017  路  7Comments  路  Source: vue-leaflet/Vue2Leaflet

Great Vue plugin!

Apologies if this isn't a question specific to your plugin, I'm not sure if there's an easier way to do this. I am struggling figuring out how to retrieve all markers on the map in order to fit the bounds of the map automatically. I've looked at this.$ref.map.mapObject._layers, and saw suggestions online to look for layers that have a .feature property, but despite having a marker/markers on the map, I'm not seeing anything that looks like the marker instance. Any suggestions?

I'm also wondering if this will even be possible, if you don't have a component for FeatureGroup...

<v-map v-if="collection" ref="map" :zoom=-1 :center="[47.413220, -1.219482]">
  <v-tilelayer :url="`https://api.mapbox.com/styles/v1/mapbox/${map_id}/tiles/{z}/{x}/{y}?access_token=${access_token}`" />

  <v-marker-cluster ref="cluster">
    <v-marker
    ref="marker"
    v-for="(model, index) in collection.models"
    v-if="model.acf.location !== null"
    :lat-lng="[model.acf.location.lat, model.acf.location.lng]"
    :key="index">
      <v-popup :content="model.acf.content"></v-popup>
    </v-marker>
  </v-marker-cluster>
</v-map>
this.$refs.map.mapObject.eachLayer(layer => {
  console.log('feature', layer.feature) // undefined
})

Thanks!

Most helpful comment

@ThomasKientz You are over-complicating it :)

Look there
image
https://leafletjs.com/reference-1.6.0.html#latlngbounds

The fitBounds accept an array of [lat,lng] items, so it is as simple as looping over your markers getting lat and long with a simple .map function, as a track

this.$refs.map.mapObject.fitBounds(this.markers.map(m => { return [m.lat, m.lng] }))

All 7 comments

Why are you trying to retrieve markers from the map as the data comes originally from collection.models?

My advice would be to calculate bounds from collection.models as a computed property.

Let me know if that helps.

Closing as no answer for a while.

Sorry, yes your approach was the correct one, thank you!

Good to hear it works for you! 馃憤

@nickforddesign @KoRiGaN How did you do ?

I have tried with no success

```vue.js

```

@ThomasKientz You are over-complicating it :)

Look there
image
https://leafletjs.com/reference-1.6.0.html#latlngbounds

The fitBounds accept an array of [lat,lng] items, so it is as simple as looping over your markers getting lat and long with a simple .map function, as a track

this.$refs.map.mapObject.fitBounds(this.markers.map(m => { return [m.lat, m.lng] }))

@wannymiarelli thanks that works, i was doing the same thing .. overcomplicating things when not even needed :P

Was this page helpful?
0 / 5 - 0 ratings

Related issues

DmitriyVTitov picture DmitriyVTitov  路  4Comments

rSammy picture rSammy  路  3Comments

CharlesOkwuagwu picture CharlesOkwuagwu  路  5Comments

digEmAll picture digEmAll  路  4Comments

carlmjohnson picture carlmjohnson  路  4Comments