[英]How can I assign the contents of a geojson file to a variable in Javascript?
显示的代码已经有效,但我想清理它。 它声明了一个名为placez的变量,其中包含 geojson 格式的信息,供代码的下一部分使用过滤器读取和加载到 map。 然而,在现实中,要映射的点数超过了 50,000(这里的例子只显示了 2)。 我想知道的是我如何才能加载来自同一目录中名为placesgj.geojson的文件的数据,其中 50,000 个数据条目将以 geojson 格式写入变量placez而不是像在这个例子。 代码的 rest 为整洁起见被省略,与功能无关。 提前致谢!
var placez = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"icon": "theatre"
},
"geometry": {
"type": "Point",
"coordinates": [-77.038659, 38.931567]
}
}, {
"type": "Feature",
"properties": {
"icon": "music"
},
"geometry": {
"type": "Point",
"coordinates": [-77.007481, 38.876516]
}
}]
};
map.on('load', function() {
// Add a GeoJSON source containing place coordinates and information.
map.addSource("placer", {
"type": "geojson",
"data": placez
});
placez.features.forEach(function(feature) {
var symbol = feature.properties['icon'];
var layerID = 'poi-' + symbol;
这是将JSON文件加载到javascript对象中的情况。 可以使用XMLHttpRequest在Pure Java Script中完成。
function loadJSONFile(callback) {
var xmlobj = new XMLHttpRequest();
xmlobj.overrideMimeType("application/json");
xmlobj.open('GET', 'placesgj.geojson', true); // Provide complete path to your json file here. Change true to false for synchronous loading.
xmlobj.onreadystatechange = function () {
if (xmlobj.readyState == 4 && xmlobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xmlobj.responseText);
}
};
xmlobj.send(null);
}
通过传递如下所示的回调函数来调用loadJSONFile函数:
loadJSONFile(function(response) {
var placez = JSON.parse(response);
});
//继续您的map.on('load',..代码在这里...
如前所述,您可以查看Fetch API
使用Leaflet API加载图层的示例:
fetch('http://localhost:8081/geoserver/basesEspaciales00/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=basesEspaciales00%3Aanimal2022ipa&maxFeatures=50&outputFormat=application%2Fjson')
.then(response => response.json())
//.then(data => console.log(data))
.then (response => response)
//.then (response => console.log (response))
.then (response => mapa(response));
function mapa(rta){
var a = rta;
var animalLayer = L.geoJSON(a, {
filter: function (feature, layer) {
if (feature.properties) {
// If the property "underConstruction" exists and is true, return false (don't render features under construction)
return feature.properties.underConstruction !== undefined ? !feature.properties.underConstruction : true;
}
return false;
},
onEachFeature: onEachFeature
}).addTo(map);
}
使用Fetch API读取文件。
function fetchJSON(url) {
return fetch(url)
.then(function(response) {
return response.json();
});
}
假设placesgj.geojson
位于同一目录中:
var data = fetchJSON('placesgj.geojson')
.then(function(data) {
// do what you want to do with `data` here...
data.features.forEach(function(feature) {
console.log(feature);
var symbol = feature.properties['icon'];
console.log(symbol);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.