最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Leaflet zoom and pan - Stack Overflow

programmeradmin2浏览0评论

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

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

Share asked Apr 14, 2013 at 20:07 Richard HovdsveenRichard Hovdsveen 731 silver badge12 bronze badges 1
  • you're looking for the bounding box – flup Commented Apr 14, 2013 at 21:07
Add a ment  | 

2 Answers 2

Reset to default 7

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.

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
}}
发布评论

评论列表(0)

  1. 暂无评论