Load GeoJSON into layer from a URL?

纵饮孤独 提交于 2019-12-24 13:15:40

问题


I'm using Mapbox 2.1 and I'm trying to build a chloropleth map from a GeoJSON source, working from this example: https://www.mapbox.com/mapbox.js/example/v1.0.0/choropleth/

However, I've fallen at the first hurdle, because my GeoJSON source is a pure GeoJSON file, not a JS file like their example.

So this line doesn't work for me:

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

Their JS file defines statesData as a variable:

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

But my GeoJSON file is just a GeoJSON file.

How can I define the equivalent of statesData so that I can follow the example?

I guess I could use eval to read in the GeoJSON, but that's generally a bad idea.


回答1:


You can use ajax to snag the data from your own site

Here is a jquery way of doing it.

$.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)
});


来源:https://stackoverflow.com/questions/30808207/load-geojson-into-layer-from-a-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!