我使用AJAX,這樣我可以推GeoJSON的多點功能,在文件中變成(全球)陣列用於其他功能的座標加載GeoJSON的文件。我想我的回調函數有問題。在下面的代碼中,我打算加載數據文件並將有關某些鯨魚的數據推送到multipointCoords數組中。這可以正常工作,但multipointCoords數組在全球不可用,而鯨魚可用。這讓我很困惑。Ajax回調和變量的作用域時加載JSON文件到陣列
此代碼也使用的OpenLayers。
var whales = {};
var multipointCoords = [];
$.getJSON('data/BW2205005.geojson', function(data) {
data.features.forEach(function(feature) {
if (!whales.hasOwnProperty(feature.properties.name)) {
whales[feature.properties.name] = {
"type": "FeatureCollection",
"features": []
};
}
whales[feature.properties.name].features.push(feature);
whales["Free Willy"].features.forEach(function(feature) {
multipointCoords.push(feature.geometry.coordinates);
});
console.log(multipointCoords[0][0]); // gives the right coordinate
});
});
console.log(whales); // is defined
console.log(multipointCoords[0][0]); // is undefined
我研究下,仍然不能修復:
How to load Open layers 3 geojson vector layer with bbox?
How do I return the response from an asynchronous call?
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
http://api.jquery.com/jQuery.getJSON/
釷尋求任何幫助。
您是否嘗試過'$ .getJSON( '數據/ BW2205005.geojson')來完成(功能(數據){你的成功的功能代碼});'?? –
您應該明白,在實際加載和執行JSON之前,您的'console.log'可能會被觸發。 '$ .getJSON'是一個**異步**函數。 –
剛剛嘗試過。不過,同樣的結果。 – interwebjill