More

Adding properties to pop ups in leaflet maps

Adding properties to pop ups in leaflet maps


I have a leaflet map which display pop-ups that give the name of a country when clicked. How can I add additional properties and have them all displayed, similar to this map http://lotrproject.com/map.

For example, how can I make my Iceland pop-up feature display the properties for "name" and "language", rather than just "name".

var countries = [ { type: "Feature", properties: { name: "Iceland", language: "Icelandic"}, geometry: { type: "Point", coordinates: [2535,911] } }, { type: "Feature", properties: { name: "Ireland" }, geometry: { type: "Point", coordinates: [1324, 1580] } }, { type: "Feature", properties: { name: "England" }, geometry: { type: "Point", coordinates: [1498, 1662] } }, { type: "Feature", properties: { name: "France" }, geometry: { type: "Point", coordinates: [1608, 1918] } }, { type: "Feature", properties: { name: "Italia" }, geometry: { type: "Point", coordinates: [1923, 2093] } }, { type: "Feature", properties: { name: "Hispania" }, geometry: { type: "Point", coordinates: [1374, 2148] } }, ]; var layerCountries = L.geoJson(countries, { // correctly map the geojson coordinates on the image coordsToLatLng: function(coords) { return rc.unproject(coords); }, // add a popup content to the marker onEachFeature: function (feature, layer) { if (feature.properties && feature.properties.name) { layer.bindPopup(feature.properties.name); } }, pointToLayer: function (feature, latlng) { return L.circleMarker(latlng, { radius: 8, fillColor: "#800080", color: "#D107D1", weight: 1, opacity: 1, fillOpacity: 0.8 }); } });

In a Leaflet popup you can just write plain HTML with anything you want. So instead of writing

layer.bindPopup(feature.properties.name);

you could simply write

layer.bindPopup('

'+feature.properties.name+'

Language: '+feature.properties.language+'

');

If you would like to display automatically all properties as a table inside the popup window, you could build up your HTML dynamically, something like:

var popupContent = ''; for (var p in feature.properties) { popupContent += ''; } popupContent += '
' + p + ''+ feature.properties[p] + '
'; layer.bindPopup(popupContent);

bindPopup takes html as an argument, so you can format it with as many properties as you want, using text, JavaScript variables and html together:

layer.bindPopup('Name: ' + feature.properties.name + '
' + 'Language: ' + feature.properties.language);

This example from the Leaflet docs may help:

L.marker([51.5, -0.09]).addTo(map) .bindPopup("Hello world!
I am a popup.");

bindPopup works the same for markers and geojson layers