javascript - 从 URL 将 GeoJSON 加载到图层中?

标签 javascript leaflet mapbox

我正在使用 Mapbox 2.1,并尝试从 GeoJSON 源构建叶绿体 map ,使用以下示例:https://www.mapbox.com/mapbox.js/example/v1.0.0/choropleth/

但是,我在第一个障碍中就失败了,因为我的 GeoJSON 源是一个纯 GeoJSON 文件,而不是像他们的示例那样的 JS 文件。

所以这条线对我不起作用:

var statesLayer = L.geoJson(statesData,  {
    style: getStyle,
    onEachFeature: onEachFeature
}).addTo(map);

他们的JS file将statesData定义为变量:

var statesData = { "type": "FeatureCollection" ... };

但是我的 GeoJSON 文件只是一个 GeoJSON 文件。

如何定义 statesData 的等效项以便我可以遵循该示例?

我想我可以使用 eval 读取 GeoJSON,但这通常是一个坏主意。

最佳答案

您可以使用ajax从您自己的网站获取数据

这是一种 jquery 方法。

$.ajax({
dataType: "json", //you shouldn't need to declare geojson
url: "data/district.geojson",
success: function(data) {
    //whatever you want to do with the data, alternatively you could use a closer around the ajax request to capture the data into a variable depending on how you have your code organized
}
}).error(function(e) {
     console.log(e)
});

关于javascript - 从 URL 将 GeoJSON 加载到图层中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30808207/

相关文章:

javascript - 更新时, Mongoose 给我一个错误 : TypeError: Cannot set property 'vidName' of null

javascript - 在 Javascript 中存储树数据

javascript - 如何使用ui-leaflet和Markercluster来改变markercluster的颜色?

html - R : CSS defined in header is not working inside leafletProxy 的传单

javascript - 延迟加载由 javascript/leaflet 中的appendChild() 附加的图像

javascript - 我可以在进度条中显示 $timeout 值吗?

C# 和 JS 函数的链接

javascript - 传单.js : Popup outside map container

javascript - Mapbox js map 没有瓦片

Mapbox 读取存储 key 失败