vue2使用高德地图点击或搜索获取经纬度

1 篇文章 0 订阅
该文章展示了如何在Vue.js应用中创建一个输入框组件,用户可以输入地址进行搜索。通过高德地图API,实现点击地图获取经纬度,以及根据地址反编码获取地理位置信息。同时,文章还包含了初始化地图、设置标记和调整视图等操作。
摘要由CSDN通过智能技术生成

<el-input
  v-model.trim="searchLocation"
  placeholder="请输入地址搜索"
  maxlength="30"
  clearable
  @blur="getLocation"
  @keyup.enter.native="getLocation"
/>
<div id="container" />

data() {
  return {
    searchLocation: '',
    ruleForm: {},
    map: null,
    marker: null
  }
},

mounted() {
  this.initMap()
  this.setLocal()
},
methods: {
  // 初始化地图
  initMap() {
    this.map = new AMap.Map('container', {
      zoom: 9, // 级别
      center: [116.397428, 39.90923] // 中心点坐标
      // viewMode: "3D", // 使用3D视图
    })
    this.marker = new AMap.Marker()
    this.map.on('click', this.clickMap)  // 地图是否允许点击
  },
  setLocal(longitude, latitude) {
    if (this.marker) {
      this.marker.setMap(null)
    }
    if (!longitude) {
      this.map.setCenter([116.397428, 39.90923])
      return
    }
    this.map.setCenter([longitude, latitude])
    if (longitude) {
      const lnglat = new AMap.LngLat(longitude, latitude)
      this.marker.setPosition(lnglat)
      this.marker.setMap(this.map)
      this.map.setFitView(this.marker)
    }
  },
  clickMap(e) {
    this.searchLocation = ''
    this.ruleForm.longitude = e.lnglat.lng
    this.ruleForm.latitude = e.lnglat.lat
    this.$set(this.ruleForm, 'coordinate', e.lnglat.lng + ',' + e.lnglat.lat)
    this.marker.setPosition(e.lnglat)
    this.map.add(this.marker)
    this.map.setFitView(this.marker)
  },
  getLocation() {
    const geocoder = new AMap.Geocoder({
      city: '全国' // 城市设为北京,默认:“全国”
    })
    geocoder.getLocation(this.searchLocation, (status, result) => {
      if (status === 'complete' && result.geocodes.length) {
        const lnglat = result.geocodes[0].location
        this.$set(this.ruleForm, 'longitude', result.geocodes[0].location.lng)
        this.$set(this.ruleForm, 'latitude', result.geocodes[0].location.lat)
        this.$set(this.ruleForm, 'coordinate', result.geocodes[0].location.lng + ',' + result.geocodes[0].location.lat)
        this.marker.setPosition(lnglat)
        this.map.add(this.marker)
        this.map.setFitView(this.marker)
      } else {
        console.error('根据地址查询位置失败')
      }
    })
  },
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值