Vue2(vue-amap) 最新高德地图获取坐标与地址信息+搜索功能

效果

第一步:首先我们先去高德地图开放平台申请一个Key

第二步:

需要安装地图插件

npm install vue-amap --save

第三步:

// 引入vue-amap
import VueAMap from 'vue-amap'
Vue.use(VueAMap)
VueAMap.initAMapApiLoader({
  key: '你的Key',  // key
  plugin: [
  'AMap.Geolocation',  //定位空间,用来获取和展示用户主机所在的经纬度位置
    ' AMap.Autocomplete ',  //输入提示插件
    ' AMap.PlaceSearch ', //POI搜索插件
    ' AMap.Scale ',   //右下角缩略图插件,比例尺
    ' AMap.OverView ', //地图鹰眼插件
    ' AMap.ToolBar ',  //地图工具条
    ' AMap.MapType ',  //类别切换空间,实现默认图层与卫星图,实施交通层之间切换的控制
    ' AMap.PolyEditor ', //编辑 折线多边形
    ' AMap.CircleEditor ',
    "AMap.Geocoder",     //地图编码
   'AMap.AMapManager',
   'AMap.Marker'
  ],
  // 高德 sdk 版本,默认为 1.4.4
  v: '1.4.4',
  uiVersion: '1.0' //ui版本
})
//高德的安全密钥
window._AMapSecurityConfig = {
  securityJsCode: '你的密钥',
}

添加标签

              <div style="border: 1px solid #cccccc">
                  <!-- //搜索框 -->
                  <el-amap-search-box
                    id="search"
                    :search-option="searchOption"
                    :on-search-result="onSearchResult"
                  />
                  <!-- 地图 -->
                  <el-amap
                    class="amap-box"
                    :zoom="amap.zoom"
                    :center="amap.center"
                    :plugin="amap.plugin"
                    :events="amap.events"
                  >
                    <!-- 当前位置图标 -->
                    <el-amap-marker
                      v-for="(marker, index) in amap.markers"
                      :key="'marker' + index"
                      :position="marker.position"
                    />
                    <!-- 位置名称显示 -->
                    <el-amap-text
                      v-for="(marker, index) in amap.markers"
                      :key="'text' + index"
                      :text="marker.text"
                      :offset="marker.offset"
                      :position="marker.position"
                    />
                  </el-amap>
                </div>

数据源:


export default {
  name: "vehicleSpotInspection",
  data() {
    const vm = this;
    return {
      address: "",//需要传给后端的字段
      // form对象
      dataForm: getFormData(),
      // 地图搜索对象
      searchOption: {
        city: "全国",
        citylimit: true,
      },
      lng: 0,
      lat: 0,
      // 地图对象
      amap: {
        zoom: 16,
        center: [116.319802, 39.98294],
        events: {
          // 点击获取地址的数据
          click(e) {
            const { lng, lat } = e.lnglat;
            vm.dataForm.lon = lng;
            vm.dataForm.lat = lat;
            // 这里通过高德 SDK 完成。
            var geocoder = new AMap.Geocoder({
              radius: 100,
              extensions: "all",
            });
            geocoder.getAddress([lng, lat], function (status, result) {
              if (status === "complete" && result.info === "OK") {
                if (result && result.regeocode) {
                  console.log("点击获取地址的数据", result);
                  vm.dataForm.orgAddr = result.regeocode.formattedAddress;
                  vm.dataForm.province =
                    result.regeocode.addressComponent.province;
                  vm.dataForm.city = result.regeocode.addressComponent.city;
                  vm.dataForm.district =
                    result.regeocode.addressComponent.district;
                  vm.dataForm.lat = lat ? lat.toString() : "";
                  vm.dataForm.lon = lng ? lng.toString() : "";
                  vm.amap.markers = [];
                  const obj = {
                    position: [lng, lat],
                    text: result.regeocode.formattedAddress,
                    offset: [0, 30],
                  };
                  vm.amap.markers.push(obj);
                  vm.sure();
                }
              }
            });
            // this.$nextTick().then(() => {
            //           // 在这里执行你需要在 DOM 更新后执行的代码
            //         });
          },
        },

        plugin: [
          {
            // 定位
            pName: "Geolocation",
            events: {
              init(o) {
                // o是高德地图定位插件实例
                o.getCurrentPosition((status, result) => {
                  console.log("定位:", result);
                  if (result && result.position) {
                    // 设置经度
                    vm.lng = result.position.lng;
                    // 设置维度
                    vm.lat = result.position.lat;
                    vm.address = result.formattedAddress; //获取具体位置
                    console.log("定位address", vm.address);
                    // 设置坐标
                    vm.amap.center = [vm.lng, vm.lat];
                    let op = {
                      position: [vm.lng, vm.lat, vm.address],
                      text: vm.address, //提交之后显示的位置
                      offset: [0, 30],
                    };
                    vm.amap.markers.push(op);
                    // 页面渲染好后
                    // this.$nextTick().then(() => {
                    //   // 在这里执行你需要在 DOM 更新后执行的代码
                    // });
                  }
                });
              },
            },
          },
        ],
        //
        markers: [],
      },
    };

  },

方法:

 // 点击获取地址的数据
    // 地图点击事件处理函数
    onMapClick(e) {
      const { lng, lat } = e.lnglat;
      // 更新数据属性
      this.dataForm.lon = lng;
      this.dataForm.lat = lat;

      // 使用 this.$amap 创建 Geocoder 实例
      var geocoder = new this.$amap.Geocoder({
        radius: 100,
        extensions: "all",
      });
      geocoder.getAddress([lng, lat], (status, result) => {
        if (status === "complete" && result.info === "OK") {
          if (result && result.regeocode) {
            console.log("点击获取地址的数据", result);
            this.dataForm.orgAddr = result.regeocode.formattedAddress;
            this.dataForm.province = result.regeocode.addressComponent.province;
            this.dataForm.city = result.regeocode.addressComponent.city;
            this.dataForm.district = result.regeocode.addressComponent.district;
            this.dataForm.lat = lat.toString();
            this.dataForm.lon = lng.toString();

            // 更新标记
            this.amap.markers = [
              {
                position: [lng, lat],
                text: result.regeocode.formattedAddress,
                offset: [0, 30],
              },
            ];

            // 调用其他方法,例如 sure()
            this.sure();
          }
        }
      });
    },
    // 地图搜索回调
    onSearchResult(pois) {
      const vm = this;
      vm.amap.markers = [];
           // 根据是否有搜索结果来启用或禁用搜索框
           this.searchDisabled = pois && pois.length === 0;
      let latSum = 0;
      let lngSum = 0;
      console.log("地图回调", pois);
      if (pois.length > 0) {
        pois.forEach((poi, index) => {
          const { lng, lat } = poi;
          if (index === 0) {
            lngSum = lng;
            latSum = lat;
            const obj = {
              position: [poi.lng, poi.lat],
              text: poi.name,
              offset: [0, 30],
            };
            vm.amap.markers.push(obj);
            console.log("地图搜索回调", poi);
            vm.dataForm.orgAddr = poi.name;
            vm.dataForm.lat = poi.lat ? poi.lat.toString() : "";
            vm.dataForm.lon = poi.lng ? poi.lng.toString() : "";
          }
        });
        vm.amap.center = [lngSum, latSum];
      }
    },
    // 定位成功后更新位置信息的函数
    updateLocationInfo(position) {
      this.dataForm.lat = position.lat;
      this.dataForm.lng = position.lng;
      this.dataForm.orgAddr = position.formattedAddress; // position 对象中有 formattedAddress 属性
      console.log("更新位置", this.dataForm);
      // 更新地图中心点和标记
      this.amap.center = [this.dataForm.lng, this.dataForm.lat];
      this.amap.markers = [
        {
          position: [this.dataForm.lng, this.dataForm.lat],
          text: this.address,//这里改成后台提供的字段可以提交给后台
          offset: [0, 30],
        },
      ];
    },
    // 提交方法
    sure() {
      const vm = this;
      console.log(this.amap.markers);
      this.$emit("updateLocation", vm.dataForm);
    },

遇到的问题:1.有的可能会提示 找不到AMap模块 可以引入 import AMap from 'AMap'

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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 实现高德离线地图的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值