vue项目中使用高德地图搜索定位

实现vue项目中展现地图(这里用的是高德地图),并且有搜索框根据搜索的位置定位

  • 注册帐号

访问高德地图开发平台根据实际情况填写就可以🍜(实名认证的时候选择个人就可以,如果是企业级的项目,可能会涉及人员变动,建议使用公司邮箱进行注册)区别如下👇。

  • 创建应用

新建应用时名称,与类型可以随意填写,尽量填写的与开发的应用一直,方便后期维护🚘

应用创建成功之后,点击添加就会需要我们选择需要使用高德地图的哪些服务,不同的服务平台,对应填写的内容也有所区别🎪,例如Android需要填写App包名,Android的SHA1码等等,因为我这次的项目是个大屏项目所以就选择Web端(JSAPI)😮

信息填写完毕之后就会在当前应用下生成对应的Key值和安全密钥(安全密钥在之前的版本中是没有的)

技术选型

vue-amap

vue-amap是基于 Vue 2.x 与高德的地图组件👨‍🦰,提供一些基础和高级的功能,例如:地图扎点,信息窗体,搜索组件,类型插件等等,不需要我们在造轮子了,所以我们就来试一试🎑。

复制代码
  • npm安装
npm install vue-amap --save
  • main.js中挂载vue-amap
复制代码
import VueAMap from 'vue-amap';
Vue.use(VueAMap);
VueAMap.initAMapApiLoader({
  //申请地址 https://lbs.amap.com/ 选择web端jsAPI
  key: '自己申请的高德地图key', 
  // 插件集合,用到什么插件就使用什么插件
  plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.CircleEditor'],
  v: '1.4.4', // 高德sdk版本,最新的sdk已经出到了2.0
  //官网解释:JSAPI 2.0 提供的开发接口与 1.4 版本达到 99%的兼容度,但是为了保证插件的稳定性我们还是选择1.4.4。
})
复制代码
  • 封装组件amap
复制代码
<template>
  <div class="amap-page-container">
    <div class="input-search">
      <el-input class="inpu" placeholder="请输入你要定位的地址" v-model="address">
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <el-button type="primary" @click="searchMap()">定位</el-button>
    </div>
    <el-amap vid="amap" :plugin="plugin" class="amap-demo" :center="center" :zoom="zoom" :events='events'>
      <!-- 点击显示标记 -->
      <el-amap-marker v-for="(marker, index) in markers" :key="marker.index" :position="marker.position"
        :icon="marker.icon" :title="marker.title" :events="marker.events" :visible="marker.visible"
        :draggable="marker.draggable" :vid="index"></el-amap-marker>
    </el-amap>
    <div class="dis-tan ju-cen">
    </div>
  </div>
</template>

<script>
  window._AMapSecurityConfig = {
    securityJsCode: "这里输入自己申请的安全密钥"
  };
  export default {
    name: "v-map",
    props: {

    },
    data() {
      let self = this;
      return {
        tishi: '',
        //从这里下去是地图有关的
        address: '', //获取的位置
        zoom: 13, // 地图缩放
        center: [122.59996, 26.197646], // 初始中心
        lng: 0, //经纬度
        lat: 0,
        loaded: false,
        // 点击显示的标记默认的定位
        markers: [],
        //  自动定位到当前位置
        plugin: [{
          timeout: 1000, //超过10秒后停止定位,默认:无穷大
          panToLocation: true, //定位成功后将定位到的位置作为地图中心点,默认:true
          zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:f
          pName: 'Geolocation',
          events: {
            init(o) {
              // o 是高德地图定位插件实例
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  self.address = result.formattedAddress;
                  self.lng = result.position.lng;
                  self.lat = result.position.lat;
                  self.center = [self.lng, self.lat];
                  self.markers = [{
                    position: self.center,
                  }]
                  self.loaded = true;
                  self.$nextTick();
                } else {
                  o.getCityInfo((status, result) => {
                    if (result && result.center) {
                      // self.address = result.formattedAddress;
                      self.lng = result.center[0];
                      self.lat = result.center[1];
                      self.center = result.center;
                      self.markers = [{
                        position: self.center,
                      }]
                      self.loaded = true;
                      self.$nextTick();
                    }
                  });
                }
              });
            }
          }
        }],
        // 点击地图获取当前位置并显示标记
        events: {
          click(e) {
            self.chaadd(e.lnglat)
          }
        }
      }
    },
    created() {
      console.log(this.address)
    },
    methods: {
      searchMap() {
        let that = this;
        let address = this.address;
        var geocoder = new AMap.Geocoder({
          city: "", //城市设为北京,默认:“全国”
        });
        geocoder.getLocation(address, function(status, result) {
          console.log("status", status)
          console.log("result", result)
          if (status === 'complete' && result.geocodes.length) {
            var lnglat = result.geocodes[0].location;
            that.center = [lnglat.lng, lnglat.lat]
            that.lng = lnglat.lng;
            that.lat = lnglat.lat;
            that.markers = [{
              position: that.center,
            }]
            let data = {
              lng: that.lng,
              lat: that.lat
            };
            that.$emit('mapDing', data);
          } else {
            console.log('根据地址查询位置失败');
          }
        });
      },
      chaadd(e) {
        let self = this;
        let {
          lng,
          lat
        } = e;
        self.lng = lng;
        self.lat = lat;
        self.center = [self.lng, self.lat];
        self.loaded = true;
        self.markers = [{
          position: self.center,
        }]
        var geocoder = new AMap.Geocoder({
          radius: 1000 //范围,默认:500
        });
        var marker = new AMap.Marker();

        function regeoCode() {
          var lnglat = [lng, lat]
          geocoder.getAddress(lnglat, function(status, result) {
            if (status === 'complete' && result.regeocode) {
              self.address = result.regeocode.formattedAddress;
            } else {
              console.log('根据经纬度查询地址失败')
            }
          });
        }
        regeoCode();
      },
    }
  }
</script>


<style scoped>
  .amap-page-container {
    height: 400px;
    margin-top: 20px;
    position: relative;
  }

  .input-search {
    position: absolute;
    top: 0px;
    right: 0px;
    z-index: 5;
  }

  .inpu {
    width: calc(100% - 120px);
    margin-right: 20px;
    margin-bottom: 20px;
    margin-left: 20px;
  }
  .el-button--medium{
    height: 34px;
  }

  .wan {
    margin-top: 20px;
  }
</style>
复制代码
  • 在父组件中调用
复制代码
 <v-amap @mapDing="getCoordinate"></v-amap>

  

//搜索地址 查询结果
getCoordinate(data) {
console.log("getCoordinate:", data)
},

 
复制代码

 

刷新页面,地图加载偶尔失败

  • 在main.js中加入以下内容。
// 解决地图刷新显示不出来
const amapKeys = Object.keys(localStorage).filter(key => key.match(/^_AMap_/))
amapKeys.forEach(key => {
  // console.log(key)
  localStorage.removeItem(key)
})

 

 

 

 

 

 

 

 

 

复制代码

posted on   Breeze_zhou  阅读(3645)  评论(0编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示