定位-获取经纬度、地址信息(高德/腾讯)

高德API

获取高德key

  1. 高德开放平台注册认证
  2. 进入到应用管理 → 我的应用在这里插入图片描述
  3. 创建新应用 → 点击添加 → 填写所需信息 → 生成相应的key和安全密钥 在这里插入图片描述

项目使用

  1. 在公共的html文件(public/index.html)中引入
  <script type="text/javascript">
    window._AMapSecurityConfig = {
      // 升级之后key必须和密钥一起使用,否则不生效
      securityJsCode: '生成的安全密钥'
    }
  </script>
  <script
    type="text/javascript"
    src="https://webapi.amap.com/maps?v=2.0&key=生成的key"
  ></script>

如果不加安全密钥,查询地址时会一直失败并报错INVALID_USER_SCODE

  1. 因为项目需求,这里把获取定位方法封装成一个函数
/** 
* 获取经纬度和地址并返回信息
* API是异步的,这里用Promise处理,逻辑在then中处理
*/
export const getLocation = function () {
  return new Promise((resolve, reject) => {
    let location = {
      lng: '', // 经度
      lat: '', // 纬度
      address: ''
    }
    AMap.plugin(["AMap.Geolocation", "AMap.Geocoder"], function () {
      var geolocation = new AMap.Geolocation({
        // 是否使用高精度定位,默认:true
        enableHighAccuracy: true,
        // 设置定位超时时间,默认:无穷大
        timeout: 10000,
      })

      // 地址逆解析
      var geocoder = new AMap.Geocoder({
        city: "", // 城市设为北京,默认:“全国”
        radius: 1000 // 范围,默认:500
      })
      function regeoCode() {
        return new Promise((resolve, reject) => {
          var lnglat = [location.lng, location.lat]
          geocoder.getAddress(lnglat, function (status, result) {
            if (status === 'complete' && result.regeocode) {
              console.log('查询地址成功', result)
              location.address = result.regeocode.formattedAddress
              console.log('详细信息', location)
              resolve(location)
            } else {
              console.log('根据经纬度查询地址失败', result)
              reject(result)
            }
          })
        })
      }

      geolocation.getCurrentPosition(function (status, result) {
        console.log('定位状态和结果', status, result)
        if (status == 'complete') {
          console.log('定位成功', result)
          location.lat = result.position.lat
          location.lng = result.position.lng
          regeoCode().then(res => {
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        } else {
          console.log("定位失败:" + result.message)
          reject(result.message)
        }
      })
    })
  })
}

插件引入形式有两种:
① 同步加载插件:可以在html引入的入口地址后面加上&plugin=你需要的插件,引入多个用逗号隔开
② 异步加载插件:AMap.plugin(你需要的插件, function () {})多个插件使用[插件1, 插件2],通过AMap.plugin方法按需引入插件,在plugin回调之后使用插件功能
大家如果有别的功能需求,可以去官网里面找相应的功能,里面有示例:高德地图API教程

  1. 文件中使用
// 引入
import { getLocation } from '@/utils/positionLoaction'
...
getLocation().then(res => {
    console.log('定位结果', res);
}).catch(error => {
    console.log('定位错误信息', error);
})
...

以下是控制台输出,供参考

在这里插入图片描述

腾讯

  1. 跟高德一样,需要去开发平台注册申请key
  2. 页面使用
<template>
  <div>
    <iframe
      id="geoPage"
      width="0"
      height="0"
      frameborder="0"
      style="display: none"
      scrolling="no"
      src="https://apis.map.qq.com/tools/geolocation?key=你的key&referer=myapp"
    >
    </iframe>
    <div>
      <p ref="lng">经度:{{ loc.lng }}</p>
      <p ref="lat">纬度:{{ loc.lat }}</p>
      <p ref="city">城市:{{ loc.city }}</p>
      <p ref="city">地址:{{ loc.address }}</p>
    </div>
  </div>
</template>

<script>
import { getLocation, getLocationH5 } from '@/utils/public/positionLoaction'
export default {
  name: 'Position',
  data() {
    return {
      loc: {},
    }
  },
  created() {
    const _this = this
    window.addEventListener('message', function (event) {
      // 位置信息
      if (event.data?.lat) {
        _this.loc = event.data
        console.log('location', event.data)
        // 这里是根据腾讯返回的经纬度传给高德,获取具体位置(看个人)
        _this.updateAdress().then(res => {
          console.log(res);
          _this.loc.address = res
        }).catch(error => {
			console.log(error)
		})
      }
    }, false)
    setTimeout(function () {
      if (!_this.loc) {
        this.$toast('定位超时')
      }
    }, 6000) // 6s为推荐值,业务调用方可根据自己的需求设置改时间,不建议太短 
  },
  methods: {
    updateAdress() {
      const _this = this
      return new Promise((resolve, reject) => {
        AMap.plugin(["AMap.Geolocation", "AMap.Geocoder"], function () {
          var geocoder = new AMap.Geocoder({
            radius: 1000 //范围,默认:500
          })
          var lnglat = [_this.loc.lng, _this.loc.lat]
          geocoder.getAddress(lnglat, function (status, result) {
            if (status === 'complete' && result.regeocode) {
              console.log('高德-查询地址成功', result.regeocode)
              resolve(result.regeocode.formattedAddress)
            } else {
              console.log('高德-根据经纬度查询地址失败', result)
              reject(result)
            }
          })
        })
      })
    },
  },
  destroyed() {
    window.removeEventListener('message')
  }
}
</script>

<style>
</style>

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值