w2olves
w2olves

Reputation: 2329

Centering a leaflet map when marker is close to the edges

I am not sure what the exact technical term for this question would be so please pardon the noobish question.

I have a leaflet map like this:

 var map = L.map("dvMapContainer",
                {

                }).setView([39.782388193, -86.14135265], 14);

I am adding a marker to this map like this:

 var vehicleMarker = new L.Marker([39.782388193, -86.14135265], { id: 'vehicle', icon: cssIcon });
  map.addLayer(vehicleMarker);

Every few seconds, I update the position of the vehicleMarker and center the map

  vehicleMarker.setLatLng(newLatLng);
                                map.setView(newLatLng, 18);

This works fine however the effect is not very visually pleasing as the map is constantly moving. I would like to move only the marker until it gets close to the edge of the map and then recenter the map. Is that possible ? Any hints/solutions will be much appreciated.

Upvotes: 0

Views: 589

Answers (1)

Corvae
Corvae

Reputation: 308

Each time you check (every few seconds), you can compare your marker location with the map bounds:

var bounds = map.getBounds();
if(vehicleMarker.getLatLng().lng > bounds.getEast()-.001 || vehicleMarker.getLatLng().lng < bounds.getWest()+.001 || vehicleMarker.getLatLng().lat > bounds.getNorth()-.001 || vehicleMarker.getLatLng().lat < bounds.getSouth()+.001)
    //change bounds

If your next marker location is close to your current bounds, then change your map's current bounds.

You can change the .001 depending on how far zoomed out you are.

More info on bounds here: http://leafletjs.com/reference.html#latlngbounds

Upvotes: 2

Related Questions