Search code examples
javascriptgisleafletmapboxgeojson

Adding geoJSON feature attributes to mapbox popup


I am looking to add a popup with geoJSON attributes to each book store marker on my map. I have used "layer.feature.properties.name" within the marker.bindpopup method, but am getting a return of "undefined".

L.mapbox.accessToken = 'jk.eyJ1IjsdkjfhskjdfhksdskdjflWNCJ9.Ov2O5PtskdljfsdR0lq3Q';
var map = L.mapbox.map('map', 'example.kks3kec4')
    .setView([38.633, -90.319],12);

//add cafe, books store, and university geoJSON layers with styling
var bookStore = L.mapbox.featureLayer()
    .loadURL('book_store84.geojson')
    //wait for the layer to be "on", or "loaded", to use a function that will setIcon with an L.icon object
    .on('ready', function(layer) {
        this.eachLayer(function(marker) {
            marker.setIcon(L.mapbox.marker.icon({
                'marker-color': '#BA1A1A',
                'marker-symbol': "library",
                'description': "book store"
            }));
            //when layer.feature is within the popup, it returns "undefined"
            marker.bindPopup("<p>" + layer.feature.properties.name + "</p>");
        });
    })
    .addTo(map);

Solution

  • You're using the layer variable:

    marker.bindPopup("<p>" + layer.feature.properties.name + "</p>");
    

    The layer variable does not contain the feature object. You are looping over the contained layers assigning them to the marker variable, those have the feature object, so you should that:

    marker.bindPopup("<p>" + marker.feature.properties.name + "</p>");