Jamie
Jamie

Reputation: 306

Parsing JSON API result and loading in to Leaflet

I am trying to take the JSON from an API call, parse it in to a GeoJSON array (just taking the lat, long and name variable) and then load it in to a Leaflet map.

I am getting no errors in the console. The geojson is loading in to the map but it is empty. When i query it (console.log(geojson) it appears empty. For some reason my function is failing to correctly parse in to the geojson.

var map1 = L.map('map').setView([52.599043, -1.325812], 6);

var OpenStreetMap_Mapnik = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 19,
    attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}).addTo(map1);


var ports = $.ajax({
          url:"API_URL",
          dataType: "json",
          success: console.log("County data successfully loaded."),
        })
var geojson = {
  type: "FeatureCollection",
  features: [],
};

for (var i in ports.data) {
  geojson.features.push({
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [ports.data[i].longitude, ports.data[i].latitude]
    },
    "properties": {
      "stationName": ports.data[i].port_name
    }
  });
}

L.geoJSON(geojson).addTo(map1);

Upvotes: 1

Views: 1141

Answers (1)

Jamie
Jamie

Reputation: 306

Following Andreas's comment I looked in to Asynchronous AJAX.

I ended up restructuring my code to ensure that the processing of the response was done after the ajax call was completed:

I nested the processing of API response in a function that used the output from the API call. The API call has a function that runs when it's successful that passes the response to the processing function.

function callback1(response) {
    var geojson = {
        type: "FeatureCollection",
        features: [],
        };

    for (var i in response.data) {
        geojson.features.push({
        "type": "Feature",
        "geometry": {
        "type": "Point",
        "coordinates": [response.data[i].longitude, response.data[i].latitude]
        },
        "properties": {
        "stationName": response.data[i].port_name
        }
        })};
        L.geoJSON(geojson, {onEachFeature:Ports_Popup}).addTo(map1);
        console.log(response);
};

$.ajax({
      url:"https://statistics-api.dft.gov.uk/api/ports?filter[country]=scotland",
      dataType: "json",
      success: function(response){
      callback1(response)
    }})

Upvotes: 4

Related Questions