解析 JSON API 结果并加载到 Leaflet

Parsing JSON API result and loading in to Leaflet

我正在尝试从 API 调用中获取 JSON,将其解析为 GeoJSON 数组(仅获取纬度、经度和名称变量),然后将其加载到 Leaflet 地图中。

我在控制台中没有收到任何错误。 geojson 正在加载到地图中,但它是空的。当我查询它时 (console.log(geojson) 它看起来是空的。出于某种原因,我的函数无法正确解析到 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);

根据 Andreas 的评论,我查看了异步 AJAX。

我最终重组了我的代码以确保响应的处理在 ajax 调用完成后完成:

我将 API 响应的处理嵌套在一个使用 API 调用输出的函数中。 API 调用有一个函数,该函数在成功时运行,将响应传递给处理函数。

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)
    }})