在 OpenLayers 中绘制 GeoJSON 面要素并计算面积和中心点,可以结合 OpenLayers 的 ol/format/GeoJSON
模块将 GeoJSON 数据转换为 OpenLayers 的 Feature,然后使用 Turf.js 进行计算。示例代码如下
import Map from 'ol/Map';
import View from 'ol/View';
import { Tile as TileLayer } from 'ol/layer';
import OSM from 'ol/source/OSM';
import { Vector as VectorLayer } from 'ol/layer';
import VectorSource from 'ol/source/Vector';
import GeoJSON from 'ol/format/GeoJSON';
import * as turf from '@turf/turf';// 创建地图
const map = new Map({target: 'map',layers: [new TileLayer({ source: new OSM() })],view: new View({center: [0, 0],zoom: 2})
});// 创建一个 GeoJSON 面要素
const geojson = {type: 'Feature',geometry: {type: 'Polygon',coordinates: [[[116.39, 39.91],[116.41, 39.91],[116.41, 39.93],[116.39, 39.93],[116.39, 39.91]]]}
};// 将 GeoJSON 转换为 OpenLayers Feature
const vectorSource = new VectorSource({features: new GeoJSON().readFeatures(geojson, {featureProjection: 'EPSG:4326'})
});const vectorLayer = new VectorLayer({ source: vectorSource });
map.addLayer(vectorLayer);// 使用 Turf.js 计算面积和中心点
const polygon = turf.polygon(geojson.geometry.coordinates);
const area = turf.area(polygon);
const center = turf.center(polygon);console.log('面积:', area.toFixed(2) + ' 平方米');
console.log('中心点:', center.geometry.coordinates);