Vue 引入高德地图+点击定位

 1. npm安装高德地图

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

2. 组件中引入

import AMapLoader from '@amap/amap-jsapi-loader'

3. 密匙配置

window._AMapSecurityConfig = {
  securityJsCode: '8bec9c54c48d3a7cb270ae1d354d3c87'
}

4. 在组件中使用

  mounted() {
    const _this = this
    AMapLoader.load({
      key: _this.key,
      version: '2.0',
      plugins: ['AMap.ToolBar', 'AMap.Geocoder', 'AMap.PlaceSearch', 'AMap.AutoComplete']
    })
      .then((AMap) => {
        // 地图
        _this.map = new AMap.Map('container', {
          viewMode: '2D',
          zoom: 10,
          center: [116.410435, 39.905418]
        })

        _this.map.addControl(new AMap.ToolBar())

        // 搜索
        _this.placeSearch = new AMap.PlaceSearch({
          city: ''
        })

        // 点击事件
        _this.map.on('click', _this.clickMap)

        // 逆向地理编码插件
        _this.geocoder = new AMap.Geocoder({
          // city: "010", //城市设为北京,默认:“全国”
          radius: 1000 // 范围,默认:500
        })
      })
      .catch((e) => {
        console.log(e)
      })
  },

5. 点击事件

clickMap(e) {
  const longitude = e.lnglat.getLng()  // 经度
  const latitude = e.lnglat.getLat()   // 纬度
  const _this = this
  _this.geocoder.getAddress([longitude, latitude], (status, result) => {
    console.log(status, result)
    if (status === 'complete' && result.info === 'OK') {
      _this.$emit('change', result, { longitude: longitude, latitude: latitude })
      // 传给父组件
    }
  })
}

6. 父组件接收

changeMap(result, lnglat) {
  console.log(result, lnglat)
  this.infoForm.nodeAddress = result.regeocode.formattedAddress
}

7. 添加marker

    addMarker(address, lnglat) {
      // 移除已经创建的marker
      if (this.marker) this.map.remove(this.marker)
      // 设置地图中心点和缩放级别
      this.map.setZoomAndCenter(16, lnglat)
      // 自定义标记点
      this.marker = new AMap.Marker({
        position: lnglat,
        anchor: 'top-center',
        offset: new AMap.Pixel(-10, -10)
      })
      // 添加
      this.marker.setMap(this.map)
      // 设置label
      this.marker.setLabel({
        direction: 'top-center',
        offset: new AMap.Pixel(10, 0), // 设置文本标注偏移量
        content: "<div style='width:50px;'>" + address + '</div>' // 设置文本标注内容
      })
    }

8. 搜索 

search(keyword) {
  const _this = this
  _this.placeSearch.search(keyword, function(status, result) {
       _this.$emit('searchChange', result.poiList.pois)
  })
},

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

萨科学习之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值