以下是使用腾讯地图 API 和 Vue3 实现生成 marker 并跟随鼠标移动的代码示例:

  1. 首先在 index.html 中引入腾讯地图 API 的 js 文件:
<script src='https://map.qq.com/api/js?v=2.exp&key=YOUR_KEY'></script>
  1. 在 App.vue 中定义地图容器和 marker:
<template>
  <div class='map-container' ref='mapContainer'></div>
</template>

<script>
  export default {
    data() {
      return {
        map: null,
        marker: null
      }
    },
    mounted() {
      // 初始化地图
      this.initMap()
    },
    methods: {
      initMap() {
        // 创建地图容器
        this.map = new qq.maps.Map(this.$refs.mapContainer, {
          center: new qq.maps.LatLng(39.916527, 116.397128), // 北京市中心
          zoom: 13
        })

        // 创建 marker
        this.marker = new qq.maps.Marker({
          map: this.map,
          position: this.map.getCenter()
        })

        // 监听鼠标移动事件
        qq.maps.event.addListener(this.map, 'mousemove', e => {
          // 更新 marker 位置
          this.marker.setPosition(e.latLng)
        })
      }
    }
  }
</script>

<style>
  .map-container {
    width: 100%;
    height: 100%;
  }
</style>
  1. 在 main.js 中创建 Vue 实例并挂载到 DOM 上:
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')
  1. 运行项目,即可看到地图和跟随鼠标移动的 marker 效果。

注意:在使用腾讯地图 API 时,需要先申请一个开发者密钥,将 YOUR_KEY 替换成自己的密钥。

Vue3 + 腾讯地图 API 实现鼠标跟随 Marker 效果

原文地址: https://www.cveoy.top/t/topic/lZMu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录