微信小程序-自动定位并将经纬度解析为具体地址

时间:2020-07-03 19:24:31   收藏:0   阅读:112

微信小程序可以通过API获取当前位置的经纬度。

在微信小程序开发文档中可以找到这个API的使用示例。

https://developers.weixin.qq.com/miniprogram/dev/api/location.html

 

但是需要获取具体地址 如:湖南省长沙市岳麓区****,就需要使用到外部的API(此处用到的是腾讯的位置服务)

这是开发文档 里面有具体步骤和示例 http://lbs.qq.com/qqmap_wx_jssdk/index.html

自动获取地理位置可用于签到,具体实现如下。

一、index.wxml 显示经纬度及地址数据

<!--index.wxml-->

<view wx:if="{{latitude}}" mode="widthFix">纬度:{{latitude}}</view>
<view wx:if="{{longitude}}" mode="widthFix">经度:{{longitude}}</view>
<view wx:if="{{address}}" mode="widthFix">地址:{{address}}</view>

二、index.js 调用API获取数据

//index.js
var QQMapWX = require(‘../../util/qqmap-wx-jssdk.js‘)  //引入获得地址的js文件
var qqmapsdk;
const app = getApp()
Page({
  data: {
   
    latitude: null,
    longitude: null,
    address: null,
    
  },
  onLoad: function () {
    this.getLocation();//一进来就得到地址
  },
  getLocation() {
    var that = this
    wx.getLocation({//调用API得到经纬度
      type: ‘wgs84‘,
      success: function (res) {
        var speed = res.speed
        var accuracy = res.accuracy
        var latitude = res.latitude
        var longitude = res.longitude

        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
        //地址解析
        var demo = new QQMapWX({
          key: ‘****‘// 这个KEY的获取方式在上面链接 腾讯位置服务的开发文档中有详细的申请密钥步骤
        });

        demo.reverseGeocoder({//地址解析
          location: {
            latitude: latitude,
            longitude: longitude
          },
          success: function (res) {
            console.log(res);
            //获得地址
            that.setData({
              address: res.result.address
            })
          },
          fail: function (res) {
            console.log(res);
          },
          complete: function (res) {
            console.log(res);
          }
        });
      }

    })
  }
})

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!