Search code examples
javascriptjsonapileafletgeojson

Parsing GeoJSON with leaflet from an external API


I'm trying to use an external API to retrieve GeoJSON data and ultimately show the data on a map. I'm using the leaflet library for the map and the issue I'm facing is that the data I get from this API seems fine (i.e. if I take the data from the console.log and then use it directly in the "L.geoJson(WHAT TO INPUT HERE)" it works) but for some reason if I try to use the object itselft it doesn't work.

                var map = L.map('map').setView([48.85, 2.35], 13);
                var stamenLayer = L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/toner/{z}/{x}/{y}.png', {
                  attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://creativecommons.org/licenses/by-sa/3.0">CC BY SA</a>.'
                }).addTo(map);

                function reqListener () {
                  console.log(this.response);
                }

                var oReq = new XMLHttpRequest();
                oReq.addEventListener("load", reqListener);
                oReq.open("GET", "http://dataratp.opendatasoft.com/api/records/1.0/download?dataset=liste-des-commerces-de-proximite-agrees-ratp&rows=100&format=geojson");
                oReq.send();
                L.geoJson(**WHAT TO INPUT HERE**).addTo(map);

Not too sure what's causing the issue as the data looks fine (I tested it on http://geojsonlint.com/).

Thanks for your help, Julien


Solution

  • The type of data you're receiving is a string. L.GeoJSON expects a GeoJSON object. You can convert the string to an object using the JSON.parse method:

    The JSON.parse() method parses a string as JSON.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

    L.geoJson(JSON.parse(this.response)).addTo(map);
    

    Next you'll need to know that XMLhttpRequest is asynchronous. See: Easy to understand definition of "asynchronous event"? Which in short means that when L.GeoJSON is being called, oReq.send might not be ready yet. That's where the eventlistener comes in. It calls the reqListener method when oReq.send is done receiving. You need to create your L.GeoJSON layer in the reqListener method like so:

    function reqListener () {
        L.geoJson(JSON.parse(this.response)).addTo(map);
    }
    

    Working example: http://plnkr.co/edit/ODe622?p=preview