Display Features properties
by Alex Azuero
HTML
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css">
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet-src.js"></script>
<div id="map" ></div>
<table id="properties"></table>
CSS
#map {
height: 400px;
}
JavaScript
var lat = 46.566414;
var lng = 2.4609375;
var zoom = 5;
var map = new L.Map('map');
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data © OpenStreetMap contributors';
var osm = new L.TileLayer(osmUrl, {minZoom: 3, maxZoom: 8, attribution: osmAttrib});
map.addLayer(osm);
map.setView(new L.LatLng(lat, lng), zoom);
L.geoJson(getData(), {
onEachFeature: handleFeature
}
).addTo(map);
function handleFeature(feature, layer) {
layer.on({
mouseover: mouseoverfunction,
mouseout: mouseoutfunction
});
}
function mouseoverfunction(e) {
var properties = e.target.feature.properties;
for (var prop in properties) {
if (properties.hasOwnProperty(prop)) {
// or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety...
console.log("prop: " + prop + " value: " + properties[prop]);
document.getElementById("properties").innerHTML = document.getElementById("properties").innerHTML + "<tr><td>" + prop + "</td><td>" + properties[prop] + "</td></tr>";
}
}
}
function mouseoutfunction(e) {
document.getElementById("properties").innerHTML = "";
}
function getData() {
return {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": { "id": "1", "where": "north" },
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
1.3842773437499998,
50.91688748924508
],
[
0.24169921874999997,
50.10648772767335
],
[
0.263671875,
49.1242192485914
],
[
1.9775390625,
48.850258199721495
],
[
3.80126953125,
48.73445537176822
],
[
4.7021484375,
49.396675075193976
...