微信小程序城市定位(百度地圖API)


概述

微信小程序提供一些API(地址)用於獲取當前用戶的地理位置等信息,但無論是wx.getLocation,還是wx.chooseLocation均沒有單獨的字段表示國家與城市信息,僅有經緯度信息。在實際項目需求中是不夠的,我們可以將微信提供的經緯度信息利用第三方地圖API轉換為國家與城市信息。

微信小程序官方地理位置相關API:https://mp.weixin.qq.com/debug/wxadoc/dev/api/location.html#wxchooselocationobject

百度地圖API

1.首先我們需要在百度地圖開放平台(http://lbsyun.baidu.com/index.php) 注冊為開發者。

2.申請開發者密鑰(AK):其中,APPID處填寫小程序的APP ID

3.百度地圖逆地址解析API可以接受經緯度坐標坐標,返回帶有國家和城市的地址信息。

逆地址解析API:http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding

此處注意:百度地圖API默認采用坐標為bd09ll(百度經緯度坐標),而微信內置地圖獲得的經緯度坐標為wgs84ll( GPS經緯度)。

開發

功能一:獲取位置並顯示地理信息。



1.利用微信選擇位置API,獲得經緯度信息
2.百度地圖API,將微信獲得的經緯度傳給百度,獲得城市等信息

'https://api.map.baidu.com/geocoder/v2/?ak=自己申請的百度密鑰&location=' + lb.latitude + ',' + lb.longitude + '&output=json&coordtype=wgs84ll'


3.我們將微信得到的位置名稱“故宮博物館”與百度地圖API得到的“北京市東城區”合並顯示在頁面上。
完整代碼:

    wx.chooseLocation({   // ①.利用微信選擇位置API,獲得經緯度信息  
      success: function (lb) {
        console.log("地理位置")
        console.log(lb)
        that.data.addressData = lb
        wx.request({ // ②百度地圖API,將微信獲得的經緯度傳給百度,獲得城市等信息
          url: `https://api.map.baidu.com/geocoder/v2/?ak=GuMNe9FqXsvKoWY9VZaWNw9wlzUGjyTE&location${lb.latitude},${lb.longitude}&output=json&coordtype=wgs84ll`,
          data: {},
          header: {
            'Content-Type': 'application/json'
          },
          success: function (res) {
            console.log(res.data.result);
            console.log(res.data.result.addressComponent.city + res.data.result.addressComponent.district);
            that.setData({
         // ③.我們將微信得到的位置名稱“故宮博物館”與百度地圖API得到的“北京市東城區”合並顯示在頁面上。 addressAll: res.data.result.addressComponent.city
+ res.data.result.addressComponent.district + "·" + lb.name }) }, fail: function () { // fail }, complete: function () { // complete } }) }, cancel: function (lb) { }, fail: function (lb) { console.log(lb) } })

 

功能二:點擊位置查看地圖。


此功能較為簡單。
1.在地址處定義好需要的數據:

 <block wx:if="{{resultData[k].address != 'undefined'}}">
      <text class="address" bindtap="bindLocation" data-address="{{resultData[k].address}}" data-name="{{resultData[k].name}}" data-longitude="{{resultData[k].longitude}}" data-latitude="{{resultData[k].latitude}}">{{resultData[k].addressAll}}</text>
    </block>

2.借助微信小程序的查看位置的API wx.openLocation。這個API會自動打開地圖。
微信小程序顯示位置的API:https://mp.weixin.qq.com/debug/wxadoc/dev/api/location.html#wxopenlocationobject

 bindLocation: function (e) {// 點擊地址,查看位置
 wx.openLocation({
      latitude: e.target.dataset.latitude,
      longitude: e.target.dataset.longitude,
      name: e.target.dataset.name,
      address: e.target.dataset.address
    })
  },

最后:今天要分享的就是這些了,有問題歡迎留言。


免責聲明!

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



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