腾讯地图添加自定义标记

首先要加载腾讯地图

 var center = new TMap.LatLng(39.984104, 116.307503);//设置中心点坐标
        //初始化地图
        var map = new TMap.Map("container", {
            center: center
        });

然后创建事件

        var markerLayer = new TMap.MultiMarker({
            id: 'marker-layer',
            map: map
        });

监听点击事件添加marker

        map.on("click", (evt) => {
            markerLayer.add({
            	position: evt.latLng
            });                      
        });

以上是给腾讯地图添加标记,map与marker建议定义为一个全局变量,在首次加载的时候就加载出来

然后如何点击标记弹出对话框,并在鼠标移动到

首先需要定义一个信息框

 this.infoWindow = new TMap.InfoWindow({
        map: window.Map,
        position: new TMap.LatLng(39.984104, 116.307503),
        offset: { x: 0, y: -32 }, //设置信息窗相对position偏移像素
        enableCustom: true,
        content: '<div id="info_card"></div>',
      });

这是一个自定义的弹框
然后给弹框加样式

#info_card {
  position: relative;
  width: 280px;
  height:260px;
  background-color: #c7c9c8;
}

现在就可以弹出框了,但是腾讯地图原生的content类型为string 所以无法直接引用vue组件

所以需要我们在添加标记的时候通过id获取当前标记并将vue组件追加到标记中
首先我们想显示自定义组件要创建自己的组件并将组件引用到当前放有地图的主页面中

import InfoWindow from '@/components/InfoWindow/index.vue'
components: {
    'info-window': InfoWindow //弹框用子组件包裹
  },
        <info-window ref="infoWindow" />

然后在添加标记的时候,监听click事件,当点击的时候添加弹出框

addWindow() {
      var that = this;
      //监听标注点击事件
      if (that.infoWindow == null) {
        that.windowInfo();
        that.infoWindow.close();
        that.userMarkerContainer.on("click", function (evt) {
          if (!that.isAddMarker) {
            that.createInfoDom(evt)
            document.getElementById("info_card").append(that.$refs.infoWindow.$el)
            that.$refs.infoWindow.initialize({
              evt: evt
            });
          }
        })
        that.userMarkerContainer.on("mouseover", this.onSelfMarkerMouseover);
        that.userMarkerContainer.on("mouseout", this.onSelfMarkerMouseout);
      }
    },

添加点击,鼠标移动到,鼠标移出事件,并通过$refs传递参数,这样我们就可以在弹框中编辑我们的信息了
组件中的数据我们就可以和后端自由交互了

弹出框完成之后但是鼠标单击双击按下等事件会因为点击弹出框,会联动后面地图的鼠标事件
所以为了解决事件继续传播的问题 需要在组件最外围标签中事件停止传播

<div @click.stop="stopEventSpread" @mousedown.stop="stopEventSpread" @dblclick.stop="stopEventSpread">

stopEventSpread方法不做任何处理
这样就完成了腾讯地图上的标记,弹出框与vue组件的完美契合

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐