vue 中使用高德地图(原生方法)可搜索定位

需求:表单中的经纬度和位置需要通过高德地图定位点进行拾取,并且地图可以进行搜索,搜素出来的定位点也可进行点击获取位置
<template lang="html">
<Modal v-model="visible" title="位置定位" width="800px" :mask-closable="false" @on-cancel="closeModal">
  <div class="container">
    <div class="search-box">
      <input id="tipInput" placeholder="输入关键字搜索"/>
    </div>
    <div style="height:400px" id="container" tabindex="0"></div>
    <div class="toolbar">地址: {{ address }}</div>
  </div>
  <div slot="footer" class="dialog-footer">
    <Button type="primary" @click="onSave">确定</Button>
    <Button style="margin-left: 8px" @click="closeModal">取消</Button>
  </div>
</Modal>
</template>

<script>
export default {
  name: 'MyMap',
  props: {
    // 控制model显示隐藏
    isShow: {
      type: Boolean,
      default: true
    },
    location: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    let self = this
    return {
      map: null,
      visible: this.isShow,
      address: '',
      lng: 108.88671,
      lat: 34.22344
    }
  },
  watch: {
    isShow(n, o) {
      if (n && o) {
        this.visible = n;
      }
    }
  },
  mounted() {
    this.init()
    this.mapSearchInit()
  },
  methods: {
    closeModal() {
      this.visible = false;
      this.$emit('showModel', this.visible);
    },
    //地图初始化
    init() {
      let that = this
      that.address = that.location.address;
      let map = new AMap.Map('container', {
        resizeEnable: true,
        center: [that.location.lng, that.location.lat],
        zoom: 16,
        lang: 'zh'
      })
      that.map = map;
      AMap.plugin(['AMap.Geocoder'], () => {
        let geocoder = new AMap.Geocoder({
          radius: 1000
        })
        let marker = new AMap.Marker({
          position: [that.location.lng, that.location.lat],
          offset: new AMap.Pixel(-13, -30),
          icon: new AMap.Icon({
            image: "http://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
            size: new AMap.Size(28, 35), //图标大小
            imageSize: new AMap.Size(28, 35)
          }),
        })
        marker.setMap(map);
        // 绑定事件
        map.on('click', function (ev) {
          console.log('ev', ev)
          regeoCode([ev.lnglat.lng, ev.lnglat.lat])
          that.lng = ev.lnglat.lng.toString()
          that.lat = ev.lnglat.lat.toString()
        })

        function regeoCode(lnglat) {
          map.add(marker)
          marker.setPosition(lnglat)
          geocoder.getAddress(lnglat, function (status, result) {
            if (status === 'complete' && result.regeocode) {
              that.address = result.regeocode.formattedAddress
              console.log('address', that.address);

            } else {
              console.log('位置获取失败')
            }
          })
        }
      })

      AMap.plugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.Geocoder', 'AMap.Geolocation'], () => {
        map.addControl(new AMap.Scale())
      })
      window.modalMap = map
    },
    mapSearchInit() {
      let that = this;
      var autoOptions = {
        input: "tipInput"
      };
      var auto = new AMap.Autocomplete(autoOptions);
      console.log('auto', auto)
      var placeSearch = new AMap.PlaceSearch({
        map: that.map
      });  //构造地点查询类
      AMap.event.addListener(auto, "select", select);//注册监听,当选中某条记录时会触发
      AMap.event.addListener(placeSearch, 'markerClick', function(e) {
        console.log('eeee', e)
        that.address = e.data.address;
        that.lng = e.data.location.lng
        that.lat = e.data.location.lat
        // that.$emit('saveModel', e.data.location.lng, e.data.location.lat, e.data.address);
      })
      function select(e) {
        placeSearch.setCity(e.poi.adcode);
        placeSearch.search(e.poi.name);  //关键字查询查询
      }
    },
    onSave() {
      this.$emit('saveModel', this.lng, this.lat, this.address);
    }
  }
}
</script>

<style lang="css">
.container {
  width: 100%;
  height: 500px;
}

.search-box {
  z-index: 5;
  width: 100%;
  height: 30px;
  margin-bottom: 20px;
}

.search-box input {
  float: left;
  width: 80%;
  height: 100%;
  border: 1px solid #30ccc1;
  padding: 0 8px;
  outline: none;
}

.search-box button {
  float: left;
  width: 20%;
  height: 100%;
  background: #30ccc1;
  border: 1px solid #30ccc1;
  color: #fff;
  outline: none;
}

.toolbar {
  margin-top: 20px;
}
.amap-sug-result { z-index: 9999; }
</style>

Vue2,可以使用高德地图API来获取当前定位。首先,需要引入高德地图的SDK,并在Vue组件使用AMap.Geolocation来获取当前位置的经纬度信息。以下是一个示例代码: 首先,在utils文件夹创建一个名为getLocation.js的文件,用于封装获取经纬度的公用方法。该方法使用了Promise来确保在获取到经纬度信息后再进行后续操作。具体代码如下: ```javascript function loadSDK() { if (window.AMap) return; return new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = 'http://webapi.amap.com/maps?v=1.4.6&key=*****************'; // ***为申请的高德key document.head.appendChild(script); script.onload = resolve; script.onerror = reject; }); } export default async () => { await loadSDK(); return new Promise((resolve) => { AMap.plugin('AMap.Geolocation', () => { const geolocation = new AMap.Geolocation({ enableHighAccuracy: false }); geolocation.getCurrentPosition((status, result) => { const res = status === 'complete' ? result.position : { lat: 39.909187, lng: 116.397451 }; // 默认北京 116.397451、39.909187 console.log('定位结果', res); resolve(res); }); }); }); } ``` 然后,在Vue组件,可以通过调用上述封装的方法来获取当前定位的经纬度信息。具体代码如下: ```javascript import getLocation from '@/utils/getLocation'; export default { methods: { async getCurrentLocation() { try { const position = await getLocation(); // 在这里可以使用获取到的经纬度信息进行后续操作 console.log('当前定位经纬度', position); } catch (error) { console.error('获取定位失败', error); } }, }, mounted() { this.getCurrentLocation(); }, }; ``` 以上代码,通过调用`getLocation`方法来获取当前定位的经纬度信息,并在`getCurrentLocation`方法进行后续操作。在Vue组件的`mounted`钩子函数调用`getCurrentLocation`方法来获取当前定位信息。 请注意,上述代码高德地图SDK的引入地址和申请的key需要根据实际情况进行修改。 #### 引用[.reference_title] - *1* *2* [(2023进阶版)vue+h5 通过高德地图原生) 获取当前位置定位](https://blog.csdn.net/yangzixiansheng/article/details/131308415)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [vue使用高德地图获取当前经纬度](https://blog.csdn.net/V_AYA_V/article/details/105275063)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值