vue-amap 实现高德地图定位 + 搜索 +回显

本文档详细介绍了如何在Vue项目中集成高德地图API,包括注册开发者账号、安装vue-amap依赖、配置地图插件、获取和设置地图坐标、实现定位和地址解析功能。同时展示了父子组件间如何传递经纬度信息,实现实时位置回显。
摘要由CSDN通过智能技术生成

1.注册成为开发者  -》 申请秘钥key 调用高德api

高德地图开放平台:https://lbs.amap.com/?ref=https://console.amap.com/dev/index

此处有详细步骤:(注:有些功能-》申请的 key 必须配备安全密钥 jscode 一起使用)

此处有详细步骤:Vue(vue-amap) 接入高德地图获取坐标与地址信息_Your-Nikee的博客-CSDN博客_vue-amap 根据地点查询坐标

2.安装vue-amap 依赖

npm install vue-amap --save

3. 在项目 main.js 中引入 (根据所需功能引入)

import VueAMap from 'vue-amap';   //引入高德
VueAMap.initAMapApiLoader({
  key: '写入申请的key',
  //插件集合
  plugin: [
    'AMap.Geolocation',  //定位空间,用来获取和展示用户主机所在的经纬度位置
    ' AMap.Autocomplete ',  //输入提示插件
    ' AMap.PlaceSearch ', //POI搜索插件
    ' AMap.Scale ',   //右下角缩略图插件,比例尺
    ' AMap.OverView ', //地图鹰眼插件
    ' AMap.ToolBar ',  //地图工具条
    ' AMap.MapType ',  //类别切换空间,实现默认图层与卫星图,实施交通层之间切换的控制
    ' AMap.PolyEditor ', //编辑 折线多边形
    ' AMap.CircleEditor ',
    "AMap.Geocoder"     //地图编码
  ]
});

4.在需要地图的组件中调用

1.  map子页面 

html:

一些属性:   
<!--
      amap-manager: 地图管理对象
      vid:地图容器节点的ID
      zooms: 地图显示的缩放级别范围,在PC上,默认范围[3,18],取值范围[3-18];在移动设备上,默 
              认范围[3-19],取值范围[3-19]
      center: 地图中心点坐标值
      plugin:地图使用的插件
      events: 事件
    -->

 

<template>
  <div class="amap-page-container">
    <!-- 搜索条件 是个对象searchOption 属性是city城市名,citylimit:false; 搜索回调函数 -->
    <el-amap-search-box
      class="search-box"
      :search-option="searchOption"
      :on-search-result="onSearchResult"
    ></el-amap-search-box>
   
    <el-amap
      ref="map"
      vid="amapDemo"
      :amap-manager="amapManager"
      :center="center"
      :zoom="12"
      :plugin="plugin"
      :events="events"
      class="amap-demo"
    >
      <!-- 点标记在地图上显示的位置,默认为地图中心点, -->
      <el-amap-marker
        :position="marker.position"
        :events="marker.events"
        :visible="marker.visible"
        :draggable="marker.draggable"
      ></el-amap-marker>
    </el-amap>
  </div>
</template>

js: 地理编码与逆地理编码-服务-教程-地图 JS API v2.0 | 高德地图API

<script>
import VueAMap from "vue-amap";
const amapManager = new VueAMap.AMapManager();  //获取实例中 的画布
// let Geocoder;
export default {
  name: "amaps",
  props: ["Nowlnglat"],   //接受父页面的经纬度
  data() {
    let self = this; //定义当前对象(data) 为 self
    return {
      amapManager,
      //搜索条件
      searchOption: {
        city: "全国",   //范围
        citylimit: false, //是否限制城市内搜索
      },
      marker: {
        //   position: [118.054927, 36.813487], //坐标
        position: [0, 0], //坐标
        events: {
          click: (e) => {
            console.log("点击maker", e);
            this.marker = null;
          },
         //点标记拖拽移动结束触发事件
          dragend: (e) => {
            console.log("---event---: dragend", e);
            this.marker.position = [e.lnglat.lng, e.lnglat.lat];
          },
        },
        visible: true,    //点标记是否可见,默认为true。
        draggable: false, //设置点标记是否可拖拽移动,默认为false。
        template: "<span>1</span>",
      },
      lng: 0, //经度
      lat: 0, //纬度
      clicklnglat:[],
      center: [0, 0],
      //el-amap绑定一个事件  (点击)获取当前位置的经纬度
      events: {
        init: (o) => {
          o.getCity((result) => {
            // console.log(result);
          });
        },
        //点击获取 当前位置的经纬度
        click: (e) => {
          // if (!!this.marker) {
            //获取点击后的经纬度
            self.lng = e.lnglat.lng;
            self.lat = e.lnglat.lat;
            self.center = [e.lnglat.lng, e.lnglat.lat];  //设置范围中心点
            self.marker.position = [self.lng, self.lat];


            //存储 点击后经纬度
            sessionStorage.setItem("maplng", self.lng);
            sessionStorage.setItem("maplat", self.lat);
            console.log("点击后", sessionStorage.getItem("maplng"));
            console.log("点击后",sessionStorage.getItem("maplat"));

          // } 
          // else {
            // this.marker = {
            //   position: [e.lnglat.lng, e.lnglat.lat],
            //   events: {
            //     click: (e) => {
            //       console.log("点击maker", e);
            //       this.marker = null;
            //     },
            //     dragend: (e) => {
            //       console.log("---event---: dragend", e);
            //       this.marker.position = [e.lnglat.lng, e.lnglat.lat];
            //     },
            //   },
            //   visible: true,
            //   draggable: false,
            //   template: "<span>1</span>",
            // };
          // }
                 //Geocoder编码:根据地理名称来获得地点的经纬度
          let geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all",
          });
          //根据坐标获取位置  将经纬度 转换后成 地址信息 放在 输入框展示
          geocoder.getAddress(
            [e.lnglat.lng, e.lnglat.lat],
            function (status, result) {
              if (status === "complete" && result.info === "OK") {
                document.querySelector(".search-box-wrapper input").value =
                  result.regeocode.formattedAddress;
              }
            }
          );
        },
      },
      // el-amap定位当前位置  (初始化)
      plugin: [
        {
          enableHighAccuracy: true, //是否使用高精度定位,默认:true
          timeout: 100, //超过10秒后停止定位,默认:无穷大
          maximumAge: 0, //定位结果缓存0毫秒,默认:0
          convert: true, //自动偏移坐标,偏移后的坐标为高德坐标,默认:true
          showButton: true, //显示定位按钮,默认:true
          buttonPosition: "RB", //定位按钮停靠位置,默认:'LB',左下角
          showMarker: true, //定位成功后在定位到的位置显示点标记,默认:true
          showCircle: true, //定位成功后用圆圈表示定位精度范围,默认:true
          panToLocation: true, //定位成功后将定位到的位置作为地图中心点,默认:true
          zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默 
                                  认:f
          extensions: "all",
          pName: "Geolocation",
          events: {
            init(o) {
              // o是高德地图定位插件实例
            //   console.log("0", o);

              o.getCurrentPosition((status, result) => {
                // console.log("初始化当前位置", result);
                if (result && result.position) {

                  // 设置经度
                  self.lng = result.position.lng;
                  // 设置纬度
                  self.lat = result.position.lat;

                  //如果 Nowlnglat 经纬度有值 
                       回显或刷新页面: 显示初始化的定位  或  点击后的定位
                  if(self.Nowlnglat[0] != null && self.Nowlnglat[1] != null){
    
                      console.log('Nowlnglat____',self.Nowlnglat)

                    let  Clnglat =self.Nowlnglat
                    self.center = Clnglat;
                    self.marker.position = Clnglat;
                 
                    let geocoder = new AMap.Geocoder({
                            radius: 1000,
                            extensions: "all",
                        });
                        //根据坐标获取位置  将经纬度 转换后成 地址信息 放在 输入框展示
                        geocoder.getAddress(
                            Clnglat,
                            function (status, result) {
                            if (status === "complete" && result.info === "OK") {
                                document.querySelector(".search-box-wrapper input").value =
                                result.regeocode.formattedAddress;
                            }
                            }
                        );
                    // alert(123)
                    } else {
                       // 设置坐标中心点
                    self.center = [self.lng, self.lat];
                    self.marker.position = [self.lng, self.lat];
                    //存储  初始化定位
                    sessionStorage.setItem("maplng1", self.lng);
                    sessionStorage.setItem("maplat1", self.lat);
                    console.log("初始", sessionStorage.getItem("maplng1"));
                    console.log(sessionStorage.getItem("maplat1"));

                    document.querySelector(".search-box-wrapper input").value =
                    result.formattedAddress;
                  }
                  self.loaded = true;
                  self.$nextTick(); //页面渲染好后
                }
              });
            },
          },
        },
      ],
    };
  },
  methods: {
    //搜索地址 查询结果
    onSearchResult(pois) {
      console.log(pois);
      this.marker.position = [pois[0].lng, pois[0].lat];
      this.center = [pois[0].lng, pois[0].lat];
      sessionStorage.setItem("maplng", pois[0].lng);
      sessionStorage.setItem("maplat", pois[0].lat);
    },
  },
};
</script>

css:

<style scoped lang="scss">
.map_address {
  height: 50vh;
  width: 100vh;
  // background: red;
  .amap-wrapper {
    // display: flex;
    // flex-direction: column;
    height: 100%;
    width: 100%;
    .search-box {
      width: 100%;
      // transform: translateY(-20px);
      border: 1px solid #d9d9d9;
      /deep/.search-btn {
        background: #46a6ff;
        width: 15%;
        border-radius: 5px;
      }
    }
  }
}
</style>

 2.  父页面 (表单页)

html: 引入子组件map  


 <el-form-item label="地理位置:" >
      <address-map :Nowlnglat="Nowlnglat" ></address-map>
 </el-form-item>

 js:Nowlnglat(经纬度)传给子组件  回显

<script>

import addressMap from '@/views/register/components/map.vue' //引入组件

export default {
  name: "module2",
  data() {
    return {
      Nowlnglat:[],
    };
  },

   components:{addressMap},

  mounted() {
     //判断获取到的经纬度 初始化或点击后 传给子组件map 回显


      if(sessionStorage.getItem('maplng')&&sessionStorage.getItem('maplat')){
            this.formData.longitude= sessionStorage.getItem('maplng')
            this.formData.latitude= sessionStorage.getItem('maplat')
          this.Nowlnglat=[this.formData.longitude,this.formData.latitude]
          // console.log('点击后--',this.Nowlnglat)

         }else{
            this.formData.longitude= sessionStorage.getItem('maplng1')
            this.formData.latitude= sessionStorage.getItem('maplat1')
            this.Nowlnglat=[this.formData.longitude,this.formData.latitude]
          // console.log('初始化--',this.Nowlnglat)
         }
     
  },
  methods: {

  }
};
</script>

  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Vue-amap 是一个基于 Vue.js高德地图组件库,支持在线地图和离线地图。实现高德离线地图,需要先下载离线地图数据,在 Vue-amap 中引入并配置离线地图数据即可。 以下是实现步骤: 1. 下载离线地图数据:在高德官网下载离线地图数据,下载后解压缩得到离线地图数据文件夹。 2. 在 Vue 项目中安装 vue-amap: ``` npm install vue-amap --save ``` 3. 在 main.js 中引入和配置 vue-amap: ``` import VueAMap from 'vue-amap'; Vue.use(VueAMap); VueAMap.initAMapApiLoader({ key: 'your amap key', plugin: ['AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.Geolocation'], // 默认高德 sdk 版本为 1.4.4 v: '1.4.4', // 配置离线地图数据路径,注意路径要使用绝对路径 uiVersion: '1.0', map: { // 配置离线地图数据路径,注意路径要使用绝对路径 mapStyle: 'amap://styles/whitesmoke', features: ['bg', 'road', 'building'], customMapStyle: { 'styleJson': [ { 'featureType': 'water', 'elementType': 'all', 'stylers': { 'color': '#d1d1d1' } }, { 'featureType': 'land', 'elementType': 'all', 'stylers': { 'color': '#f3f3f3' } }, { 'featureType': 'railway', 'elementType': 'all', 'stylers': { 'visibility': 'off' } }, { 'featureType': 'highway', 'elementType': 'all', 'stylers': { 'color': '#fdfdfd' } }, { 'featureType': 'highway', 'elementType': 'labels', 'stylers': { 'visibility': 'off' } }, { 'featureType': 'arterial', 'elementType': 'geometry', 'stylers': { 'color': '#fefefe' } }, { 'featureType': 'arterial', 'elementType': 'geometry.fill', 'stylers': { 'color': '#fefefe' } }, { 'featureType': 'poi', 'elementType': 'all', 'stylers': { 'visibility': 'off' } }, { 'featureType': 'green', 'elementType': 'all', 'stylers': { 'visibility': 'off' } }, { 'featureType': 'subway', 'elementType': 'all', 'stylers': { 'visibility': 'off' } }, { 'featureType': 'manmade', 'elementType': 'all', 'stylers': { 'color': '#d1d1d1' } }, { 'featureType': 'local', 'elementType': 'all', 'stylers': { 'color': '#d1d1d1' } }, { 'featureType': 'arterial', 'elementType': 'labels', 'stylers': { 'visibility': 'off' } }, { 'featureType': 'boundary', 'elementType': 'all', 'stylers': { 'color': '#fefefe' } }, { 'featureType': 'building', 'elementType': 'all', 'stylers': { 'color': '#d1d1d1' } }, { 'featureType': 'label', 'elementType': 'labels.text.fill', 'stylers': { 'color': '#999999' } } ] }, // 配置离线地图数据路径,注意路径要使用绝对路径 zooms: [3, 20], viewMode: '3D', expandZoomRange: true }, // 配置离线地图数据路径,注意路径要使用绝对路径 filePath: '/path/to/offline/map/data' }); ``` 注意,需要将 filePath 设置为离线地图数据文件夹的绝对路径。 4. 在组件中使用 Vue-amap: ``` <template> <el-amap :zoom="13" :center="center"> <el-amap-marker :position="center"></el-amap-marker> </el-amap> </template> <script> export default { data () { return { center: [116.397428, 39.90923] }; } }; </script> ``` 在 el-amap 中设置 zoom 和 center 即可显示地图。el-amap-marker 可以设置标记点。 至此,就完成了 Vue-amap 实现高德离线地图的步骤。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值