Javascript 解析JSON API结果并加载到传单
我试图从一个API调用中获取JSON,将其解析到一个GeoJSON数组中,只需获取lat、long和name变量,然后将其加载到传单映射中 我在控制台中没有收到任何错误。geojson正在加载到地图中,但它是空的。当我查询console.loggeojson时,它显示为空。由于某种原因,我的函数无法正确解析到geojsonJavascript 解析JSON API结果并加载到传单,javascript,json,ajax,leaflet,geojson,Javascript,Json,Ajax,Leaflet,Geojson,我试图从一个API调用中获取JSON,将其解析到一个GeoJSON数组中,只需获取lat、long和name变量,然后将其加载到传单映射中 我在控制台中没有收到任何错误。geojson正在加载到地图中,但它是空的。当我查询console.loggeojson时,它显示为空。由于某种原因,我的函数无法正确解析到geojson var map1 = L.map('map').setView([52.599043, -1.325812], 6); var OpenStreetMap_Mapnik =
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: '© <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)
}})
在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)
}})
这是否意味着我必须找到一种方法等待Ajax调用完成加载,然后再运行其余的代码?这就是异步函数在后台做一些事情并在准备好后返回的要点,在接受的答案和副本的第一个链接中进行了很好的解释。可能重复当然,这是否意味着我必须找到一种方法等待Ajax调用完成加载,然后再运行其余的代码?这就是异步函数的要点—在后台做一些事情,准备好后返回,并在接受的答案和副本的第一个链接中进行了很好的解释。学习JavaScript做得很好异步性!很高兴在这里分享你的结果。继续努力。学习JavaScript异步性做得很好!很高兴在这里分享你的结果。继续努力。