GeoJson文件中的更改不会在地图上刷新
问题描述:
我从GEOJSON文件创建一个图层。我对该文件做了一些更改,希望这些更改能够反映在地图上。但地图保持不变。GeoJson文件中的更改不会在地图上刷新
我想我应该强制地图重新加载JSON文件,但不知道如何做到这一点。
答
我有完全一样的问题,这是我如何解决它:
考虑使用向量加载函数来处理抓取您的GeoJSON的文件。我有很多缓存问题没有使用矢量加载函数来获取geojson文件,下面的方法消除了这个问题。例如:
var utils = {
refreshGeoJson: function(source,url) {
var now = Date.now();
if (typeof url == 'undefined') {
url = source.getUrl();
}
url += '?t=' + now; //Add current time to prevent browser caching
console.info('refreshGeoJson url: ' + url);
this.getJson(url).when({
ready: function(response) {
var format = new ol.format.GeoJSON();
var features = format.readFeatures(response, {
featureProjection: 'EPSG:3857'
});
console.dir(features);
console.log(features.length);
source.addFeatures(features);
source.changed();
}
});
},
getJson: function(url) {
var xhr = new XMLHttpRequest(),
when = {},
onload = function() {
console.log('xhr.status onload() ' + xhr.status);
if (xhr.status === 200) {
console.log('getJson() xhr: ');
console.dir(xhr);
console.log('getJson() xhr.response: ');
console.dir(xhr.response);
when.ready.call(undefined, JSON.parse(xhr.response));
}
if (xhr.status === 404) {
console.log('file not found! url: ' + url);
alert("file not found!\n" + url);
}
},
onerror = function() {
console.info('Cannot XHR ' + JSON.stringify(url));
};
//console.log('getJson() - retrieve file url: ' + url);
xhr.open('GET', url, true);
xhr.setRequestHeader('cache-control', 'no-store');
xhr.onload = onload;
xhr.onerror = onerror;
xhr.send(null);
return {
when: function(obj) { when.ready = obj.ready; }
};
}
};
var vectorLoader = function(extent, resolution, projection) {
utils.refreshGeoJson(this);
}
var vectorSource = new ol.source.Vector({
url: /path-to/myFile.geojson',
format: new ol.format.GeoJSON({
defaultDataProjection :'EPSG:3857'
}),
loader: vectorLoader,
strategy: ol.loadingstrategy.all
});
我有一个定时函数来调用vectorSouce.clear()
重新加载该层的数据之前。调用.clear()
会触发地图图层的矢量加载器功能。
你能告诉我们一些你试过的代码吗? – kaycee