Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update content in a Leaflet popup?

I'm working with Wax with Leaflet. I'm setting up a map of the US, drawing state boundaries with GeoJSON using leaflet's L.GeoJSON.

I'm able to get everything set during the map load, but I need to be able to adjust the content in the popups after the map is drawn. Here's a stripped down version of what I'm doing:

var gjStates = new L.GeoJSON(null, null);
wax.tilejson(url, function(tilejson) {  
    map = new L.Map('map').addLayer(new wax.leaf.connector(tilejson)).addLayer(gjStates);

    gjStates.on("featureparse", function (e) {
        if (e.properties && e.properties.name){
            pops[e.id.substring(4)] = e.layer.bindPopup('<h4>Hello ' + e.properties.name + '!</h4>');
        }
    });
    for (s in usStateData) {
        gjStates.addGeoJSON(usStateData[s]);
    }
});

Now, everything draws fine, popups have good conent, but then I want to alter it later and there's no way to reference it. I saw in the source that bindPopup() returns 'this', which I thought was the L.Popup object, but ended up something else. So for instance, the following code will udpate the active popup, not the specific one for the specific L.Path object(state) I'm trying to get at.

pops['AK']._map._popup.setContent('I am ALASKA!');

Digging through the DOM with firebug, I can also see that the popup content is set in an internal variable and I can update it. However, updating this does not update the HTML, and there's no way for me to find out that Alaska has the key of 52. _layers[52] also does not have the setContent() method I'd hope for if it was an L.Popup object.

gjStates._layers[52]._popupContent = 'I am ALASKA!';

So, I'm kind of stuck and not finding what I need. Is there any way for me to reference, and update the content for, a specific popup on the map after the initial rendering?

like image 814
Mike Shultz Avatar asked Mar 09 '12 21:03

Mike Shultz


People also ask

How do I create a pop up in leaflet?

Use the addPopups() function to add standalone popup to the map. A common use for popups is to have them appear when markers or shapes are clicked. Marker and shape functions in the Leaflet package take a popup argument, where you can pass in HTML to easily attach a simple popup.

How do you show markers in leaflet?

Leaflet has a very handy shortcut for this: marker.bindPopup("<b>Hello world!</b><br>I am a popup.").openPopup(); circle.bindPopup("I am a circle."); polygon.bindPopup("I am a polygon."); Try clicking on our objects.


1 Answers

I'm pretty sure you can just keep references to all the layers, and then call layer.bindPopup() at a later time to change the popup content.

like image 157
Acorn Avatar answered Oct 25 '22 07:10

Acorn