OpenLayers Workshop(二)Vector Data

Downloading features 下载特征结果

上传数据并编辑后,我们想让我们的用户下载结果。 为此,我们将我们的特征数据序列化为 GeoJSON 并创建一个 元素,该元素具有触发浏览器文件保存对话框的下载属性。 同时,我们将在地图上添加一个按钮,让用户清除现有要素并重新开始。

首先,我们需要一些按钮的标签.在index.html的map-container下面添加这些元素:

<div id="tools">
  <a id="clear">Clear</a>
  <a id="download" download="features.json">Download</a>
</div>

接下来为这些按钮添加样式,以让它们看上去正常些:

#tools {
  position: absolute;
  top: 1rem;
  right: 1rem;
}
#tools a {
  display: inline-block;
  padding: 0.5rem;
  background: white;
  cursor: pointer;
}

清除特征是比较容易的部分,所以我们先做这件事。 矢量源有一个 source.clear() 方法。 我们希望单击“清除”按钮来调用该方法,因此我们将在 main.js 中添加一个用于单击的侦听器:

const clear = document.getElementById('clear');
clear.addEventListener('click', function() {
  source.clear();
});

为了序列化我们的特征数据以供下载,我们将使用 GeoJSON 格式。 由于我们希望“下载”按钮在编辑过程中随时可用,我们将序列化源中每个更改事件的功能,并为锚元素的 href 属性构造一个数据 URI:

const format = new GeoJSON({featureProjection: 'EPSG:3857'});
const download = document.getElementById('download');
source.on('change', function() {
  const features = source.getFeatures();
  const json = format.writeFeatures(features);
  download.href = 'data:text/json;charset=utf-8,' + json;
});

发表评论