Leaflet Markers – Create Marker from AJAX Call Data

ajaxleaflet

Get all the basic works with Leaflet and want to add markers using ajax call

    $("button").click(function(){
    $.get("GetLocationsServlet", function(data){
        markers = data.split(";");
        var length = markers.length;

        for (var i = 0; i < length; i++) {

            alert(markers[i]); // data print out ok
            L.marker(markers[i]).addTo(mymap); // Error
        }
    });
});

Got error when adding the marker to the map

Uncaught TypeError: Cannot read property 'lat' of null
at Object.project (leaflet.js:5)

The data return from the ajax call is like this

[49.205036,-123.002846, "Riverway Sport Complex"];[49.22193,-123.01249, "Imperial@Patterson"];[49.214756,-122.9882, "Royal Oak @Rumble"]

It worked when I tried to manually add the marker by hard coding the data to the L.marker() function. i.e.

L.marker([49.205036,-123.002846, "Riverway Sport Complex"]).addTo(mymap);

Best Answer

Most probably your data is still string type, which is not suitable as input to Leaflet Marker factory L.marker.

From your code and data sample, jQuery $.get performs an AJAX request and treats the response as text (in your data argument), that you refactor using the string method split. Therefore your markers array contains string representations:

'[49.205036,-123.002846, "Riverway Sport Complex"]'

You can easily convert it into a proper JavaScript object using JSON.parse:

JSON.parse(markers[i])

Then you can properly instantiate your markers:

L.marker(JSON.parse(markers[i])).addTo(mymap);