Rendering GeoJSON 渲染GeoJSON数据
在开始编辑前,我们将要看一下使用矢量源和图层的基本特征渲染。workshop的data文件夹下包含有一个countries.json的GeoJSON文件,我们将要加载这个文件的数据并将其渲染到地图上。
首先编辑index.html文件,以渲染一个全屏的地图:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>OpenLayers</title>
<style>
html, body, #map-container {
margin: 0;
height: 100%;
width: 100%;
font-family: sans-serif;
background-color: #04041b;
}
</style>
</head>
<body>
<div id="map-container"></div>
</body>
</html>
现在我们将要导入三个重要的元素以处理矢量数据:
- 一种用于读取和写入序列化数据的格式 (在这个例子里面是GeoJSON)
- 用于获取数据和管理要素空间索引的矢量源
- 用于在地图上渲染要素的矢量图层
在main.js种加载并渲染那个包含GeoJSON特征的数据:
import 'ol/ol.css';
// GeoJSON格式
import GeoJSON from 'ol/format/GeoJSON';
import {Map, View} from 'ol';
// 展示数据的图层
import VectorLayer from 'ol/layer/Vector';
// 获取数据
import VectorSource from 'ol/source/Vector';
import View from 'ol/View';
// 在Map实例的layers属性中使用Vector的layer并指定数据源
new Map({
target: 'map-container',
layers: [
new VectorLayer({
source: new VectorSource({
format: new GeoJSON(),
url: './data/countries.json'
})
})
],
view: new View({
center: [0,0],
zoom: 2
})
});
效果只有简单的轮廓,如下图:

由于我们会经常刷新这个页面,所以如果说地图能够保存刷新之前的位置就好了。我们将使用ol-hashed
这个包来实现这个需求。这个包已经在workshop的依赖中安装过了,如果要手动安装可以执行:
npm install ol-hashed
在main.js种添加这个依赖包:
import sync from 'ol-hashed';
现在我们需要将我们的地图分配给一个变量(命名为map),以便我们可以将该变量传递给sync函数:
const map = new Map({
使用方式是用sync()方法对map实例进行调用:
sync(map);
这样,在刷新页面后也会停留在上一次访问的位置。