阅读 34
前言
❝GeoJSON 是地理数据交换的常用格式,而 OpenLayers 提供了多种灵活的方式加载和展示这类数据。无论是简单的静态文件,还是需要动态加载的在线数据,掌握不同的加载方法能帮助你更高效地开发地图应用。
1. GeoJSON标准数据加载
如下所示GeoJSON标准数据,可通过features
参数直接加载。
const KMJSON = {
"type": "Feature",
"properties": {
"adcode": 530100,
"name": "昆明市(磨憨)",
"GDP": "8275.22",
"unit": "亿元",
"COLOR": "#70A800"
},
"geometry": {
"type": "MultiPolygon",
"coordinates":[[[]]]
}
}
只需调用GeoJSON
类readFeatures
方法读取给定数据即可。
source: new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(KMJSON)
}),
2. 解析数据路径加载
如下以加载云南省行政区矢量数据为例,通过GeoJSON
数据URL
结合format
参数来实现GeoJSON
数据加载。
// GeoJSON 服务
const JSON_URL = "./data/geojson/yn_region.json"
// 行政区矢量图层
const regionLayer = new ol.layer.Vector({
source: new ol.source.Vector({
url: JSON_URL,
format: new ol.format.GeoJSON(),
}),
style: {
'fill-color': ['string', ['get', 'COLOR'], '#eee'],
},
})
3. 解析URL加载
通过使用fetch
函数请求在线数据可以加载GeoJSON
,使用GeoJSON
对象属性readFeature
方法读取解析结果数据即可。
const JSON_URL = "https://geo.datav.aliyun.com/areas_v3/bound/530000_full.json"
fetch(JSON_URL)
.then(response => response.json())
.then(result => {
const vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(result)
})
const layer = new ol.layer.Vector({
source: vectorSource
})
})
在使用过程中,还可以加入加载策略,在OpenLayers中,具有三种策略,分别是all
、bbox
和tile
,默认为all
加载策略。
这三种方式都是函数类型,其中all
方式一次性返回所有请求数据,bbox
返回视图范围数据,tile
方式返回瓦片范围数据。
const JSON_URL = "https://geo.datav.aliyun.com/areas_v3/bound/530000_full.json"
source: new ol.source.Vector({
url: JSON_URL,
format: new ol.format.GeoJSON(),
strategy:ol.loadingstrategy.bbox
}),
4. 转换投影加载
在加载GeoJSON数据时可以转换投影坐标系进行加载。dataProjection
参数数据坐标系,默认为"EPSG:4326"
,featuresProjection
为数据按格式读取或写入的投影坐标系,传递给读或写方法的选项将优先。
const vectorSource = new ol.source.Vector({
url: JSON_URL,
format: new ol.format.GeoJSON({
dataProjection: "EPSG:4326",
featuresProjection: "EPSG:3857"
})
})