点击按钮使用OpenLayers+Vue跳转到某一个点
<template>
<div>
<button @click="centerMap">定位</button>
<div id="mapCon" ref="mapCon" style="width: 100%; height: 95%; position: absolute;"></div>
</div>
</template>
<script>
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import ScaleLine from 'ol/control/ScaleLine';
import OSM from 'ol/source/OSM.js';
export default {
name: 'MapComponent',
mounted() {
this.initializeMap();
},
methods: {
initializeMap() {
this.map = new Map({
target: this.$refs.mapCon,
layers: [
new TileLayer({
title: 'OSM',
source: new OSM(),
})
],
view: new View({
center: [0, 0],
zoom: 2,
projection: "EPSG:4326"
}),
});
this.map.addControl(new ScaleLine());
this.map.on('click', this.onMapClick);
},
onMapClick(event) {
const lonLat = event.coordinate;
console.log('Clicked coordinates:', lonLat);
},
centerMap() {
const newLocation = [114.546872282, 30.588835819];
const zoomLevel = 7;
this.map.getView().animate(
{
center: newLocation,
zoom: zoomLevel,
},
);
},
},
beforeDestroy() {
if (this.map) {
this.map.setTarget(null);
}
}
};
</script>
<style>
.city-popup {
cursor: pointer;
}
.city-popup .coordinates.hidden {
display: none;
}
.city-popup.clicked .coordinates {
display: block;
}
</style>
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/070f0ee7055644d2807dfd2185a237c6.png)