How to change the map center in Leaflet.js

后端 未结 4 1165
无人及你
无人及你 2020-12-23 00:34

The following code initializes a leaflet map. The initialize function centers the map based on user location. How do I change the center of the map to a new position after c

相关标签:
4条回答
  • 2020-12-23 00:48

    Use map.panTo(); does not do anything if the point is in the current view. Use map.setView() instead.

    I had a polyline and I had to center map to a new point in polyline at every second. Check the code : GOOD: https://jsfiddle.net/nstudor/xcmdwfjk/

    mymap.setView(point, 11, { animation: true });        
    

    BAD: https://jsfiddle.net/nstudor/Lgahv905/

    mymap.panTo(point);
    mymap.setZoom(11);
    
    0 讨论(0)
  • 2020-12-23 00:54

    You can also use:

    map.setView(new L.LatLng(40.737, -73.923), 8);
    

    It just depends on what behavior you want. map.panTo() will pan to the location with zoom/pan animation, while map.setView() immediately set the new view to the desired location/zoom level.

    0 讨论(0)
  • 2020-12-23 00:56

    You could also use:

    var latLon = L.latLng(40.737, -73.923);
    var bounds = latLon.toBounds(500); // 500 = metres
    map.panTo(latLon).fitBounds(bounds);
    

    This will set the view level to fit the bounds in the map leaflet.

    0 讨论(0)
  • 2020-12-23 01:05

    For example:

    map.panTo(new L.LatLng(40.737, -73.923));
    
    0 讨论(0)
提交回复
热议问题