IT评测·应用市场-qidao123.com
标题:
99.在 Vue 3 中使用 OpenLayers 配置 Icon 和 Text 标注
[打印本页]
作者:
宝塔山
时间:
2025-3-12 20:48
标题:
99.在 Vue 3 中使用 OpenLayers 配置 Icon 和 Text 标注
在前端 GIS 开辟中,
OpenLayers
是一款强盛且开源的舆图库,能够轻松实现 Web 端的舆图渲染和交互操纵。本文将基于
Vue 3
,先容如安在
OpenLayers
中使用
Icon(图标)
和
Text(文本标注)
,并具体解析参数配置。
1. 环境准备
在 Vue 3 项目中使用 OpenLayers,须要先安装依赖:
npm install ol
假如你的项目是基于 Vite 构建的,默认支持 ESM 方式引入,无需额外配置。
2. 创建 OpenLayers 舆图
我们先初始化 OpenLayers 舆图,并在 onMounted 钩子中执行渲染逻辑。
完整代码
<!--
* @Author: 彭麒
* @Date: 2025/3/11
* @Email: 1062470959@qq.com
* @Description: 此源码版权归吉檀迦俐所有,可供学习和借鉴或商用。
-->
<template>
<div class="container">
<div class="w-full flex justify-center">
<div class="font-bold text-[24px]">在Vue3中使用OpenLayers配置Icon和text的参数</div>
</div>
<div id="vue-openlayers"></div>
</div>
</template>
<script setup>
import { onMounted, ref } from "vue";
import "ol/ol.css";
import { Map, View } from "ol";
import TileLayer from "ol/layer/Tile";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import OSM from "ol/source/OSM";
import Feature from "ol/Feature";
import { Point } from "ol/geom";
import { Circle, Fill, Icon, Stroke, Style, Text } from "ol/style";
const map = ref(null);
const dataSource = new VectorSource({ wrapX: false });
const showPoint = () => {
const iconFeature = new Feature({
geometry: new Point([116, 39]),
});
const iconStyle = new Style({
image: new Icon({
rotation: 45,
crossOrigin: "anonymous",
anchor: [0.5, 1.5],
scale: 0.1,
src: new URL("@/assets/OpenLayers/beijing.png", import.meta.url).href,
}),
text: new Text({
text: "cuclife",
anchor: [0.5, 1.5],
rotation: 50,
font: "bold 20px Arial, sans-serif",
textAlign: "right",
offsetX: -50,
offsetY: 20,
fill: new Fill({
color: "red",
}),
stroke: new Stroke({
color: "white",
width: 2,
}),
}),
});
const pointStyle = new Style({
image: new Circle({
radius: 7,
fill: new Fill({
color: "red",
}),
stroke: new Stroke({
color: "blue",
width: 1,
}),
}),
});
iconFeature.setStyle([pointStyle, iconStyle]);
dataSource.addFeature(iconFeature);
};
// 初始化地图
const initMap = () => {
const OSM_Layer = new TileLayer({
source: new OSM(),
});
const feature_Layer = new VectorLayer({
source: dataSource,
});
map.value = new Map({
target: "vue-openlayers",
layers: [OSM_Layer, feature_Layer],
view: new View({
projection: "EPSG:4326",
center: [116, 39],
zoom: 14,
}),
});
};
onMounted(() => {
initMap();
showPoint();
});
</script>
<style scoped>
.container {
width: 840px;
height: 570px;
margin: 50px auto;
border: 1px solid #42B983;
}
#vue-openlayers {
width: 800px;
height: 450px;
margin: 0 auto;
border: 1px solid #42B983;
position: relative;
}
</style>
复制代码
4. 运行效果
终极效果如下: ✅
舆图居中在北京
✅
添加了赤色圆点
✅
显示图标(beijing.png),并带有旋转
✅
笔墨“北京”赤色显示,白色描边
5. 结语
通过本文,我们学习了: ✔ 在 Vue 3 项目中集成 OpenLayers
✔ 如何使用 Icon 配置舆图标注
✔ 如安在 OpenLayers 中添加 Text 并调解样式
希望这篇文章能帮助你更好地把握 OpenLayers,欢迎交流讨论!
欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/)
Powered by Discuz! X3.4