我正在尝试使用JavaScript从URL加载包含FeatureCollection
的远程/外部GeoJSON文件,然后仅选择某些功能以最终加载到Leaflet地图。我认为这应该很简单,但显然不是...
我尝试过的方法:
leaflet-omnivore
将GeoJSON文件加载到GeoJSON
宾语。这似乎无法正确加载文件,因此我得到了
Invalid GeoJSON object
个错误。[variable] is not defined
错误
稍后与JSON对象进行交互。我认为这是由于
AJAX的异步特性?如何以可以继续将其作为对象操作的方式加载此GeoJSON文件?
这是我的JavaScript显示案例(3):
// Define URL path to geojson file containing FeatureCollection
var url = "https://blah.blah.geojson";
// Load geojson file as JSON object
$.getJSON(url, function(data) {
// Turn JSON object into geojson object
var geoJson_data = L.geoJson(data);
});
// Create list of properties to filter by
var list_of_props = ['foo', 'bar', 'boop'];
// Define restriction to certain features
var data_filtered = L.geoJson(geoJson_data, { // <- "geoJson_data is not defined" error occurs here
filter: function(feature, layer) {
if (feature.properties) {
return feature.properties.foo in list_of_props;
}
}
});
// Ultimately I'd want to add the filtered data to a map like so...
data_filtered.add_To(previouslyDefinedLeafletMap);
答案 0 :(得分:0)
对于所有使用Ajax调用的方法(例如getJSON),您都必须在回调方法中处理数据。
编写代码的最好方法是...
// Load geojson file as JSON object
$.getJSON(url, function(data) {
processJSON(data);
});
function processJSON(data) {
// Turn JSON object into geojson object
var geoJson_data = L.geoJson(data);
// Define restriction to certain features
var data_filtered = L.geoJson(geoJson_data, {
filter: function(feature, layer) {
if (feature.properties) {
return feature.properties.foo in list_of_props;
}
}
});
// Ultimately I'd want to add the filtered data to a map like so...
data_filtered.add_To(previouslyDefinedLeafletMap);
}