150

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 calling the initialize function?

function initialize() {
map = L.map('map');
L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', {
    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://cloudmade.com">CloudMade</a>'
}).addTo(map);

map.locate({setView: true, maxZoom: 8});    
} 
jww
  • 97,681
  • 90
  • 411
  • 885
Joel James
  • 3,870
  • 9
  • 32
  • 47

6 Answers6

225

For example:

map.panTo(new L.LatLng(40.737, -73.923));
Paulo Rodrigues
  • 5,273
  • 7
  • 35
  • 58
158

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.

GoTo
  • 5,966
  • 2
  • 28
  • 31
Greg Wilson
  • 2,380
  • 2
  • 15
  • 14
15

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);
SHR
  • 7,940
  • 9
  • 38
  • 57
Stefan Nedelcu
  • 167
  • 1
  • 4
7

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.

LatinRickshaw
  • 85
  • 1
  • 7
1

In the case of map-centering problem despite using panTo(),flyTo() or setView() try to adjust the map with map.invalidateSize():

setTimeout(function () {
    map.invalidateSize(true);
}, 100);

jQuery sample:

$(document).ready(function () {
    mymap.invalidateSize();
});
Jasom Dotnet
  • 1,225
  • 12
  • 17
0

I was looking for a way to change the bounds but without the animation. This worked for me:

var bounds = L.latLng(40.737, -73.923).toBounds();
map.fitBounds(bounds, {animation: false});
Akaisteph7
  • 5,034
  • 2
  • 20
  • 43