简体   繁体   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>

` `

I use leaflet.js and jQuery, I get data via api from backend to python.I am creating a map.我使用leaflet.js 和jQuery,我通过api 从后端到python 获取数据。我正在创建一个地图。 And later I add a marker.My problem is when the map is rendered and the marker is not in the spotlight.The focus is on the coordinates that were created when the map was initialized.后来我添加了一个标记。我的问题是当地图被渲染而标记不在聚光灯下时。重点是地图初始化时创建的坐标。 I expect the marker to be the focus, how do I fix this?`我希望标记成为焦点,我该如何解决这个问题?`

You can get the bounds of the geoJSON layer and center the map to it:您可以获取geoJSON图层的边界并将地图居中:

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

map.fitBounds(geo.getBounds());

I solved my problem by adding map.setView(latlng);我通过添加 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