Search code examples
jqueryleafletmarkerclusterer

Jquery Ajax with Leaflet and MarkerCluster Errors out


I have an application where I am loading markers dynamically by looping through a dataset.

for (var i = 0; i < data.length; i++) {
                var plateNo = data[i].PLATE_NUMBER;
                var permitNo = data[i].PERMITINFOID;
                var popup = '<h5>EPS</h5>' + 'Plate:' + plateNo + '<br/>' +
                    ' Permit: <a class=\'link\'  href=' + url + '>' + permitNo + '</a>' + 
                    '<p style=\"color:blue\">' + '' + '<a class=\'link\'  href=' + url + '>' + 
                    'Import' + '</a>' + '<br/>' + '<a class=\'link\'  href=' + url + '>' + 
                    'Duplicate' + '</a>' + '<br/>' + '<a class=\'link\'  href=' + url + '>' + 
                    'Removed' + '</a>' + '<br/>' + '</p>';

                var m = L.marker([data[i].REF_LATITUDE, data[i].REF_LONGITUDE], { icon: epsiconR, draggable: 'true' })
                                    .bindPopup(popup);
                markerClusters.addLayer(m);

                }
                map.addLayer(markerClusters);
            map.invalidateSize(false);

I am attaching an event handler to each of the items with class 'link' like this:

  map.on('popupopen', function () {
            $('.link').click(function (e) {
                createDialog();
            });
        });

I am ajax loading a different page in the createDialog method like this:

 function createDialog() {
             $("#testPara").slideToggle("slow");
        $.ajax({
            dataType: 'html',
            url: '/home/UpdateInventory',
            success: function (data) {
                $('#testPara').html(data);
            }
        });

}

The markers cluster fine and clicking on the popups ajax loads the div just fine. However once the Ajax load is done if I try to zoom in or out of the map or drag the map around I get an error Cannot read property 'lat' of undefined

Map simply freezes after that. I have been stuck on this for an entire day and would greatly appreciate any help or input.

This fiddle shows the issue, when you click on a link the console shows error

http://jsfiddle.net/pk9vbvs4/

Thanks


Solution

  • It looks to me that you are trying to load a page which has scripts that collide with the current page scripts (and possibly document id's as well). At least in your jsFiddle, you try to load the very same page (using url: '/'), which breaks all the JavaScript.

    All scripts are loaded twice, and initialization code is run again on variables that are not re-initialized, so weird things happen.

    Demo of loading something without any script inside: http://jsfiddle.net/pk9vbvs4/1/ Everything still runs fine.

    Since we do not have any detail about the target page, I cannot tell for sure this is the root cause for your issue.