当前位置: 首页 > article >正文

Vue2接入高德地图API实现搜索定位和点击获取经纬度及地址功能

目录

一、申请密钥

二、安装element-ui

三、安装高德地图依赖

四、完整代码

五、运行截图


一、申请密钥

登录高德开放平台,点击我的应用,先添加新应用,然后再添加Key。

如图所示填写对应的信息,系统就会自动生成。

二、安装element-ui

没安装的看官方文档:Element - The world's most popular Vue UI framework

三、安装高德地图依赖

npm i @amap/amap-jsapi-loader --save

四、完整代码

把刚才申请好的安全密钥和Key替换进去。

完整代码:

<template>
  <div style="display: flex">
    <div style="margin-top: 10px">
      <div>
        <span>搜索地址:</span>
        <el-autocomplete
            v-model="keywords"
            style="width: 300px"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入内容"
            @select="handleSelect"
        ></el-autocomplete>
        <span style="margin-left: 10px">
          <span>经度:{{ form.lng }}</span>
          <span style="margin-left: 10px">纬度:{{ form.lat }}</span>
          <span>地址:{{form.address}}</span>
        </span>
        <el-button style="margin-left: 10px" type="danger" size="small" @click="reset">清空</el-button>
      </div>
      <div id="container" class="container"></div>
    </div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
  // 安全密钥
  securityJsCode: "安全密钥",
};
export default {
  name: "HomeView",
  data() {
    return {
      // 地图实例
      map: null,
      // 标记点
      marker: "",
      // 地址逆解析
      geoCoder: null,
      // 搜索提示
      AutoComplete: null,
      //缩放控件
      ToolBar:null,
      //地图放大镜
      HawkEye:null,
      // 搜索关键字
      keywords: "",
      // 位置信息
      form: {
        lng: "119.793098",
        lat: "31.91243",
        address:'',
      },
      // 搜索节流阀
      loading: false,
      // 搜索提示信息
      options: [],
    };
  },
  created() {
    this.initMap();
  },
  methods: {
    reset(){
      this.keywords = '';
      this.form = {
        lng: "119.793098",
        lat: "31.91243",
        address: '',
      }
      // 清除点
      this.removeMarker();
      // 标记点
      this.setMapMarker();
    },
    initMap() {
      AMapLoader.load({
        // 你申请的Key
        key: "Key",
        version: "2.0",
        // 需要用到的插件
        plugins: ["AMap.Geocoder", "AMap.AutoComplete","AMap.ToolBar","AMap.HawkEye"],
      })
          .then((AMap) => {
            this.map = new AMap.Map("container", {
              viewMode: "3D", //是否为3D地图模式
              zoom: 23, //初始化地图级别
              center: [this.form.lng, this.form.lat], //初始化地图中心点位置
            });
            //地址逆解析插件
            this.geoCoder = new AMap.Geocoder({
              city: "010", //城市设为北京,默认:“全国”
              radius: 1000, //范围,默认:500
            });
            // 搜索提示插件
            this.AutoComplete = new AMap.AutoComplete({ city: "全国" });
            this.ToolBar =  new AMap.ToolBar({
              position: {
                bottom: '210px',
                right: '35px'
              }
            });
            this.HawkEye =  new AMap.HawkEye({
              position: {
                bottom: '110px',
                left: '35px'
              }
            });
            this.map.addControl(this.ToolBar);
            this.map.addControl(this.HawkEye);
            // 清除点
            this.removeMarker();
            // 标记点
            this.setMapMarker();
            //点击获取经纬度;
            this.map.on("click", (e) => {
              // 获取经纬度
              this.form.lng = e.lnglat.lng;
              this.form.lat = e.lnglat.lat;
              // 清除点
              this.removeMarker();
              // 标记点
              this.setMapMarker();
            });
          })
          .catch((err) => {
            // 错误
          });
    },
    // 标记点
    setMapMarker() {
      // 自动适应显示想显示的范围区域
      this.map.setFitView();
      this.marker = new AMap.Marker({
        map: this.map,
        position: [this.form.lng, this.form.lat],
      });
      // 逆解析地址
      this.toGeoCoder();
      this.map.setFitView();
      this.map.add(this.marker);
    },
    // 清除点
    removeMarker() {
      if (this.marker) {
        this.map.remove(this.marker);
      }
    },
    // 逆解析地址
    toGeoCoder() {
      let lnglat = [this.form.lng, this.form.lat];
      this.geoCoder.getAddress(lnglat, (status, result) => {
        if (status === "complete") {
          this.form.address = result.regeocode.formattedAddress;
        }else {
          this.form.address = '';
        }
      });
    },
    querySearchAsync(queryString, cb){
      if (queryString) {
        this.AutoComplete.search(queryString, (status, result) => {
          if(status === 'complete'){
            this.options = result.tips;
            for (let i = 0; i < this.options.length; i++) {
              this.options[i].value = this.options[i].name;
            }
          }else {
            this.options = [];
          }
          cb(this.options);
        });
      } else {
        this.options = [];
        cb(this.options);
      }
    },
    handleSelect(val){
      // 清空时不执行后面代码
      if (!val) {
        return;
      }
      this.form = {
        lng: val.location.lng,
        lat: val.location.lat,
      };
      // 清除点
      this.removeMarker();
      // 标记点
      this.setMapMarker();
    },
  },
  mounted() {
  },
};
</script>

<style>
.container {
  margin-top: 10px;
  width: 1280px;
  height: 720px;
}
</style>

五、运行截图

直接运行项目,效果如下:

更多用法请参考官方文档:添加地图控件-入门教程-地图 JS API 2.0 | 高德地图API


http://www.kler.cn/news/311310.html

相关文章:

  • 【Python报错已解决】ModuleNotFoundError: No module named ‘sklearn‘
  • 离散化c++
  • Django创建模型
  • 力扣(leetcode)每日一题 1184 公交站间的距离
  • 机器人相关知识的本身和价值
  • C++实现的小游戏
  • 关于Element-ui中el-table出现的表格错位问题解决
  • 启发式生成最佳轨迹ReGentS:超32个智能体生成现实世界的安全关键驾驶场景
  • 数据库(DB、DBMS、SQL)
  • 中关村科金推出得助音视频鸿蒙SDK,助力金融业务系统鸿蒙化提速
  • 蓝桥杯1.确定字符串是否包含唯一字符
  • VS Code远程连接虚拟机
  • 如何用站群服务器做抢购秒杀平台
  • Linux6-vi/vim
  • 使用稀疏和低秩分解的汉克尔结构矩阵进行脉冲噪声去除
  • UE5源码Windows编译、运行
  • 内存管理(C++版)
  • Python | Leetcode Python题解之第401题二进制手表
  • uni-app生命周期
  • Java 23 的12 个新特性!!
  • 攻防世界-Web题目2(弱比较、php伪协议)
  • Python 数学建模——高斯核密度估计
  • MVP 最简可行产品
  • 【深度智能】:迈向高级时代的人工智能全景指南
  • 数字世界的新秩序:探索Web3的前景
  • WPF颜色(SolidColorBrush)和Win32颜色(COLOREF)互转的方法
  • Python编程实例-正则表达式在数据清洗中的使用技巧
  • C#笔记13 线程同步概念及其实现,详解lock,Monitor,Mutex代码用法
  • pg入门2—pg中的database和schema有什么区别
  • 各大搜索引擎提交入口