Leaflet JavaScript Maps - Part3 - User Interaction & Rotate Colors

This adds some new functionality to: Part 2 - Auto Center and Zoom

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="toolbar">
  <a href="javascript:void(0)" onclick="zoomToMapObjects(mapObjects)" accesskey="R" title="Click or use Alt-R to show all mapped objects">
	Re-center &amp; show all objects 
	</a>
</div>
<div id="map"></div>

CSS

html,
body {
  height: 97%;
}

#map {
  height: 95%;
}

JavaScript

// For Leaflet tutorials, see: https://mattgingery.github.io/LeafletExamples

var lfmap;
var mapObjects = [];
var colorIndex = -1;

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 = getGrid(32.802077, -117.244066, 0.00100, 0.001500, 15, 10); // list of test shapes
  data.push([getRectangleCoords(32.813000, -117.250000, 0.02, 0.01)]);

  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 || typeof data == 'undefined') {
    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) {
  var mapCenter = [centerLat, centerLong];

  lfmap = L.map('map').setView(mapCenter, zoomLevel);

  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a...