一、介绍
openlayer提供了一个绘制图形的工具。允许用户在地图上交互式绘制点(Point)、线(LineString)、多边形(Polygon)、圆形(Circle) 等几何图形。

二、初始化地图
js
import { Map, View } from "ol";
import { XYZ, Vector as VectorSource } from "ol/source.js";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer.js";
import { toLonLat, fromLonLat } from "ol/proj";
import "ol/ol.css";
const raster = new TileLayer({
source: new XYZ({
url: pgis_img,
rossOrigin: "anonymous",
projection: "EPSG:4326",
tileGrid: createXYZ({
extent: [-180, -90, 180, 90],
maxZoom: 20,
}),
}),
});
const source = new VectorSource({ wrapX: false });
tconst vector = new VectorLayer({
source: this.source,
zIndex: 100,
declutter: true // 避免图标重叠
});
const map = new Map({
layers: [raster, vector],
target: id,
view: new View({
center: fromLonLat(center),
zoom: 13
}),
controls: [], // 不添加任何默认控件
});
三、draw工具
OpenLayers 的 Draw
交互允许用户在 map 上绘制几何图形。以下是 Draw
的基本用法和常见配置:
选项 | 类型 | 描述 |
---|---|---|
source |
ol/source/Vector |
必需,绘制的要素将添加到的矢量源 |
type |
string |
必需,几何类型 ('Point', 'LineString', 'Polygon', 'Circle', 'MultiPoint', 'MultiLineString', 'MultiPolygon') |
style |
ol/style/Style |
绘制时的样式 |
freehand |
boolean |
是否自由绘制(默认false) |
maxPoints |
number |
最大点数(用于线或多边形) |
minPoints |
number |
最小点数(用于线或多边形) |
geometryFunction |
function |
自定义几何函数 |
condition |
function |
触发绘制的条件(默认是点击) |
snapTolerance |
number |
捕捉容差(像素) |
js
import Draw from "ol/interaction/Draw.js";
const draw = new Draw({
source: source, // 绘制的要素将添加到的源
id: type,
type: type, // 几何类型:'Point', 'LineString', 'Polygon', 'Circle'等
});
map.addInteraction(draw);// 将绘制交互添加到地图
//绘制开始
draw.on("drawstart", (e) => {
console.log('绘制开始', evt.feature);
});
// 绘制结束
draw.on('drawend', function(evt) {
console.log('绘制结束', evt.feature);
// 可以在这里处理绘制完成的要素
});
// 绘制过程中
draw.on('drawabort', function() {
console.log('绘制中止');
});
// 移除现有的绘制交互
map.removeInteraction(this.draw);
//撤销最后一次绘制
draw.removeLastPoint();
四、将绘制的图像生成geojson
new GeoJSON()
是 OpenLayers 中用于处理 GeoJSON 数据的格式类,它提供了读取和写入 GeoJSON 数据的功能。
readFeatures()
- 读取 GeoJSON 要素writeFeatures()
- 写入 GeoJSON 要素readFeature()
- 读取单个 GeoJSON 要素writeFeature()
- 写入单个 GeoJSON 要素
GeoJSON 标准规定使用 WGS84 坐标系(EPSG:4326),而 OpenLayers 地图通常使用 Web 墨卡托投影(EPSG:3857)。GeoJSON
类可以自动处理坐标转换:
js
import GeoJSON from "ol/format/GeoJSON";
draw.on("drawend", (e) => {
const feature = e.feature;
let geometry = feature.getGeometry();
if (!geometry) {
console.error("几何图形不存在!");
return;
}
// 如果是圆形,转换为多边形
if (geometry.getType() === "Circle") {
geometry = fromCircle(geometry, 64);
feature.setGeometry(geometry);
}
feature.setProperties({
name,
id
});
let geojson = new GeoJSON().writeFeature(feature, {
featureProjection: "EPSG:3857", // 目标坐标系
dataProjection: "EPSG:4326", // 数据源坐标系
});
console.log("geo", geojson);
});