Skip to content

Instantly share code, notes, and snippets.

@jeffreymorganio
Created May 6, 2017 15:13
Show Gist options
  • Save jeffreymorganio/cfc991f4ad97e406466c89a4ab10eb61 to your computer and use it in GitHub Desktop.
Save jeffreymorganio/cfc991f4ad97e406466c89a4ab10eb61 to your computer and use it in GitHub Desktop.
Click to center a Leaflet JS map marker
license: mit

Click on the marker to zoom in and center the map on the marker.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>
<link rel="stylesheet" href="map.css">
<script src="map.js"></script>
<title>Center Leaflet Marker</title>
</head>
<body onload="showMap()">
<div id="leaflet-map"></div>
</body>
</html>
#leaflet-map {
width: 962px;
height: 502px;
}
var map = null;
var zoomLevel = 13;
var eiffelTower = new L.LatLng(48.858093, 2.294694);
var notreDame = new L.LatLng(48.852929, 2.350154);
function showMap() {
initMap();
addMarker();
}
function initMap() {
var tileLayer = createTileLayer();
var mapOptions = {
center: notreDame,
zoom: zoomLevel,
layers: [tileLayer]
};
map = new L.Map('leaflet-map', mapOptions);
}
function createTileLayer() {
var tileSourceURL = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png';
var tileSourceOptions = {
attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
};
return new L.TileLayer(tileSourceURL, tileSourceOptions);
}
function addMarker() {
L.marker(eiffelTower)
.on('click', function() {
centerLeafletMapOnMarker(map, this);
})
.addTo(map);
}
function centerLeafletMapOnMarker(map, marker) {
var latLngs = [ marker.getLatLng() ];
var markerBounds = L.latLngBounds(latLngs);
map.fitBounds(markerBounds);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment