Dropping an image on a Leaflet map and create a marker
Note: This only works correctly if the whole map is visible in the viewport.
Leaflet is an an open-source JavaScript library
for mobile-friendly interactive maps http://leafletjs.com/
Here data is provided by OpenStreetMap
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0-beta.2.rc.2/leaflet.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0-beta.2.rc.2/leaflet.css">
<div id="map"></div>
<img src="https://static.twinesocial.com/uploads/appProfiles/3986IUR95CHD0LYJ.png" />
CSS
#map {
height: 80vh;
}
img {
height: 50px;
}
JavaScript
// center of the map
var center = [-33.8650, 151.2094];
// Create the map
var map = L.map('map').setView(center, 3);
// Set up the OSM layer
L.tileLayer(
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18
}).addTo(map);
// add a marker in the given location
L.marker(center).addTo(map);
target = document.getElementById("map")
target.ondragover = function (e) {
e.preventDefault()
e.dataTransfer.dropEffect = "move"
}
target.ondrop = function (e) {
e.preventDefault()
imagePath = e.dataTransfer.getData("text/plain")
coordinates = map.containerPointToLatLng(L.point([e.clientX,e.clientY]))
L.marker(coordinates, {icon: L.icon({iconUrl: imagePath}),
draggable: true}).addTo(map)
}