Leaflet polyline disappears on pan

2020-02-01 15:34发布

问题:

I have a Leaflet map with a polyline and a whole bunch of icons. When I pan the map along the line, the icons are always visible but the line disappears. This happens while the map is being dragged (if I am panning slowly), or while the map is moving (if I quickly grab the map and release with a flicking motion). The polyline behavior is the same with or without { renderer: L.canvas() }.

Why does this happen and how can I make the line be visible while panning?

var mymap = L.map('mapid').setView([51.505, -0.09], 10);

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpandmbXliNDBjZWd2M2x6bDk3c2ZtOTkifQ._QA7i5Mpkd_m30IGElHziw', {
  maxZoom: 18,
  attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
    '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
    'Imagery © <a href="http://mapbox.com">Mapbox</a>',
  id: 'mapbox.streets'
}).addTo(mymap);

var array = [];
for (var counter = 0; counter < 100; counter++) {
  array[counter] = [51.505 - counter * 0.1, -0.09 - counter * 0.1]
}

L.polyline(array, {
  renderer: L.canvas()
}).addTo(mymap);
for (var index = 0; index < array.length; index++) {
  var latlng = array[index];
  L.marker(latlng).addTo(mymap);
}
#mapid {
  height: 90vh;
}
<script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>
<link href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" rel="stylesheet" />

<div id="mapid"></div>

And the same demo, as a JSFiddle: https://jsfiddle.net/xbxrtx50/1/

回答1:

Why does this happen?

Performance.

Drawing things with SVG or Canvas is computationally expensive, and blocks the UI thread, so Leaflet does it as few times as possible. This means redrawing only when there is no zoom or pan interaction going on.

and how can I make the line be visible while panning?

Instantiate your L.Renderer manually (either L.SVG or L.Canvas), and use its padding option to make it much larger than the visible size of the map. That will alleviate the rendering artifacts.

You might also want to try out Leaflet.VectorGrid.Slicer, which should render the geometries in a tiled manner while the map is being panned around.



标签: leaflet