JavaScript微信定位功能實現方法_javascript技巧

來源:互聯網
上載者:User

分享下微信是如何定位的:

本文主要講解如何利用微信定位,如何將定位到的經緯度轉換為百度地圖對應的經緯度,以及處理定位失敗、取消及錯誤時的預設做法。

//擷取地理位置資訊start//封裝成一個函數 function getPosition() { //用ajax請求  $.ajax({   url: "/wechat/jssdk",//請求地址   type: 'post',//post請求   dataType: 'json',   contentType: "application/x-www-form-urlencoded; charset=utf-8",   data: {    'url': location.href.split('#')[0]//將第一個#號前的地址傳遞   },//請求成功的函數   success: function (data) {    wx.config({     // debug: true,     appId: data.data.appId,     timestamp: data.data.timestamp,     nonceStr: data.data.nonceStr,     signature: data.data.signature,     jsApiList: ['checkJsApi', 'getLocation']    });    wx.ready(function () {     wx.getLocation({     //獲得定位成功      success: function (res) {      //這是微信返回的真正經緯度       var oldLat = res.latitude; // 緯度,浮點數,範圍為90 ~ -90       var oldLng = res.longitude; // 經度,浮點數,範圍為180 ~ -180。       /*下面是為了將獲得的真正經緯度轉換為對應的百度經緯度,因為是利用百度地圖的經緯度去查詢資料的,資料庫中存的也是百度的經緯度*/       //建立一個百度地圖的點       var customerPoint = new BMap.Point(oldLng, oldLat);       //       var convertor = new BMap.Convertor();       var pointArr = [];//建立一個數組       pointArr.push(customerPoint);//將剛才的點放進去       convertor.translate(pointArr, 1, 5, initMap); //轉換座標       function initMap(data) {        if (data.status === 0) {//轉換成功         var point = data.points[0];//得到後的點         var lng = point.lng;//獲得轉換後的經度         var lat = point.lat;//獲得轉換後的緯度         toDoFunction(lng, lat);//將經緯度傳入到要運用的函數中        } else {        //下面兩行是預設定位到西湖的經緯度         lng = 120.141375;         lat = 30.257806;         toDoFunction(lng, lat);//將經緯度傳入到要運用的函數中        }       }      },      //取消定位      cancel: function () {      //下面兩行是預設定位到西湖的經緯度       var lng = 120.141375;       var lat = 30.257806;       toDoFunction(lng, lat);//將經緯度傳入到要運用的函數中      },      //定位失敗      fail: function () {      //下面兩行是預設定位到西湖的經緯度       var lng = 120.141375;       var lat = 30.257806;       toDoFunction(lng, lat);//將經緯度傳入到要運用的函數中      }     });     //定位發生錯誤     wx.error(function () {     //下面兩行是預設定位到西湖的經緯度      var lng = 120.141375;      var lat = 30.257806;      toDoFunction(lng, lat);//將經緯度傳入到要運用的函數中     });    });   }  }); }

以上代碼,如果可以定位到就用定位到的真正的經緯度,再轉換成百度地圖對應的經緯度,如果定位失敗或者是點擊取消或者發生錯誤,則預設定位到西湖的經緯度。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.