Open info layer together with click on marker (leaflet) - leaflet

I would like to trigger an extra event when clicking on a marker. Now, it opens a popup, but instead I would like to show the information in an extra info layer. I have managed to show the layer (var info), but I don't know how to change the information with a click on the marker.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Schönberg Topography</title>
<link rel="stylesheet" href="../lib/mapbox.css" />
<script src="../lib/mapbox.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../dist/MarkerCluster.css" />
<link rel="stylesheet" href="../dist/MarkerCluster.Default.css" />
<script src="../dist/leaflet.markercluster-src.js"></script>
<script charset="UTF-8" src="topography.js"></script>
<style>
body {
padding: 0;
margin: 0;
}
html,
body,
#map {
height: 100%;
}
.info {
padding: 6px 8px;
font: 14px/16px Arial, Helvetica, sans-serif;
background: white;
background: rgba(255, 255, 255, 0.8);
box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
border-radius: 5px;
}
.info h4 {
margin: 0 0 5px;
color: #777;
}
</style>
<style type="text/css">
a:link {
text-decoration: none;
}
</style>
</head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<body>
<div id="map"></div>
<script type="text/javascript">
var cloudmadeUrl = 'http://otile1.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png',
cloudmadeAttribution = 'Map data © 2011 OpenStreetMap contributors, Imagery © 2011 Mapbox, Points &copy 2012 LINZ',
cloudmade = new L.TileLayer(cloudmadeUrl, {
maxZoom: 17,
attribution: cloudmadeAttribution
}),
latlng = new L.LatLng(48.86, 2.34);
var map = new L.Map('map', {
center: latlng,
zoom: 12,
maxBounds: [
[49, 2.7],
[48.7, 2, 45]
],
layers: [cloudmade]
});
var markers = new L.MarkerClusterGroup();
for (var i = 0; i < addressPoints.length; i++) {
var a = addressPoints[i];
var title = a[2];
var name = a[3]
var colormarker = a[4]
var typemarker = a[5]
var marker = L.marker(new L.LatLng(a[0], a[1]), {
icon: L.mapbox.marker.icon({
'marker-symbol': typemarker,
'marker-color': colormarker
}),
title: name
});
var info = L.control();
info.onAdd = function() {
this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
this.update();
return this._div;
};
// method that we will use to update the control based on feature properties passed
info.update = function() {
this._div.innerHTML = title;
};
marker.bindPopup(title);
markers.addLayer(marker);
}
map.addLayer(markers);
info.addTo(map);
</script>
</body>
</html>

You would need to modify your update function to take a parameter to begin here.You also only need to be creating this info control once, not each time inside the loop..because you only need one open at a time, right?
info.update = function(content) {
this._div.innerHTML = content;
};
Don't forget to update your onAdd with regards to removing the update.
info.onAdd = function() {
this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
return this._div;
};
Then, inside the callback for a click event on a marker, you would call info.update("My new content").

Related

Leaflet - BindPopup USGS Earthquakes Magnitude

In the brochure, I am making an earthquake map from data that comes from the USGS earthquakes. My question is how can I click and get the magnitude of each of the earthquakes as a popup? The script is as follows:
<!doctype html>
<html lang="es">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.1/dist/leaflet.css" type="text/css">
<script src="https://unpkg.com/leaflet#1.3.1/dist/leaflet.js" type="text/javascript"></script>
<script src="https://unpkg.com/esri-leaflet#2.1.4/dist/esri-leaflet.js"></script>
<script src="/js/leaflet.ajax.min.js" type="text/javascript"></script>
<style>
html, body {
height: 100%;
width: 100%;
margin: 0
}
#mapa {
height: 100%;
width: 100%;
}
</style>
<title>Simbologia</title>
</head>
<body>
<div id="mapa"></div>
<script type="text/javascript">
var mapa = L.map("mapa", {
center: [0, 0],
zoom: 2
});
var capaOrtoFoto = L.esri.basemapLayer("Imagery");
capaOrtoFoto.addTo(mapa);
var url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson";
L.Util.ajax(url).then(
function (datosGeoJOSN) {
var capaTerremotos = L.geoJSON(datosGeoJOSN, {
pointToLayer: function (entidad, latlng) {
return L.circleMarker(latlng);
}
});
capaTerremotos.addTo(mapa);
capaTerremotos.bindPopup().openPopup();
});
</script>
</body>
</html>
How can I make the "bindPopup" function call the magnitude of the earthquake?
Use feature.properties.mag to access the magnitude in your response:
fetch(url)
.then(data => data.json())
.then(data => {
L.geoJSON(data, {
pointToLayer: function(feature, latlng) {
return L.circleMarker(latlng).bindPopup(`Magnitude: ${feature.properties.mag}`).openPopup();
}
}).addTo(mapa);
})
Also you can use fetch API which requires no script importing to make the request.
Moreover the version of leaflet, esri-leaflet that you are using seem old.
<!doctype html>
<html lang="es">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css" type="text/css">
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js" type="text/javascript"></script>
<script src="https://unpkg.com/esri-leaflet#3.0.4/dist/esri-leaflet.js"></script>
<style>
html,
body {
height: 100%;
width: 100%;
margin: 0
}
#mapa {
height: 100%;
width: 100%;
}
</style>
<title>Simbologia</title>
</head>
<body>
<div id="mapa"></div>
<script type="text/javascript">
var mapa = L.map("mapa", {
center: [0, 0],
zoom: 2
});
var capaOrtoFoto = L.esri.basemapLayer("Imagery");
capaOrtoFoto.addTo(mapa);
var url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson";
fetch(url)
.then(data => data.json())
.then(data => {
L.geoJSON(data, {
pointToLayer: function(feature, latlng) {
return L.circleMarker(latlng).bindPopup(`Magnitude: ${feature.properties.mag}`).openPopup();
}
}).addTo(mapa);
})
</script>
</body>
</html>

How to dynamically adjust symbology based on user generated table

I have created a simple leaflet web app that allows for the user to search for the countries that they have traveled.
The user can use a search box or click on the layer on the map. either action will highlight the country green and load the name and flag in an adjacent table.
This works fine. However, problems arise should the user decide to remove a country visited (for example they made a mistake when selecting)
I have included the ability to delete the table items by user click and enabled a function on double click of the layer itself to reset the colour.
What I need is for these two actions to relate to one another. so if the user removes the flag, the related country is reset and vis versa.
I think I need some sort of listener on the click remove or highlight function or perhaps defining the symbology based on the user-generated table of countries visited. Any suggestions?
<!DOCTYPE html>
<html>
{% load static %}
{% load leaflet_tags %}
<head>
{% leaflet_js %}
{% leaflet_css %}
<script type="text/javascript" src="{% static 'dist/leaflet.ajax.js' %}"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>hello world</title>
<link rel="stylesheet" href="{% static 'leaflet-groupedlayercontrol/leaflet.groupedlayercontrol.min.css' %}" />
<link rel="stylesheet" href="https://labs.easyblog.it/maps/leaflet-search/src/leaflet-search.css" />
<link rel="stylesheet" href="https://labs.easyblog.it/maps/leaflet-search/examples/style.css" />
<style type="text/css">
#findbox {
background: #eee;
border-radius: 0.125em;
border: 2px solid #1978cf;
box-shadow: 0 0 8px #999;
margin-bottom: 10px;
padding: 2px 0;
width: 600px;
height: 26px;
}
.search-tooltip {
width: 200px;
}
.leaflet-control-search .search-cancel {
position: static;
float: left;
margin-left: -22px;
}
#map {
width: 50%;
height: 650px;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<p style="text-align: center; font-size: 24px; color: #175b81; font-weight: bold;"></p>
<h3>My World Map</h3>
<div id="findbox"></div>
<div id="map" style="height: 680px; width: 48%; display: ;"></div>
<div class="sidebar" style="display: right;">
<p style="text-align: centre; font-size: 24px; color: #175b81; font-weight: bold;">My Flags:</p>
<table style="width: 90%;">
<tr>
<td id="name" hidden></td>
<td id="code" hidden></td>
</tr>
<ul id="Countries_Visted"></ul>
</table>
</div>
<script>
var img1 = "<img src=";
var im2 = ">";
var quotes = "'";
var flagimage_pt1 = "https://www.countryflags.io/";
var flagimage_pt2 = "/flat/64.png";
// creating mapbox basemap
var mapboxAccessToken =
"pk.eyJ1IjoiY2hyaXNyeWFuLXRlY2giLCJhIjoiY2thY2c3bDZyMDZsNDJ4cHJlZmhwZmFjaCJ9.3GuHRvRz-8fxi4r103z05w";
var mapbox = L.map("map").setView([46.0, 8.0], 2.2);
mapbox.doubleClickZoom.disable();
L.tileLayer(
"https://api.mapbox.com/styles/v1/chrisryan-tech/ckaxvc0bt10041iqfz5fb7dgj/tiles/256/{z}/{x}/{y}#2x?access_token=" +
mapboxAccessToken,
{
tileSize: 512,
zoomOffset: -1,
attribution:
'© Mapbox © OpenStreetMap',
}
).addTo(mapbox);
//loading data with style, click function and listener
var data_layer = new L.GeoJSON.AJAX("{% url 'borders_data' %}", {
style: countriesStyle,
onEachFeature: countriesOnEachFeature,
});
//listener - adding to map on load
data_layer.on("data:loaded", function (e) {
layer.addTo(mapbox);
});
function countriesStyle(feature) {
return {
fillColor: "grey",
weight: 2,
opacity: 0.2,
color: "grey",
dashArray: 3,
fillOpacity: 0.2,
};
}
function countriesOnEachFeature(feature, layer) {
layer.on({
click: function (e) {
var layer = e.target;
layer.setStyle({
weight: 1,
color: "#fff",
dashArray: "",
fillOpacity: 0.9,
fillColor: "green",
});
if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
layer.bringToFront();
}
},
});
layer.on({
click: load_name_flag,
});
layer.on({
dblclick: clear,
});
}
///// clearing styling
var layer = data_layer;
function clear(e) {
layer.resetStyle(e.target);
}
///// adding to clicked countries to countries visted list
function load_name_flag(e) {
var field1 = document.getElementById("name");
field1.innerHTML = e.target.feature.properties.name;
var field2 = document.getElementById("code");
field2.innerHTML = e.target.feature.properties.iso2;
var selected_name_search = field1.innerHTML;
var selected_flag_search = img1 + quotes + flagimage_pt1 + field2.innerHTML + flagimage_pt2 + quotes + im2;
var selected_features_combine = selected_name_search + selected_flag_search;
$("#Countries_Visted").append("<li>" + selected_features_combine + "</li>").disabled = true;
}
</script>
<!- search box functionality - searches attribute data -->
<!- contained within Geojson from loaded event listener -->
<script src="https://unpkg.com/leaflet#1.3.0/dist/leaflet.js"></script>
<script src="https://labs.easyblog.it/maps/leaflet-search/src/leaflet-search.js"></script>
<script>
//pointing search function to map layer
var searchControl = new L.Control.Search({
container: "findbox",
layer: data_layer,
initial: false,
collapsed: false,
propertyName: "name",
marker: false,
});
// search box finds layer and adds country name and flag, changes layer symbol to green
searchControl.on("search:locationfound", function (e) {
var field1 = document.getElementById("name");
field1.innerHTML = e.layer.feature.properties.name;
var field2 = document.getElementById("code");
field2.innerHTML = e.layer.feature.properties.iso2;
var selected_name_search = field1.innerHTML;
var selected_flag_search = img1 + quotes + flagimage_pt1 + field2.innerHTML + flagimage_pt2 + quotes + im2;
var selected_features_combine = selected_name_search + selected_flag_search;
// styles for selected country
e.layer.setStyle({ fillColor: "green", color: "black", fillOpacity: 0.8 });
/// adding name and flag to countriesvisted list from searchbox select
$("#Countries_Visted").append("<li>" + selected_features_combine + "</li>").disabled = true;
});
mapbox.addControl(searchControl); //inizialize search control
// function to remove added layers
Countries_Visted.onclick = function remove(e) {
var li = e.target;
var layer = data_layer;
var listItems = document.querySelectorAll("li");
var ul = document.getElementById("ul");
li.parentNode.removeChild(li);
layer.resetStyle(e.target);
};
</script>
</body>
</html>

No img displayed on the leaflet control

My web app contains two basemaps to display. I created a leaflet control layer to manage their visibility :
var baseMaps = {
"Bing Satellite": bingLayer,
"OpenCycleMap": tileLayer
};
L.control.layers(baseMaps).addTo(map);
The issue is the icon which should be within the control doesn't show up. When I inspect, the console renders a 404 error : Failed to load resource: the server responded with a status of 404 (Not Found) on layers-2px.png.
I'm using cdn to call leaflet so I have no clue about the issue!!
Here is the rendering in the map :
Your assistance would be appreciated.
I put a working example.
<html>
<head>
<meta charset=utf-8 />
<title>Leaflet Control.Layers</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<!-- Load Leaflet from CDN -->
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.4/dist/leaflet.css"
integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA=="
crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.3.4/dist/leaflet.js"
integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA=="
crossorigin=""></script>
<!-- Load Esri Leaflet from CDN -->
<script src="https://unpkg.com/esri-leaflet#2.2.3/dist/esri-leaflet.js"
integrity="sha512-YZ6b5bXRVwipfqul5krehD9qlbJzc6KOGXYsDjU9HHXW2gK57xmWl2gU6nAegiErAqFXhygKIsWPKbjLPXVb2g=="
crossorigin=""></script>
<style>
body { margin:0; padding:0; }
#map { position: absolute; top:0; bottom:0; right:0; left:0; }
</style>
</head>
<body>
<div id="map"></div>
<script>
var gray = L.layerGroup();
// more than one service can be grouped together and passed to the control together
L.esri.basemapLayer("DarkGray").addTo(gray);
L.esri.basemapLayer("GrayLabels").addTo(gray);
var states = L.esri.featureLayer({
url: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3",
style: function (feature) {
return {color: '#bada55', weight: 2 };
}
});
var map = L.map('map', {
center: [39, -97.5],
zoom: 4,
layers: [gray, states]
});
var baseLayers = {
"Grayscale": gray,
"Streetmap": L.esri.basemapLayer("Streets")
};
var overlays = {
"U.S. States": states
};
// http://leafletjs.com/reference-1.0.3.html#control-layers
L.control.layers(baseLayers, overlays).addTo(map);
</script>
</body>
</html>
You can modify the background-image property of the following css selectors by setting your custom image:
.leaflet-control-layers-toggle, .leaflet-touch .leaflet-control-layers-toggle {
background-image: url('http://ovrdc.github.io/parcel-viewer/assets/images/layers-bl.png');
background-size: 80%;
margin-top: 0px;
width: 36px;
height: 36px;
}
<html>
<head>
<meta charset=utf-8 />
<title>Leaflet Control.Layers</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<!-- Load Leaflet from CDN -->
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.4/dist/leaflet.css"
integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA=="
crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.3.4/dist/leaflet.js"
integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA=="
crossorigin=""></script>
<!-- Load Esri Leaflet from CDN -->
<script src="https://unpkg.com/esri-leaflet#2.2.3/dist/esri-leaflet.js"
integrity="sha512-YZ6b5bXRVwipfqul5krehD9qlbJzc6KOGXYsDjU9HHXW2gK57xmWl2gU6nAegiErAqFXhygKIsWPKbjLPXVb2g=="
crossorigin=""></script>
<style>
body { margin:0; padding:0; }
#map { position: absolute; top:0; bottom:0; right:0; left:0; }
.leaflet-control-layers-toggle, .leaflet-touch .leaflet-control-layers-toggle {
background-image: url('http://ovrdc.github.io/parcel-viewer/assets/images/layers-bl.png');
background-size: 80%;
margin-top: 0px;
width: 36px;
height: 36px;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var gray = L.layerGroup();
// more than one service can be grouped together and passed to the control together
L.esri.basemapLayer("DarkGray").addTo(gray);
L.esri.basemapLayer("GrayLabels").addTo(gray);
var states = L.esri.featureLayer({
url: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3",
style: function (feature) {
return {color: '#bada55', weight: 2 };
}
});
var map = L.map('map', {
center: [39, -97.5],
zoom: 4,
layers: [gray, states]
});
var baseLayers = {
"Grayscale": gray,
"Streetmap": L.esri.basemapLayer("Streets")
};
var overlays = {
"U.S. States": states
};
// http://leafletjs.com/reference-1.0.3.html#control-layers
L.control.layers(baseLayers, overlays).addTo(map);
</script>
</body>
</html>

Measuring drawn line length with turf.js and mapbox

I'm trying to build out the functionality to measure a line that a user draws over a Mapbox map, using turf.js 'length' feature.
That said, I'm a coding newb - I know just barely enough to be dangerous.
Ultimately I'd like to be able to draw both areas and lines, and have their respective measures returned (area for polygons, lengths for line strings).
Can anyone offer insight as to why this code doesn't work?
https://jsfiddle.net/knxwu342
<html>
<head>
<meta charset=utf-8 />
<title>Line Test</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
.calculation-box-length {
height: 75px;
width: 100px;
position: absolute;
bottom: 40px;
left: 10px;
background-color: rgba(255, 255, 255, .9);
padding: 15px;
text-align: center;
}
</style>
<script src='https://api.tiles.mapbox.com/mapbox.js/plugins/turf/v3.0.11/turf.min.js'>
</script>
<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.0.9/mapbox-gl-draw.js'></script>
<link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.0.9/mapbox-gl-draw.css' type='text/css'/>
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.45.0/mapbox-gl.js'>
</script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.45.0/mapbox-gl.css' rel='stylesheet' />
</head>
<body>
<div id='map'></div>
<div class='calculation-box-length'>
<p>Length:</p>
<div id='calculated-length'></div>
</div>
<nav id="menu"></nav>
<script>mapboxgl.accessToken = 'pk.eyJ1IjoibWJsYWNrbGluIiwiYSI6ImNqaWMxcGk2MzAwd3YzbG1oeW4yOHppdnYifQ.xdb-2slu5LapzpuMCiKzQQ';
//*********-----------------------------------------------------------------------------------------------------------------**********
//Create new map object
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mblacklin/cjii8o7w91g9o2stcktaeixai', // stylesheet location
center: [-117.572737, 51.746916], // starting position [lng, lat]
zoom: 16 // starting zoom
});
//*********-----------------------------------------------------------------------------------------------------------------**********
// Add navigation controls to the map
map.addControl(new mapboxgl.NavigationControl());
//*********-----------------------------------------------------------------------------------------------------------------**********
// Add the ability to draw geometries and display their measurements
//
var draw = new MapboxDraw({
displayControlsDefault: false,
controls: {
line_string: true,
polygon: true,
trash: true
}
});
map.addControl(draw);
map.on('draw.create.', updateLength);
map.on('draw.delete', updateLength);
map.on('draw.update', updateLength);
function updateLength(e) {
var data = draw.getAll();
var answer = document.getElementById('calculated-length');
if (data.features.length > 0) {
var length = turf.length(data);
// restrict to area to 2 decimal points
answer.innerHTML = '<p><strong>' + length + '</strong></p><p> meters</p>';
} else {
answer.innerHTML = '';
if (e.type !== 'draw.delete') alert("Use the draw tools in the upper right to calculate a distance");
}
};
//
//*********-----------------------------------------------------------------------------------------------------------------**********
</script>
</body>
</html>
I see two little problems in your code:
There is a typo in your 'draw.create' listener. Just remove the point after create:
map.on('draw.create', updateLength);
The version of Turf you are using is too old and does not seem to have the length function. Try using the most recent one: https://npmcdn.com/#turf/turf/turf.min.js

Leaflet API GeoJSON Error

I am trying to load a GeoJSON file for an interactive map of West Virginia Counties but I am getting an error saying Uncaught ReferenceError: wvData is not defined on line 140. Can someone help me in figuring out how to resolve this? I am attaching my full code.
<html>
<head>
<title>Leaflet Interactive GeoJSON</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<style>
#map {
width: 100%;
height: 100%;
}
.info {
padding: 6px 8px;
font: 14px/16px Arial, Helvetica, sans-serif;
background: white;
background: rgba(255,255,255,0.8);
box-shadow: 0 0 15px rgba(0,0,0,0.2);
border-radius: 5px;
}
.info h4 {
margin: 0 0 5px;
color: #777;
}
.legend {
text-align: left;
line-height: 18px;
color: #555;
}
.legend i {
width: 18px;
height: 18px;
float: left;
margin-right: 8px;
opacity: 0.7;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<script type="text/javascript" src="CountySelection.js"></script>
<script type="text/javascript">
var map = L.map('map').setView([37.8, -96], 4);
L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {
maxZoom: 16,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'examples.map-20v6611k'
}).addTo(map);
// control that shows state info on hover
var info = L.control();
info.onAdd = function (map) {
this._div = L.DomUtil.create('div', 'info');
this.update();
return this._div;
};
info.update = function (props) {
this._div.innerHTML = '<h4>US Population Density</h4>' + (props ?
'<b>' + props.NAME + '</b><br />' + props.POP2010 + ' people / mi<sup>2</sup>'
: 'Hover over a state');
};
info.addTo(map);
// get color depending on population density value
function getColor(d) {
return d > 1000 ? '#800026' :
d > 500 ? '#BD0026' :
d > 200 ? '#E31A1C' :
d > 100 ? '#FC4E2A' :
d > 50 ? '#FD8D3C' :
d > 20 ? '#FEB24C' :
d > 10 ? '#FED976' :
'#FFEDA0';
}
function style(feature) {
return {
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.7,
fillColor: getColor(feature.properties.POP2010)
};
}
function highlightFeature(e) {
var layer = e.target;
layer.setStyle({
weight: 5,
color: '#666',
dashArray: '',
fillOpacity: 0.7
});
if (!L.Browser.ie && !L.Browser.opera) {
layer.bringToFront();
}
info.update(layer.feature.properties);
}
var geojson;
function resetHighlight(e) {
geojson.resetStyle(e.target);
info.update();
}
function zoomToFeature(e) {
map.fitBounds(e.target.getBounds());
}
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: zoomToFeature
});
} <!-- ADDED: Line 140 in the source code -->
geojson = L.geoJson(wvData, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
map.attributionControl.addAttribution('Population data © US Census Bureau');
var legend = L.control({position: 'bottomright'});
legend.onAdd = function (map) {
var div = L.DomUtil.create('div', 'info legend'),
grades = [0, 10, 20, 50, 100, 200, 500, 1000],
labels = [],
from, to;
for (var i = 0; i < grades.length; i++) {
from = grades[i];
to = grades[i + 1];
labels.push(
'<i style="background:' + getColor(from + 1) + '"></i> ' +
from + (to ? '–' + to : '+'));
}
div.innerHTML = labels.join('<br>');
return div;
};
legend.addTo(map);
</script>
</body>
</html>
In the line
geojson = L.geoJson(wvData, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
you haven't yet defined wvData anywhere, and looks like you haven't loaded your geojson file yet either. If you're data is defined in a separate geojson file, you'll need to load it via an ajax request, or checkout the leaflet-omnivore plugin.
Lyzi Diamond published some blog posts about loading geojson with leaflet. It helped me a lot: http://lyzidiamond.com/posts/external-geojson-and-leaflet-the-other-way/