Leaflet JavaScript Maps - Part 2 - Auto Center and Zoom
Builds on Part 1 simple Leaflet example. This automatically centers the map to the drawn objects and zooms in to show those objects.
by Matt Gingery
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>
CSS
html,
body,
#map {
height: 97%;
}
JavaScript
// For Leaflet tutorials, see: https://mattgingery.github.io/LeafletExamples
drawMap(39.82835, -98.5816684, 5); // The Geographic Center of the United States
// Use this to get the array of Polygons you wish to display.
// This is where you should retrieve shape data from your middle-tier application.
// Each item must contain:
// Polygon definition which is an array of 2 element arrays of lat/long points
// Optional items:
// short title of the shape, additional html to display on popup, color.
function getPolygons() {
var data = [
[
[
[32.802077, -117.244066],
[32.802555, -117.241716],
[32.800715, -117.241169],
[32.800225, -117.243638]
],
"PB Middle School"
],
[
[
[32.800807, -117.226163],
[32.801618, -117.222419],
[32.798083, -117.221303],
[32.797325, -117.225219]
],
"Mission Bay High School", "2475 Grand Ave, San Diego, CA 92109", "gold"
]
];
if (data == null ) {
return [];
} else {
return data;
}
}
// Use this to get the array of Markers you wish to display.
// This is where you should retrieve point data from your middle-tier application.
// Each item must contain: lattitude, longitude
// Optional items: short title of the point, additional html to display on popup.
function getMarkers() {
var data = [
[32.794033, -117.250707, "Library", "<hr /><a target='new' href='https://www.sandiego.gov/public-library/locations/pacific-beach-taylor-library'><i>More Info...</i></a>"],
[32.808842, -117.231990, "Kate Sessions Elementary", null]
];
if (data == null ) {
return [];
} else {
return data;
}
}
// Basic map instantiation. Can also use other sources besides OpenStreetMaps -
// you should get the tileLayer urlTemplate and options from
// your middle-tier application which should store that data in a config file.
function drawMap(centerLat, centerLong, zoomLevel) {
try {
var lfmap;
...