Leaflet Highlight Feature through hovering text
HTML
<script src="http://leafletjs.com/examples/us-states.js"></script>
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css">
<div>Hover over following text to higlight state:
<b><span id="New York">New York</span></b>
</div>
<div id="map"></div>
CSS
#map {
height: 700px;
margin-top: 10px;
}
#montana {
background:rgba(255, 255, 0, 0.7);
padding:3px;
cursor: pointer;
}
.hover
{
border: 1px solid red;
color: red;
}
JavaScript
var highlighted_feature;
var map = L.map('map').setView([37.8, -96], 4);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
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.density)
};
}
var geojson;
function onEachFeature(feature, layer) {
layer._polygonId = feature.id;
}
geojson = L.geoJson(statesData, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
map.attributionControl.addAttribution('Population data © <a href="http://census.gov/">US Census Bureau</a>');
function hoverstart() {
var selectedId = 30; // test-ID for State Montana
geojson.eachLayer(
function (layer) {
if (layer._polygonId == selectedId) {
//console.log(layer);
highlighted_feature = layer;
highlighted_feature.setStyle({
weight: 5,
color: '#666',
fillColor: 'red',
dashArray: '',
fillOpacity: 0.7
});
}
});
$(this).addClass("hover");
}
function hoverstop(e) {
if (highlighted_feature) {
geojson.resetStyle(highlighted_feature);
}
$(this).removeClass("hover");
}
$("#montana").hover(hoverstart, hoverstop);