Skip to content

Instantly share code, notes, and snippets.

@ramiroaznar
Last active May 21, 2024 23:50
Show Gist options
  • Save ramiroaznar/2c2793c5b3953ea68e8dd26273f5b93c to your computer and use it in GitHub Desktop.
Save ramiroaznar/2c2793c5b3953ea68e8dd26273f5b93c to your computer and use it in GitHub Desktop.
Getting coordinates from a Leaflet map
<html>
<head>
<title>Getting coordinates from 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">
function main() {
var options = {
center: [40.420488, -3.705878],
zoom: 12
}
var map = L.map('map', options);
L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {attribution: 'CARTO'})
.addTo(map);
var customMarker = L.icon({
iconUrl: 'logo_carto.png',
iconSize: [232, 92],
iconAnchor: [40.420488, -3.705878]
});
L.marker([40.420488, -3.705878], {icon: customMarker}).addTo(map);
map.on('click',
function(e){
var coord = e.latlng.toString().split(',');
var lat = coord[0].split('(');
var lng = coord[1].split(')');
console.log("You clicked the map at latitude: " + lat[1] + " and longitude:" + lng[0]);
});
}
window.onload = main;
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment