[GIS] Displaying properties of GeoJSON in popup on Leaflet

featuresgeojsonleafletpopup

This is my simple GeoJSON with Leaflet map. I want to display properties as popup but I don't know why it is empty.

Can you tell me my mistake?

<html>
<head>
<title>A Leaflet map!</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<style>
#map {
width: 960px;
height: 500px;
}
</style>
</head>

<body>
<div id="map"></div>
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<script>
    var map = L.map('map',{
    center: [49.833352, 18.163662],
    zoom: 10
    });
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    var data ={
      "type": "FeatureCollection",
      "features": [
        {
          "type": "Feature",
          "geometry": {
            "type": "Point",
            "coordinates": [
              23.4850463378073,
              46.7440954850672
            ]
          },
          "properties": {
            "f1": 11793,
            "f2": "BT"
          }
        }
      ]
    };

var layer = L.geoJson(data, {
}).addTo(map);
layer.bindPopup('<h1>'+feature.properties.f1+'</h1><p>name: '+feature.properties.f2+'</p>');
</script>
</body>
</html>

Best Answer

The line where you create and bind your popup should have been included in the onEachFeature option of your L.geoJSON factory.

var layerGroup = L.geoJSON(data, {
  onEachFeature: function (feature, layer) {
    layer.bindPopup('<h1>'+feature.properties.f1+'</h1><p>name: '+feature.properties.f2+'</p>');
  }
}).addTo(map);

Demo: http://playground-leaflet.rhcloud.com/wuseg/1/edit?html,output

Having this line outside the factory makes it access your outer scope layer variable, which is actually the GeoJSON Layer Group that holds all the features from your GeoJSON data, therefore it tries to bind a popup on each of these features (in your case, there is only 1 marker, but it could be more).

Above all, it does not know any feature variable, which creates an error.