問題描述
我正在使用 Leaflet 1.0.3 和一些插件,包括 Leaflet.ajax.我的 L.geo.ajax 調(diào)用正在工作并返回 geojson 對象,但是坐標(biāo)是相反的.我創(chuàng)建了一個函數(shù)來解決這個問題:
I am using Leaflet 1.0.3 and a few plugins including Leaflet.ajax. My L.geo.ajax call is working and returning geojson objects, however, the coordinates are reversed. I created a function to fix this:
var convertLatLng = function (latlng) {
var temp = latlng[y];
latlng[y] = latlng[x];
latlng[x] = temp;
convertedLatLng = latlng;
return convertedLatLng;
console.log('this function is running')
}
但我的問題是我不知道該放在哪里.我是否在我的 geoJson 調(diào)用中運行它?如果有,在哪里?這是 ajax 調(diào)用的片段:
But my problem is I don't know where to put it. Do I run it inside my geoJson call? If so, where? Here is a snippet of the ajax call:
var geojson = L.geoJson.ajax('http://www.iotwf.com/deployment_map/json', {
pointToLayer: function (feature, latlng) {
convertLatLng(latlng);
...
},
onEachFeature: function(feature, layer) {
...
}
});
我也愿意接受其他可以解決問題的建議.
I am also open to other suggestions for what may fix it.
推薦答案
歡迎來到 SO!
首先確保你的坐標(biāo)確實是顛倒的.
First make sure that your coordinates are indeed reversed.
請注意,GeoJSON 格式需要 [longitude, latitude]
,而 Leaflet 通常需要 [latitude, longitude]
,除了 L.geoJSON()
工廠(和插件 L.geoJson.ajax()
),它會自動讀取 GeoJSON 順序并在正確的坐標(biāo)處構(gòu)建圖層.
Note that the GeoJSON format expects [longitude, latitude]
, whereas Leaflet usually expects [latitude, longitude]
, EXCEPT in the case of L.geoJSON()
factory (and the plugin L.geoJson.ajax()
), where it automatically reads the GeoJSON order and builds the layers at the correct coordinates.
如果您的坐標(biāo)仍然是反向的,那么適當(dāng)?shù)母@然是直接更正數(shù)據(jù)源中的順序(或任何服務(wù)輸出您的數(shù)據(jù)),以便您獲得實際兼容的 GeoJSON 數(shù)據(jù).這將解決許多未來的難題.
If your coordinates are still reversed, the appropriate correction would be obviously to correct the order in your data source directly (or whatever service outputs your data), so that you get actually compliant GeoJSON data. That would solve many future headaches.
如果這不可能,那么您確實可以在腳本中嘗試解決方法.
If that is not possible, then indeed you could try a workaround within your script.
最合適的方法可能是使用 L.geoJSON
工廠的>coordsToLatLng 選項.
The most appropriate way to do so would probably be to use the coordsToLatLng
option of the L.geoJSON
factory.
更改其 默認(rèn)實現(xiàn),你會得到類似的東西:
Changing its default implementation, you would get something like:
L.geoJson.ajax(url, {
coordsToLatLng: function (coords) {
// latitude , longitude, altitude
//return new L.LatLng(coords[1], coords[0], coords[2]); //Normal behavior
return new L.LatLng(coords[0], coords[1], coords[2]);
}
});
這篇關(guān)于傳單:如何交換從 ajax 調(diào)用接收到的坐標(biāo)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!