Domanda

I feel kind of stupid here...

I have several markers in a map area and need to find a way to pan and zoom to this area. The goal is be able to view all markers at once.

I insert the markers with this code:

function plotMarkers(MarkerItems) {
if (MarkerItems) {
    MarkerItems.success(function (data) {
        var len =  data.length;
        for (var i = 0; i < len; i++) {
            m = data[i];

            var XX = parseFloat(m.X.replace(",", "."));
            var YY = parseFloat(m.Y.replace(",", "."));
            var marker = L.marker(new L.LatLng(XX, YY), { icon: blueFlagIcon }).bindPopup("test");
            markers.addLayer(marker);
        }
    });// success
}
}


var markers = new L.featureGroup();
plotMarkers(myMarkers);
map.addLayer(markers);

Should be real simple, I just dont get my head around it.

Please help

È stato utile?

Soluzione 2

Quite simple....

Just needed to add

map.fitBounds(markers.getBounds());

inside of the .success().

Full working code:

function plotMarkers(MarkerItems) {
if (MarkerItems) {
MarkerItems.success(function (data) {
    var len =  data.length;
    for (var i = 0; i < len; i++) {
        m = data[i];

        var XX = parseFloat(m.X.replace(",", "."));
        var YY = parseFloat(m.Y.replace(",", "."));
        var marker = L.marker(new L.LatLng(XX, YY), { icon: blueFlagIcon }).bindPopup("test");
        markers.addLayer(marker);
    }

    map.addLayer(markers);
    map.fitBounds(markers.getBounds());

});// success
}}

Altri suggerimenti

Look at L.Map.fitBounds and L.FeatureGroup.getBounds. So probably your code will look like:

map.fitBounds(markers.getBounds());

But if your MarkerItems.success is asynchronous (ajax and etc.) you will call this code after adding markers to layer.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top