繁体   English   中英

地图未在 Leaflet.js 中居中

[英]Map not centered in leaflet.js



        var counties = $.ajax({
            url: "{% url 'api_master_center'  %}",
            dataType: "json",
            success: console.log("County data successfully loaded."),
            error: function (xhr) {
                alert(xhr.statusText)
            }
        })

        $.when(counties).done(function () {

            var map = L.map('map', {
                center: [51.505, -0.09],
                zoom: 13
            })
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {
                foo: 'bar',
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(map);



            L.geoJSON(counties.responseJSON, {
                pointToLayer: function (feature, latlng) {
                    return L.marker(latlng);
                }
            }).addTo(map);
            console.log(counties.responseJSON)

        });
    </script>

`

我使用leaflet.js 和jQuery,我通过api 从后端到python 获取数据。我正在创建一个地图。 后来我添加了一个标记。我的问题是当地图被渲染而标记不在聚光灯下时。重点是地图初始化时创建的坐标。 我希望标记成为焦点,我该如何解决这个问题?`

您可以获取geoJSON图层的边界并将地图居中:

var geo = L.geoJSON(counties.responseJSON, {
                pointToLayer: function (feature, latlng) {
                    return L.marker(latlng);
                }
            }).addTo(map);

map.fitBounds(geo.getBounds());

我通过添加 map.setView(latlng); 解决了我的问题;

                pointToLayer: function (feature, latlng) {
                    map.setView(latlng);
                    return L.marker(latlng);
                }
            }).addTo(map);
            console.log(counties.responseJSON);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM