autopan
by Leo
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0-rc.1/leaflet-src.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0-rc.1/leaflet.css">
<body>
<div id="mapWrapper">
<div id="map" ></div>
</div>
</body>
CSS
html, body, #map {
margin: 0;
width: 100%;
height: 100%;
}
#mapWrapper
{
padding: 10px;
margin: 10px;
width: 100%;
height: 100%;
}
JavaScript
var map = new L.Map('map', {
center: new L.LatLng(45.5 + 0.003,-73.5 + 0.003),
zoom: 16
});
// create the tile layer with correct attribution
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors';
var osm = new L.TileLayer(osmUrl, {attribution: osmAttrib});
map.addLayer(osm);
//L.tileLayer('https://{s}.tile.osm.org/{z}/{x}/{y}.png', {attribution: '© <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'}).addTo(map);
var marker = L.marker(
[45.5 , -73.5 ],
{
draggable: true,
icon: new L.Icon({
iconAnchor: new L.Point(12, 40),
iconUrl: 'https://cdn0.iconfinder.com/data/icons/small-n-flat/24/678111-map-marker-32.png'
})
});
marker.on('dragstart', function(e){
});
marker.on('dragend', function(e){
});
var panOptions = {a:0.90,b:0.90,n:5,maxVelocity:50};
marker.on('drag', function(e){
//Transform mouse coordinates [0,0] to [mapSizeX,mapSizeY] to [-1,+1] to [+1,-1] coordinates
var halfMapSize = map.getSize()._divideBy(2),
//Fix event for touch input
fixedEvent = (e.originalEvent.touches && e.originalEvent.touches.length === 1) ? e.originalEvent.touches[0] : e.originalEvent,
dragPoint = map.mouseEventToContainerPoint(fixedEvent),
scaledPoint = dragPoint.subtract(halfMapSize).unscaleBy(halfMapSize),
superEllipse = Math.pow(Math.abs(scaledPoint.x/panOptions.a),panOptions.n) + Math.pow(Math.abs(scaledPoint.y/panOptions.b),panOptions.n);
if(superEllipse >= 1) {
/*
* Calculate smooth increase of pan by moving further to the edge by calculating
* first a index between 0 (the pan bounding box edge) to 1 (the map edge)
* and then plug that value into a sigmoid function to get a smooth transition
...