Openlayers 提供的 API 读取、解析和展示 GeoJSON 描述的信息。
1. 官网介绍
GeoJSON is a format for encoding a variety of geographic data structures.
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [125.6, 10.1]
},
"properties": {
"name": "Dinagat Islands"
}
}
}
GeoJSON supports the following geometry types: Point, LineString, Polygon, MultiPoint, MultiLineString, and MultiPolygon. Geometric objects with additional properties are Feature objects. Sets of features are contained by FeatureCollection objects.
2. GeoJSON 重要对象成员(名/值对)。
字段 | 是否必须 | 可选范围 |
type | 必须 | Point |
MultiPoint | ||
LineString | ||
MultiLineString | ||
Polygon | ||
MultiPolygon | ||
GeometryCollection | ||
Feature | ||
FeatureCollection | ||
crs | 可选 | 必须是一个坐标参考系统的对象 |
bbox | 可选 | 必须是边界框数组 |
二、OpenLayers 使用 GeoJSON
官方示例: https://openlayers.org/en/latest/examples/geojson.html
1. 定义样式和获取样式的方法
var styles = {
'Polygon': new Style({
stroke: new Stroke({
color: 'blue',
lineDash: [4],
width: 3,
}),
fill: new Fill({
color: 'rgba(0, 0, 255, 0.1)',
}),
})
};
var styleFunction = function (feature) {
return styles[feature.getGeometry().getType()];
};
2. 解析并展示 GeoJSON
// GeoJson 对象示例
var geojsonObject = {
type: "Feature",
geometry: {
type: "Polygon",
coordinates: [
[
[1e6, -3e6],
[2e6, -4e6],
[3e6, -6e6]
]
]
}
};
// 将 geoJSON 解析成 feature 并添加到 vectorLayer 数据源中
var vectorSource = new VectorSource({
features: new GeoJSON().readFeatures(geojsonObject)
});
//使用数据源和显示方法构建图层
var vectorLayer = new VectorLayer({
source: vectorSource,
style: styleFunction
});
也可以在创建完成后调用 API 动态添加 feature:
this.vectorSource.addFeatures(features);
VectorSource API : https://openlayers.org/en/latest/apidoc/module-ol_source_Vector-VectorSource.html
也支持ARCGIS的Json格式
var vectorSource = new VectorSource({
features: new ol.format.EsriJSON().readFeatures(geojsonObject)
})
EsriJSON
EsriJSON 是一种用于对各种地理数据结构进行编码的格式。对于 EsriJSON,其通常是指 FeatureSet 对象,其中 FeatureSet 包含一组 Feature 对象。在 ArcGIS Velocity 中,可以将 EsriJSON 提取为 FeatureSet 对象(要素集合)或者将单个 Feature 对象提取为行。
https://doc.arcgis.com/zh-cn/iot/ingest/esrijson.htm