OpenLayers入门教程, 点击按钮使用OpenLayers+Vue跳转到某一个点

点击按钮使用OpenLayers+Vue跳转到某一个点

// An highlighted block
<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'; // 引入 OpenLayers 的样式文件
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" // 设置视图的投影为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>

在这里插入图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值