基础的矢量标记、圆、多边形
示例
代码实现
vue
<template>
<div id="map" class="w-full h-96"></div>
</template>
<script setup>
import { onMounted } from "vue";
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import { fromLonLat } from "ol/proj";
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";
import Circle from "ol/geom/Circle";
import Polygon from "ol/geom/Polygon";
import { Style, Fill, Stroke, Circle as CircleStyle } from "ol/style";
onMounted(() => {
// 创建地图
const map = new Map({
target: "map",
layers: [
new TileLayer({
source: new XYZ({
url: "http://{a-c}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png",
}),
}),
],
view: new View({
center: fromLonLat([-0.09, 51.505]),
zoom: 13,
}),
});
// 创建矢量图层
const vectorSource = new VectorSource();
const vectorLayer = new VectorLayer({
source: vectorSource,
});
map.addLayer(vectorLayer);
// 添加标记点
const marker = new Feature({
geometry: new Point(fromLonLat([-0.09, 51.505])),
});
marker.setStyle(
new Style({
image: new CircleStyle({
radius: 6,
fill: new Fill({
color: "#3388ff",
}),
stroke: new Stroke({
color: "#ffffff",
width: 2,
}),
}),
})
);
vectorSource.addFeature(marker);
// 添加圆
const circle = new Feature({
geometry: new Circle(fromLonLat([-0.11, 51.508]), 500),
});
circle.setStyle(
new Style({
fill: new Fill({
color: "rgba(255,0,51,0.5)",
}),
stroke: new Stroke({
color: "red",
width: 2,
}),
})
);
vectorSource.addFeature(circle);
// 添加多边形
const polygon = new Feature({
geometry: new Polygon([
[
fromLonLat([-0.08, 51.509]),
fromLonLat([-0.06, 51.503]),
fromLonLat([-0.047, 51.51]),
fromLonLat([-0.08, 51.509]),
],
]),
});
polygon.setStyle(
new Style({
fill: new Fill({
color: "rgba(51,136,255,0.5)",
}),
stroke: new Stroke({
color: "#3388ff",
width: 2,
}),
})
);
vectorSource.addFeature(polygon);
});
</script>
<style scoped>
.w-full {
width: 100%;
}
.h-96 {
height: 24rem;
}
</style>