使用openlayers展示GeoJSON数据
- 文中包含geojson数据获取、选取坐标、并将坐标作为center和展示geojson
1. 获取数据
1.1 从阿里云获取数据
- 阿里云数据可视化平台
- 获取的是湖北省的边界数据
1.2 将数据保存为GeoJSON数据
2. 选取地图中心坐标
2.1 从osm拾取坐标
- 这个坐标是WGS 1984,EPSG:4326
说明:OpenLayers中,默认的投影是 SpherealMercator (EPSG: 3857) ,以米作为映射单位。如果想要将拾取的坐标30.4940,114.1692作为center,可以将坐标从 'EPSG:4326'转成'EPSG:3857'
2.2 'EPSG:4326'转成'EPSG:3857'并设为center
import { transform } from 'ol/proj';
const center = [114.1692, 30.494]; //EPSG:4326
const transformedCenter = transform(center, 'EPSG:4326', 'EPSG:3857');
const view = new View({
center: transformedCenter,
zoom: 10
});
2.3 在地图上显示GeoJSON中的边界信息
const map = new Map({
target: 'map',
layers: [
new VectorLayer({
source: new VectorSource({
format: new GeoJSON(),
url:'./data/hubei.geojson'
})
})
],
view: view
});
完整代码
import './style.css';
import Map from 'ol/Map.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import View from 'ol/View.js';
import VectorLayer from 'ol/layer/vector';
import VectorSource from 'ol/source/Vector';
import { transform } from 'ol/proj';
const center = [114.1692, 30.494]; //EPSG:4326
const transformedCenter = transform(center, 'EPSG:4326', 'EPSG:3857');
const view = new View({
center: transformedCenter,
zoom: 10
});
const map = new Map({
target: 'map',
layers: [
new VectorLayer({
source: new VectorSource({
format: new GeoJSON(),
url:'./data/hubei.geojson'
})
})
],
view: view
});
最后展示效果