Hokascha
Hokascha

Reputation: 2259

Update content of popup via AJAX in leaflet

I am trying to update the contents of my popups in leaflet. First, I create markers and bind popups to them:

$.ajax({
                type: "GET",
                url: "/?p=map&json=1"+filter,
                dataType: 'json',
                success: function (response) {
                    geojson = L.geoJson(response, {
                        pointToLayer: function (feature, latlng) {
                            return L.marker(latlng); 
                        },
                        onEachFeature: onEachFeature
                    });
                    markers.addLayer(geojson);
                    map.addLayer(markers);
                    });
                }
            });
var layers = [];
function onEachFeature(feature, layer) {
            feature.layer = layer;
            layer.origID = feature.properties.id;

            if (feature.properties && feature.properties.project_name) {
                var divNode = document.createElement('DIV');
                divNode.innerHTML = 'initial popup content from database <button onclick="makeAjaxCall('+feature.properties.id+')">more</button>'; 
                layer.bindPopup(divNode);
            }

            layers.push(layer);

        }

Initially, there's a button inside the popup, thats triggers an ajax call for updated popup content.

That ajax call returns and calls setPopupContent():

function setPopupContent(id,data){
            for(var i=0;i<layers.length;i++){
                if(layers[i].origID == id){
                    console.log(layers[i]);
                    var p = layers[i].getPopup();
                    p.setContent(data);
                    p.update();
                }
            }
        }

Everything works as expected but the popup's size is not updating to its new content. It remains at 301px. Shouldn't p.update() also update the popup size?

Or is there a better way to handle popup content updates that are triggered from within that popup?

Here's an example: http://plnkr.co/edit/LUyOWqkSVazhiadEix2q?p=preview (thx iH8!)

Thanks for help!

Upvotes: 1

Views: 1968

Answers (1)

iH8
iH8

Reputation: 28678

Your popup width is being constrained by the maxWidth option of L.Popup which defaults to 300px:

http://leafletjs.com/reference.html#popup-maxwidth

This can easily be set when binding/initializing the popup like this:

L.Marker([0, 0]).bindPopup('Lorem', {maxWidth: 600}).addTo(map);

A fork of your fork on Plunker: http://plnkr.co/edit/nfxhuUV40dfRV21YKFpu?p=preview

Upvotes: 1

Related Questions