移动端定位

1,222 阅读1分钟

项目中用到了自动定位获取当前的位置的功能,引入高德地图中的定位和使用微信JS-SDK中的定位功能,具体代码如下:

h5定位:

  • 首先安装高德插件AMap
  • 在项目中(我们使用的是vue框架)create生命周期方法中加载高德地图初始化方法(代码如下)
  created() {
    VueAMap.initAMapApiLoader({
      // 高德的key
      key: '自己申请的ID',
      // 插件集合
      plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.Geocoder', 'AMap.Geolocation'],
      // 高德 sdk 版本,默认为 1.4.4
      v: '1.4.4'
    })
  },

  • 执行获取当前地址的方法(此方法是异步方法,所以点击获取地址功能按钮时,会有几秒的延时,亲测会有3s-10s的时间),返回值是经纬度
        var map = new AMap.Map('container', {
          resizeEnable: true
        })
        const self = this
        AMap.plugin('AMap.Geolocation', function() {
          var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, // 是否使用高精度定位,默认:true
            timeout: 5000, // 超过10秒后停止定位,默认:5s
            buttonPosition: 'RB', // 定位按钮的停靠位置
            buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
            zoomToAccuracy: true // 定位成功后是否自动调整地图视野到定位点
          })
          geolocation.getCurrentPosition((status, result) => {
            console.log(status, result)

  • 获取到经纬度,根据经纬度转化为具体地址(地址的精确性存在问题,但是可以定位到大概位置)
            if (result && result.position) {
              AMap.plugin('AMap.Geocoder', function() {
                var geocoder = new AMap.Geocoder({
                  city: '010'
                })
                geocoder.getAddress([result.position.lng, result.position.lat], function(status, result) {
                  if (status === 'complete' && result.info === 'OK') {
                    self.isLoading = false
                    self.data ={
                      ...self.data,
                      province: result.regeocode.addressComponent.province, 
                      city: result.regeocode.addressComponent.city,
                      county: result.regeocode.addressComponent.district,
                      area_code: result.regeocode.addressComponent.adcode
                    }
                  }
                })
              })

微信定位

  • 首先判断是否在微信环境中然后执行如下代码
        wx.getLocation({
          type: 'gcj02',
          success: (res) => {
            if (res.longitude && res.latitude) {
              AMap.plugin('AMap.Geocoder', function() {
                var geocoder = new AMap.Geocoder({
                  city: '010'
                })
                geocoder.getAddress([res.longitude, res.latitude], function(status, result) {


返回的longitude和latitude就是经纬度,然后调用高德地图经纬度转化为具体的方法。

第一次写,没有经验。希望大家可以不吝赐教,谢谢!