微信小程序使用腾讯位置服务获取经纬度或省市区

微信小程序使用腾讯位置服务获取经纬度或省市区

官方文档:https://lbs.qq.com/qqmap_wx_jssdk/method-geocoder.html


根据经纬度获取省市区

var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');

// 实例化API核心类
var qqmapsdk = new QQMapWX({
  key: '去官方文档可以申请自己的密钥' // 必填
});
/**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    var latitude = '37.94036'// 纬度,浮点数,范围为90 ~ -90
    var longitude = '112.48699' // 经度,浮点数,范围为180 ~ -180
    //根据经纬度获取所在城市
    qqmapsdk.reverseGeocoder({
      location: { latitude: latitude, longitude: longitude },
      success: function (res) {
        console.log('省市区:', res.result.address)
      }
    });
  },

根据地址获取经纬度
.js

//腾讯地图
  formSubmit(e) {
    var _this = this;
    //调用地址解析接口
    qqmapsdk.geocoder({
      //获取表单传入地址
      address: e.detail.value.geocoder, //地址参数,例:固定地址,address: '北京市海淀区彩和坊路海淀西大街74号'
      success: function (res) {//成功后的回调
        console.log(res);
        var res = res.result;
        var latitude = res.location.lat;
        var longitude = res.location.lng;
        //根据地址解析在地图上标记解析地址位置
        _this.setData({ // 获取返回结果,放到markers及poi中,并在地图展示
          markers: [{
            id: 0,
            title: res.title,
            latitude: latitude,
            longitude: longitude,
            width: 20,
            height: 20,
          }],
          poi: { //根据自己data数据设置相应的地图中心坐标变量名称
            latitude: latitude,
            longitude: longitude
          }
        });
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        console.log(res);
      }
    })
  },

.wxml

<!--地图容器-->
<!--longitude及latitude为设置为调转到指定地址位置,默认不显示-->
<map id="myMap"
    markers="{{markers}}"
    style="width:100%;height:300px;"
    longitude="{{poi.longitude}}"
    latitude="{{poi.latitude}}"
    scale='16' show-location>
</map>
<!--form表单-->
<form bindsubmit="formSubmit">
    <!--地址描述输入框,示例:北京市海淀区彩和坊路海淀西大街74号-->
    <input style="border:1px solid #000;" name="geocoder"></input>
    <!--提交表单数据-->
    <button form-type="submit">地址解析</button>
</form>
<!--地址描述经纬度展示-->
<view>地址纬度:{{poi.latitude}}</view>
<view>地址经度:{{poi.longitude}}</view>
<view bindtap="dinsx">地址</view>

有什么问题欢迎评论留言,我会及时回复你的

原创文章 75 获赞 87 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43764578/article/details/102851206