vue中图片引入问题以及实现openlayers地图标记

在Vue项目中使用OpenLayers遇到地图标记不显示的困扰,问题出在图片引入方式上。通过分析和尝试,发现需使用require或import来动态引入图片资源。正确引入图片后,地图标记成功显示。
摘要由CSDN通过智能技术生成

最近因为工作需要,在研究openlayers地图的使用,但是卡在了地图标记这块,不论我怎么尝试,标记就是不会显示在地图上,反反复复看了很多博客,也研究了文档,都觉得没有问题,也用html尝试了,标记可以显示,但就是在我的vue项目中显示不出来,后来发现是图片引入的问题。

刚开始我是这样引入图片的:

但是,在vue中动态引入图片应该使用require或者import,下边是正确的做法,完整代码,方便研究openlayers的小伙伴也可以顺便借鉴一下:

首先,npm install ol

Vue2使用OpenLayers实现点击标记的方法如下: 1. 首先在Vue组件引入OpenLayers相关的库文件: ``` import 'ol/ol.css'; import Map from 'ol/Map'; import View from 'ol/View'; import VectorSource from 'ol/source/Vector'; import VectorLayer from 'ol/layer/Vector'; import Feature from 'ol/Feature'; import Point from 'ol/geom/Point'; import {fromLonLat} from 'ol/proj'; import {Icon, Style} from 'ol/style'; ``` 2. 在Vue组件定义地图容器和地图实例: ``` <template> <div id="map" style="height: 500px;"></div> </template> <script> export default { name: 'Map', data() { return { map: null } }, mounted() { // 初始化地图 this.initMap(); }, methods: { initMap() { // 创建地图容器 this.map = new Map({ target: 'map', layers: [ new VectorLayer({ source: new VectorSource({ features: [ new Feature({ geometry: new Point(fromLonLat([120.1551, 30.2741])), name: '杭州市' }) ] }), style: new Style({ image: new Icon({ anchor: [0.5, 1], src: 'https://openlayers.org/en/latest/examples/data/icon.png' }) }) }) ], view: new View({ center: fromLonLat([120.1551, 30.2741]), zoom: 12 }) }); // 监听地图点击事件 this.map.on('click', this.handleMapClick); }, handleMapClick(event) { // 获取点击的坐标 const coordinate = event.coordinate; // 获取被点击的要素 this.map.forEachFeatureAtPixel(event.pixel, (feature) => { // 判断是否是Point类型的要素 if (feature.getGeometry().getType() === 'Point') { // 获取要素的名称 const name = feature.get('name'); // 在控制台输出要素名称和坐标 console.log(name, coordinate); } }); } } } </script> ``` 3. 在`initMap`方法创建地图容器和地图实例,然后监听地图的点击事件,在`handleMapClick`方法获取被点击的要素和坐标,判断是否是Point类型的要素,然后输出要素名称和坐标。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值