Skip to content

Instantly share code, notes, and snippets.

@ramiroaznar
Last active January 24, 2023 15:39
Show Gist options
  • Save ramiroaznar/f399ffd29d1b4d48632604aebfc7b8cc to your computer and use it in GitHub Desktop.
Save ramiroaznar/f399ffd29d1b4d48632604aebfc7b8cc to your computer and use it in GitHub Desktop.
Adding or moving markers on a Leaflet map

The map is set to drag the marker and get its new location with a popup. Uncomment from line 32 to 39, and comment line 41 to 51 in order to see how to add markers on click.

<html>
<head>
<title>Adding or moving markers on a Leaflet map</title>
<meta charset="utf-8">
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
<style type="text/css">
html, body, #map{
height: 100%;
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script type="text/javascript">
var options = {
center: [35.10418, -106.62987],
zoom: 10
}
var map = L.map('map', options);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {attribution: 'OSM'})
.addTo(map);
// map.on('click',
// function(e){
// //var coord = e.latlng.toString().split(',');
// //var lat = coord[0].split('(');
// //var lng = coord[1].split(')');
// //alert("You clicked the map at LAT: " + lat[1] + " and LONG: " + lng[0]);
// L.marker(e.latlng).addTo(map);
// });
var myMarker = L.marker([35.10418, -106.6287], {title: "MyPoint", alt: "The Big I", draggable: true})
.addTo(map)
.on('dragend', function() {
var coord = String(myMarker.getLatLng()).split(',');
console.log(coord);
var lat = coord[0].split('(');
console.log(lat);
var lng = coord[1].split(')');
console.log(lng);
myMarker.bindPopup("Moved to: " + lat[1] + ", " + lng[0] + ".");
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment