mpetazzoni / leaflet-gpx

A GPX track plugin for Leaflet.js
http://mpetazzoni.github.io/leaflet-gpx
BSD 2-Clause "Simplified" License
550 stars 119 forks source link

Bounds are not valid. #118

Closed simonmnt closed 3 years ago

simonmnt commented 3 years ago

Hi,

I try to center my map to show all gpx track, but is not working.

Uncaught Error: Bounds are not valid

My code:

let map = L.map(this, {
    center: [51.505, -0.09],
    zoom: 13
});

L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: 'Map data &copy; <a href="http://www.osm.org">OpenStreetMap</a>'
}).addTo(map);

this.maxBounds = L.latLngBounds();

randonneesItems.forEach((el, i) => {
    new L.GPX(el.dataset.filePath, {
        async: true,
        marker_options: {
            startIconUrl: '',
            endIconUrl: '',
            shadowUrl: ''
        }
    }).on('loaded', (e) => {
        this.maxBounds.extend(e.target.getBounds());
    }).addTo(map);
})

map.fitBounds(maxBounds);

I don't understand why it doesn't work..

mpetazzoni commented 3 years ago

This code won't work because it will call map.fitBounds() before the GPX is loaded, at which time your maxBounds object has not been extended yet. You should be doing this in the .on('loaded', ...) event handler function, as documented in the README: https://github.com/mpetazzoni/leaflet-gpx#usage