地图未居中 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. 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?`

您可以获取 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);