Reputation: 1531
I am building a map app with Leaflet. I am pulling a geojson file of congressional districts from a static file. I would like to add a popup to each district that contains the district name - which is in the geojson file. I would also like to color the districts with unique colors.
I have tried this code for adding popups with the district names. It does not work.
var polygons;
$.getJSON(
"http://localhost:8080/assets/geo/NationalCongressional.json",
function(data) {
polygons = L.geoJSON(data, {
style: myCustomStyle,
onEachFeature: function(feature, layer) {
layer.bindPopup(feature.properties.name);
}
});
}
);
var overlays = {
polygons: polygons
};
L.control.layers(baseMaps, overlays).addTo(myMap);
The error is that polygons is undefined.
If I don't mess around with code like this to customize the layer, then I can directly add the geojson to my map with no problem. Like this...
var NationalCongressional = new L.geoJson.ajax(
"http://localhost:8080/assets/geo/NationalCongressional.json",
{
style: upperHouseStyle
}
var overlays = {
NationalCongressiona: NationalCongressional
};
L.control.layers(baseMaps, overlays).addTo(myMap);
);
Upvotes: 0
Views: 706
Reputation: 1531
Figured it out. Here's the solution...
var NationalCongressional = new L.geoJson.ajax(
"http://localhost:8080/assets/geo/NationalCongressional.json",
{
style: upperHouseStyle,
onEachFeature: function(feature, layer) {
layer.bindPopup(feature.properties.NAMELSAD);
if (feature.properties.NAMELSAD == "Congressional District 8") {
console.log("found a match");
layer.setStyle({ color: "orange" });
}
}
}
);
var overlays = {
NationalCongressional: NationalCongressional
};
L.control.layers(baseMaps, overlays).addTo(myMap);
Upvotes: 1