GeoLocation - 居中地图

GeoLocation - Center a map

我正在使用传单库创建带有标记的地图。

var mymap = L.map('mapid', {
        center: [${mapCenter.lat}, ${mapCenter.lng}],
        zoom: 9
});

我正在使用此算法根据我必须显示的所有标记来计算地图的中心

        double minLatitude = Double.MAX_VALUE;
        double maxLatitude = Double.MIN_VALUE;

        double minLongitude = Double.MAX_VALUE;
        double maxLongitude = Double.MIN_VALUE;

        for (ViewMarker marker : markers) {

            if (marker.getLng() > maxLongitude) {
                maxLongitude = marker.getLng();
            }

            if (marker.getLng() < minLongitude) {
                minLongitude = marker.getLng();
            }

            if (marker.getLat() > maxLatitude) {
                maxLatitude = marker.getLat();
            }

            if (marker.getLat() < minLatitude) {
                minLatitude = marker.getLat();
            }                       
        }

        double centerLatitude =     (minLatitude  + maxLatitude ) / 2;
        double centerLongitude =    (minLongitude + maxLongitude) / 2;

但是正如你在图片中看到的,我不会说地图在中心

实例化一个L.LatLngBounds, insert the markers' LatLngs there, and then do a map.fitBounds()

或者,使用 FeatureGroup 将所有标记保存在内部,因为它提供了 getBounds().

除非您了解大地测量学和地图投影的基础知识,否则不要使用像 centerlat = (lat1 + lat2) / 2 这样天真的解决方案,这对于默认的墨卡托投影是不正确的。