我對這個錯誤有點困惑,希望有人能對這個問題有所了解。
目前我正在嘗試向我的傳單地圖添加一個 geoJSON 圖層,更具體地說是一個顯示國家邊界的多邊形。我正在對 PHP 例程使用 AJAX 請求,該例程從包含國家/地區資料的大型 geo.json 檔案回傳資料。
我被卡住的地方是試圖將國家邊界/多邊形添加到地圖中,以下錯誤不斷列印到控制臺。
控制臺日志錯誤:
Layer.js:52 Uncaught TypeError: t.addLayer is not a function
at i.addTo (Layer.js:52)
at Object.success (index.js:104)
at fire (jquery-3.6.0.js:3500)
at Object.fireWith [as resolveWith] (jquery-3.6.0.js:3630)
at done (jquery-3.6.0.js:9796)
at XMLHttpRequest.<anonymous> (jquery-3.6.0.js:10057)
我懷疑我在我的 ajax 成功函式中做錯了什么,我試圖將資料添加到地圖中,但是經過幾天的嘗試不同的事情后,我現在需要專家的建議:)。
我還檢查了我的檔案是否正確鏈接。
任何建議將不勝感激,謝謝!
我的一些代碼:
//傳單地圖初始化
var map = L.map('map').setView([51.509, -0.08], 15);
L.tileLayer('https://tile.thunderforest.com/atlas/{z}/{x}/{y}.png?apikey={accessToken}', {
attribution: 'Map data © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery ? <a href="http://www.thunderforest.com/">Thunderforest</a>',
maxZoom: 18,
id: 'thunderforest/atlas',
accessToken: 'a794617134d14b1f82f1cd09d35bca51'
}).addTo(map);
var polygon = L.polygon([
[51.509, -0.08],
[51.503, -0.06],
[51.51, -0.047]
]).addTo(map);
var marker = new L.Marker([51.509, -0.08]);
marker.addTo(map);
});
//國家邊界AJAX請求
$('#borderSearch').click(function(){
$.ajax({
url: "lib/php/border.php",
type: "POST",
dataType: 'json',
data: {
code: $('#countryName').val()
},
success: function(result) {
var borderData = JSON.stringify(result);
var parsedGeoJson = JSON.parse(borderData);
L.geoJSON(parsedGeoJson).addTo(map);
},
error: function(jqXHR, textStatus, errorThrown){
console.log("Request Failed");
}
});
});
uj5u.com熱心網友回復:
您的map變數在另一個函式中初始化并且不可訪問全域。
var map;
$.ready(function(){ // Your function, I don't know what you do here, but I that you call this code in a function. Maybe `.ready(` or something like this
map = L.map('map').setView([51.509, -0.08], 15);
L.tileLayer('https://tile.thunderforest.com/atlas/{z}/{x}/{y}.png?apikey={accessToken}', {
attribution: 'Map data © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery ? <a href="http://www.thunderforest.com/">Thunderforest</a>',
maxZoom: 18,
id: 'thunderforest/atlas',
accessToken: 'a794617134d14b1f82f1cd09d35bca51'
}).addTo(map);
var polygon = L.polygon([
[51.509, -0.08],
[51.503, -0.06],
[51.51, -0.047]
]).addTo(map);
var marker = new L.Marker([51.509, -0.08]);
marker.addTo(map);
});
并且知道該map變數是全域的,您可以在其他函式中使用它,例如單擊偵聽器。
我很確定如果你console.log(map)在L.geoJSON(parsedGeoJson).addTo(map);這之前添加它會列印undefined
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/395270.html
上一篇:DatatablesButtonCollection-如何正確使用
下一篇:如何在遞回函式中回傳陣列?
