pc端vue封装高德地图实现定位 PlaceSearch搜索

首先安装 @amap/amap-jsapi-loader
官网教程
mapContainer.vue


<template>
  <div class="container-map" :style="styleObj">
    <!--  @change="changeInput" type="text" -->
    <a-input id='tipinput' v-model:value="inputValue" @change="changeInput"></a-input>
    <div id="container" ref="container" tabindex="0"></div>
    <div id="panel"></div>
  </div>
</template>
<script setup>
import {
    onMounted, onUnmounted, getCurrentInstance, ref, inject, watch, toRefs, reactive } from 'vue'
import {
    useRouter } from 'vue-router'
import AMapLoader from '@amap/amap-jsapi-loader';
import {
    keyGD, passwordGD } from "@/core/gaodekey.js";
import {
    message } from "ant-design-vue";
import utils from "@/core/utils.js";

const router = useRouter()
const container = ref(null)
let mapObj = null
let placeSearch = {
   }
let mapModule = null
let autoComplete = null
const inputValue = ref('')
// 当前位置
const currentPosition = ref({
   })

watch(
  () => props.value,
  (n) => {
   
    if (!n) {
   
      inputValue.value = undefined;
    } else {
   
      inputValue.value = n;
    }
  },
  {
    immediate: true }
);
const emits = defineEmits(["getPosition", 'addMarker']);
const props = defineProps({
   
  replenishmentMapList: {
   
    type: Array,
    default: () => [],
  },
  styleObj: {
   
    type: Object,
    default: () => {
    }
  },
  value: {
   },
})

const changeInput = (target) => {
   
  setTimeout(() => {
   
    emits("update:value", target.target._value);
  }, 500)
}
// 添加点位
const addMarker = (pointArray) => {
   
  // console.log(pointArray, "pointArray")
  clearMap()
  // 创建不同显示的icon
  pointArray.forEach((marker) => {
   
    new AMap.Marker({
   
      map: mapObj,
      position: [marker.lng, marker.lat],
      icon: new mapModule.Icon({
    image: marker.icon || '', size: [25, 34], imageSize: [25, 34] }),
      offset: new AMap.Pixel(-13, -30)
    });
  })

  // 移动点位中心点
  mapObj.setFitView();
}
// 清除地图所有覆盖物
const clearMap = () => {
   
  mapObj.clearMap();
}
// 初始化地图
const initMap = () => {
   
  AMapLoader.load({
   
    key: keyGD, // 申请好的Web端开发者Key,首次调用 load 时必填
    version: '2.0',// 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
    plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geolocation"],
  })
    .then((AMap) => {
   
      console.log(AMap, 'AMap')
      // 保存AMap实例
      mapModule = AMap
      const map = new AMap.Map('container', {
   
        // 设置地图容器id
        // viewMode: '3D', // 默认2d地图模式
        zoom: 12, // 初始化地图级别
        zooms: [5, 30],
        // 可以设置初始化当前位置
        // center: [116.397428, 39.90923],

        resizeEnable: true
      })
      mapObj = map
      let geolocation = new AMap.Geolocation({
   
        enableHighAccuracy: true,//是否使用高精度定位,默认:true
        timeout: 10000,          //超过10秒后停止定位,默认:5s
        position: 'RB',    //定位按钮的停靠位置
        offset: [10, 20], //定位按钮与设置的停靠位置的偏移量,默认:[10, 20]
        zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
      });
      mapObj.addControl(geolocation)
      geolocation.getCurrentPosition((status, result) => {
   
        if (status == 'complete') {
   
          console.log(result, 'result你好')
          const {
    lng, lat } = result.position
          currentPosition.value = {
    lng, lat }
          emits('getPosition', [lng, lat])
          addMarker([{
    lng, lat }])
        } else {
   
          message.error('定位失败')
        }
      })
      // 搜索功能
      toSearch()

    })
    .catch((e) => {
   
      console.log(e)
    })
}
const select = (e) => {
   
  const {
    poi } = e
  debugger
  const poiName = e.poi.name
  placeSearch.setCity(e.poi.adcode)
  // 获取当前的坐标 115.644865,40.223472
  // lng lat 
  const {
    lng, lat } = e.poi.location
  autoComplete.search(poiName, function (status, result) {
   
    if (status === 'complete' && result.info === 'OK') {
   
      console.log(result, 'result')
      addMarker([{
    lng, lat }])
      // 获取搜索到的点位
      emits('getPosition', [lng, lat])
      emits('getPositionInfo', poi)
    }
  }) // 关键字查询查询
}
const toSearch = () => {
   
  const autoOptions = {
   
    // input 为绑定输入提示功能的input的DOM ID,注意这个id要个搜索输入框的id一致
    input: 'tipinput'
  }
  autoComplete = new AMap.AutoComplete(autoOptions)
  placeSearch = new AMap.PlaceSearch(
    {
   
      map: mapObj, //展现结果的地图实例
    }
  )
  // console.log(placeSearch, 'placeSearch')
  autoComplete.on('select', select)// 注册监听,当选中某条记录时会触发
}


onMounted(() => {
   
  window._AMapSecurityConfig = {
   
    securityJsCode: passwordGD // 申请key对应的秘钥 -> 注意了,如果不搭配密钥使用,搜索将没有结果
  }
  initMap() // 初始化地图
})
onUnmounted(() => {
   
  map?.destroy();
})
// watch(propData,(newVal,oldVal)=>{})
defineExpose({
   
  addMarker,
})
</script>

<style scoped>
.container-map {
   
  padding: 0px;
  margin: 0px;
  width: 50%;
  height: 500px;

  #container {
     
    width: 100%;
    height: 100%;
  }
}
</style>

相关推荐

  1. pcvue封装地图实现定位 PlaceSearch搜索

    2024-01-25 03:44:01       44 阅读
  2. Vue地图API 的组件封装

    2024-01-25 03:44:01       33 阅读
  3. 【移动】Flutter 自定义地图比例尺

    2024-01-25 03:44:01       18 阅读

最近更新

  1. linux:命令执行过程【图表】

    2024-01-25 03:44:01       0 阅读
  2. 系统架构设计师——网络设计

    2024-01-25 03:44:01       0 阅读
  3. SSL证书到期自动巡检脚本-推送钉钉告警

    2024-01-25 03:44:01       1 阅读
  4. 如何才能在Linux下编写驱动程序

    2024-01-25 03:44:01       1 阅读
  5. Tomcat打破双亲委派模型的方式

    2024-01-25 03:44:01       1 阅读
  6. C++惯用法: 通过std::decltype来SFINAE掉表达式

    2024-01-25 03:44:01       1 阅读
  7. HTTP 范围Range请求

    2024-01-25 03:44:01       1 阅读

热门阅读

  1. linux和windows对比

    2024-01-25 03:44:01       30 阅读
  2. matlab查看源代码

    2024-01-25 03:44:01       38 阅读
  3. Package g++ is not configured yet.

    2024-01-25 03:44:01       36 阅读
  4. ABC337(A-C)

    2024-01-25 03:44:01       34 阅读
  5. 死锁面试题详解

    2024-01-25 03:44:01       34 阅读
  6. Koa框架

    2024-01-25 03:44:01       33 阅读
  7. JVM实战(29)——模拟栈内存溢出

    2024-01-25 03:44:01       31 阅读
  8. Docker离线安装

    2024-01-25 03:44:01       33 阅读