vue2 openlayers 点击标记
时间: 2023-10-01 19:08:06 浏览: 57
要在Vue2的OpenLayers中实现点击标记的功能,可以按照以下步骤:
1. 在Vue组件中引入OpenLayers和相关依赖:
```
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import {Icon, Style} from 'ol/style';
```
2. 创建地图和矢量图层,并添加到地图中:
```
<template>
<div ref="map" class="map"></div>
</template>
<script>
export default {
mounted() {
const map = new Map({
target: this.$refs.map,
layers: [
new TileLayer({
source: new OSM(),
}),
new VectorLayer({
source: new VectorSource(),
}),
],
view: new View({
center: [0, 0],
zoom: 2,
}),
});
this.map = map;
},
};
</script>
```
3. 创建一个标记并添加到矢量图层中:
```
mounted() {
// ...
const vectorSource = this.map.getLayers().item(1).getSource(); // 获取矢量图层的数据源
const iconFeature = new Feature({
geometry: new Point([0, 0]),
name: 'My Marker',
});
const iconStyle = new Style({
image: new Icon({
anchor: [0.5, 1],
src: 'https://openlayers.org/en/latest/examples/data/icon.png',
}),
});
iconFeature.setStyle(iconStyle);
vectorSource.addFeature(iconFeature); // 将标记添加到矢量图层中
},
```
4. 给标记添加点击事件监听器:
```
mounted() {
// ...
const vectorSource = this.map.getLayers().item(1).getSource(); // 获取矢量图层的数据源
const iconFeature = new Feature({
// ...
});
// ...
iconFeature.on('click', (event) => {
console.log(event.target.get('name')); // 输出标记的名字
});
vectorSource.addFeature(iconFeature); // 将标记添加到矢量图层中
},
```
完整代码示例:
```
<template>
<div ref="map" class="map"></div>
</template>
<script>
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import {Icon, Style} from 'ol/style';
export default {
mounted() {
const map = new Map({
target: this.$refs.map,
layers: [
new TileLayer({
source: new OSM(),
}),
new VectorLayer({
source: new VectorSource(),
}),
],
view: new View({
center: [0, 0],
zoom: 2,
}),
});
this.map = map;
const vectorSource = this.map.getLayers().item(1).getSource(); // 获取矢量图层的数据源
const iconFeature = new Feature({
geometry: new Point([0, 0]),
name: 'My Marker',
});
const iconStyle = new Style({
image: new Icon({
anchor: [0.5, 1],
src: 'https://openlayers.org/en/latest/examples/data/icon.png',
}),
});
iconFeature.setStyle(iconStyle);
iconFeature.on('click', (event) => {
console.log(event.target.get('name')); // 输出标记的名字
});
vectorSource.addFeature(iconFeature); // 将标记添加到矢量图层中
},
};
</script>
<style>
.map {
height: 500px;
}
</style>
```
阅读全文