Mapbox的fitBounds函数可以设置地图视野范围,但不会渲染瓦片。

8

这里是我用JavaScript编写的在地图上渲染标记并适配地图边界的代码。

地图边界根据geojson进行适配,但问题在于当地图上有任何标记并尝试适应边界时,地图瓦片图像未能渲染。

地图上仅显示标记,没有瓦片图像。

var latLongCollection = [];
    var map;
    $(document).ready(function() {
    map();
    });


    function map() {
      map = L.mapbox.map('DivId', 'ProjectId');
      GetData();
     }

    function GetData() {
       $.ajax({
           type: "GET",
           url: someUrl,
           dataType: "json",
           contentType: "application/json; charset=utf-8",
           success: AjaxSuccess,
           error: function () {
           }
       });
    }

     function AjaxSuccess(data) {
      if (data == null || data.length == 0) {
          return;
      }

      var geoJson = {
          "type": "FeatureCollection",
          "features": []
      };

      $.each(data, function (index, value) {

          var latitude = parseFloat(value.Latitude),
              longitude = parseFloat(value.Longitude);

          if (latitude && longitude) {
              var dataJson = {
                  type: "Feature",
                  geometry: { type: "Point", coordinates: [longitude, latitude] },
                  properties: {
                      someProp: value.SomeProperty,
                      }
              };

              geoJson.features.push(vehicleJson);
          }
      });

      var markerLayer = L.mapbox.featureLayer(geoJson).addTo(map);

      markerLayer.eachLayer(function (marker) {
           var feature = marker.feature;
           var featureProperty = feature.properties;

           if (featureProperty.someProp) {
               marker.setIcon(L.divIcon({
                   html: 'htmlstring',
                   iconSize: [35, 75]
               }));
           }
           else {
               marker.setIcon(L.divIcon({
                   html: 'anotherhtmlstring',
                   iconSize: [35, 75]
               }));
           }

           latLongCollection.push(marker._latlng);
    });

     markerLayer.on('click', function (e) {
         map.panTo(e.layer.getLatLng());
     });

        if (latLongCollection.length > 0) {
           map.fitBounds(latLongCollection);
       }
    }
2个回答

15

如果还有人遇到这个问题,似乎这是Leaflet中的一个bug:https://github.com/Leaflet/Leaflet/issues/2021

在最新版本中已经修复了,但如果您无法更新,则可以通过设置超时来解决竞态条件:

setTimeout(function () {
    map.fitBounds(latLongCollection);
}, 0);

之后,我会尝试按照您所说的做。 - 111
1
将 Leaflet 升级到 v=0.7.5(最新版本)并不能解决这个问题。 - Jeevan Roy dsouza

0

你是怎么尝试调试这个问题的?你的网络和js控制台有什么提示?

试着缩小地图,也许fitBounds把你的地图缩放得太多了。我曾经遇到过这个问题。解决方案是在fitBounds中使用maxSize选项,请参考leaflet文档。


不,地图缩放级别不是最大的,也没有出现任何控制台错误。当我查看网络时,Mapbox JS中止了所有加载瓦片图像的请求,因此没有瓦片图像显示出来。 - 111

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接