vue3 h5腾讯地图组件实现地图选点功能

  1. 去腾讯地图申请账号,拿到自己的key

  2. 直接上完成版代码


<template>
  <div id="app">
    <el-button @click="openMapPickPop">选点</el-button>
    <div>
      <b>经度:</b>
      <b>{{ currentPicked?.latlng.lat }}</b>
    </div>
    <div>
      <b>纬度:</b>
      <b>{{ currentPicked?.latlng.lng }}</b>
    </div>
    <div>
      <b>城市:</b>
      <b>{{ currentPicked?.cityname }}</b>
    </div>
    <div>
      <b>位置信息:</b>
      <b>{{ currentPicked?.poiaddress }}--{{ currentPicked?.poiname }}</b>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from "vue";
import { ElMessageBox } from "element-plus";

// const key= "去腾讯地图申请账号,拿到自己的key";
const IFRAME_HTML = ``;

const currentPicked = ref({
  latlng: {},
});
const onLocationVal = ref("");
function openMapPickPop($event) {
  if ($event.relatedTarget) return;
  ElMessageBox({
    title: "选择地址",
    message: IFRAME_HTML,
    customClass: "location-picker-box",
    dangerouslyUseHTMLString: true,
    closeOnPressEscape: false,
  })
    .then(() => {
      window.removeEventListener("message", handleMapChoice, false);
      console.log("选择地图", currentPicked.value);
    })
    .catch((e) => {
      if (e != "cancel") throw e;
      window.removeEventListener("message", handleMapChoice, false);
    });

  window.addEventListener("message", handleMapChoice, false);
}

// 地图选择的回调
function handleMapChoice(event) {
  let mapData = event.data;
  // 防止其他应用也会向该页面post信息,需判断module是否为'locationPicker'
  if (mapData && mapData.module != "locationPicker") return;
  console.log(mapData);
  currentPicked.value = mapData;
  onLocationVal.value = mapData.poiaddress;
}
</script>

<style lang="less">
html .location-picker-box {
  width: auto;
  max-width: none;
}
iframe {
  width: 100%;
  padding: 0;
  margin: 0;
}
</style>


参考此文

你可能感兴趣的:(javascript,前端,vue.js)