Leaflet draggable Marker
you can use map.panTo():
function onMapClick(e) {
marker = new L.marker(e.latlng, {draggable:'true'});
marker.on('dragend', function(event){
var marker = event.target;
var position = marker.getLatLng();
marker.setLatLng(new L.LatLng(position.lat, position.lng),{draggable:'true'});
map.panTo(new L.LatLng(position.lat, position.lng))
});
map.addLayer(marker);
};
map.on('click', onMapClick);
Complete html with inline js (minus cloudmade api):
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.1/leaflet.css" />
<!--[if lte IE 8]>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.1/leaflet.ie.css" />
<![endif]-->
<script src="http://cdn.leafletjs.com/leaflet-0.7.1/leaflet.js"></script>
<div id="map" style="width: 600px; height: 600px;"></div>
<script>
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('http://{s}.tile.cloudmade.com/API-KEY/997/256/{z}/{x}/{y}.png', {
attribution: 'Map data © <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>',
maxZoom: 18
}).addTo(map);
function onMapClick(e) {
marker = new L.marker(e.latlng, {draggable:'true'});
marker.on('dragend', function(event){
var marker = event.target;
var position = marker.getLatLng();
marker.setLatLng(new L.LatLng(position.lat, position.lng),{draggable:'true'});
map.panTo(new L.LatLng(position.lat, position.lng))
});
map.addLayer(marker);
};
map.on('click', onMapClick);
</script>
In case someone else stumbles upon this and needs a live pan, too.
Just remove the click event like so:
var marker = new L.marker([lat,lon],{
draggable: true
}).addTo(map);
marker.on("drag", function(e) {
var marker = e.target;
var position = marker.getLatLng();
map.panTo(new L.LatLng(position.lat, position.lng));
});
I wished it would be even more real time, it lags a little behind the mouse.
Leaflet now provides this as an option with creating a marker, so there is no need to attach a drag event to pan the map.
Link to docs: https://leafletjs.com/reference-1.3.4.html#marker-autopan
Code sample:
var marker = new L.marker([lat,lon],{
draggable: true,
autoPan: true
}).addTo(map);