微信小程序+騰訊地圖 獲取定位與地圖選點插件


騰訊位置服務官網:https://lbs.qq.com

一。思路

通過 wx.getLocation 返回經緯度傳到后台,后台調用騰訊地圖提供的逆地址解析返回用戶位置

給個按鈕讓用戶點擊調用騰訊地圖選點插件,自己選擇位置修改

二。逆地址解析

1.小程序頁面代碼

app.json必須加入

"permission": {
    "scope.userLocation": {
      "desc": "你的位置信息將用於小程序位置接口的效果展示"
    }
  }
 
頁面加入
onLoad: function (options) {
    let that = this;
    that.authodAdress();
  }
 
authodAdress() {
    //是否授權獲取地址
    let that = this;
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '是否獲取當前位置',
            content: '需要獲取您的地理位置,請確認授權,否則無法獲取您所需數據',
            success: function (res) {
              if (res.cancel) {
                wx.showModal({
                  title: '授權失敗',
                  icon: 'success',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showModal({
                        title: '授權成功',
                        icon: 'success',
                        duration: 1000
                      })
                      that.getAddress();
                    } else {
                      wx.showModal({
                        title: '授權失敗',
                        icon: 'success',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          that.getAddress();
        } else {
          that.getAddress();
        }
      }
    })
  },
 
 getAddress() {
    //獲取地址
    let that = this;
    wx.getLocation({
      type: 'wgs84',
      isHighAccuracy: true,//開啟高精度定位
      success(res) {
        console.log("獲取地理位置----------")
        console.log(res)
  //這里改成自己封裝好調用后台的api
        locationApi.getLocationConvert(res).then((apiRes) => {
          console.log("調用后台返回地址--------")
          console.log(apiRes)
        })
      }
    })
  },
 
2.后台代碼
//逆地址解析url
private static final String locationUrl = "https://apis.map.qq.com/ws/geocoder/v1/";

/**
* 逆地址解析
*
* @param lat 緯度
* @param lng 經度
**/
public static HttpClientResult convertPosition(String lat, String lng) throws Exception {
Map<String, String> param = new HashMap<>(16);
param.put("location", String.format("%s,%s", lat, lng));
param.put("key", "騰訊地圖開發密鑰");
param.put("output", "json");
  //改成自己封裝好的調用接口
HttpClientResult httpClientResult = getHttpClientResult(locationUrl, param);
if (!httpClientResult.getContent().isEmpty()) {
String all = httpClientResult.getContent().toJSONString().replaceAll("(?<=\"lat\":\\s)(\\d+\\.\\d+)", "\"$1\"").replaceAll("(?<=\"lng\":\\s)(\\d+\\.\\d+)", "\"$1\"");
httpClientResult.setContent(JSONObject.parseObject(all));
}
return httpClientResult;
}


注意:在微信開發工具里,點擊取消授權之后在進來點擊確定,可能無法進入用戶權限設置頁面。在真機上調試就沒問題


成功實例

 

 


三。地圖插件調用
1.app.json加入
"plugins": {
    "chooseLocation": {
      "version": "1.0.5",
      "provider": "wx76a9a06e5b4e693e"
    }
  }
 
2. js頁面加入
const chooseLocation = requirePlugin('chooseLocation');//導入插件
 
onShow: function () {
    let that = this;
    // 從地圖選點插件返回后,在頁面的onShow生命周期函數中能夠調用插件接口,取得選點結果對象
    const location = chooseLocation.getLocation();// 如果點擊確認選點按鈕,則返回選點結果對象,否則返回null
  }
 
showMap() {
    //顯示地圖
    const key = ""; //使用在騰訊位置服務申請的key
    const referer = '星火之志'; //調用插件的app的名稱
    wx.navigateTo({
      url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer
    });
 
    //老版本調用
    // wx.chooseLocation({
    //   success: function(e) {
    //     console.log(e)
    //     t.setData({
    //       // now_location_name: e.address,
    //       // now_location_lat: e.latitude,
    //       // now_location_lng: e.longitude,
    //       // now_detail_address: e.name
    //     });
    //   },
    //   fail: function(t) {console.log(t)},
    //   complete: function(t) {console.log(t)}
    // });
  }
 
3. wxml頁面
<button bindtap="showMap" style="margin-top:10px">選擇位置</button>
 
注:可能在微信開發者工具上調用時會報錯,不過在真機上調試就沒問題

 

成功截圖:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM