微信公眾平臺網頁開發實戰--3.利用JSSDK在網頁中獲取地理位置
阿新 • • 發佈:2019-01-06
複製一份JSSDK環境,建立一份index.html檔案,結構如圖7.1所示。
圖7.1 7.1節檔案結構
在location.js中,封裝“getLocation”介面,如下:
01 wxJSSDK.location = function(locationApi){ 02 if(wxJSSDK.isReady){ //wxJSSDK.isReady 檢視微信JSSDK是否初始化完畢 03 if(locationApi){ 04 locationApi.getLocation && wx.getLocation({ //獲取地理位置介面 05 success: function (res) { 06 locationApi.getLocation.success && 07 locationApi.getLocation.success(res); 08 } 09 }); 10 }else{ 11 console.log("缺少配置引數"); 12 } 13 }else{ 14 console.log("抱歉,wx沒有初始化完畢,請等待wx初始化完畢,再呼叫位置介面服 15 務。"); 16 } 17 }
在index.html檔案中,增加“獲取地理位置”按鈕,以及顯示獲取之後的位置資訊,程式碼結構,如下:
01 <!DOCTYPE html> 02 <html lang="en"> 03 <head> 04 <metacharset="UTF-8"> 05 <meta name="viewport" content="width=device-width,initial-scale=1.0, 06 minimum-scale=1, maximum-scale=1.0,user-scalable=no"> 07 <title>第7章 7.1節 位置操作介面</title> 08 <!--依賴檔案:jQuery--> 09 <script src="./js/jquery-1.11.2.min.js"></script> 10 <!--依賴檔案:微信的JSSDK原始檔--> 11 <scriptsrc="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script> 12 <!--依賴檔案:coolie--> 13 <script src="./js/cookie.js"></script> 14 <!--JSSDK的環境--> 15 <script src="./js/wxJSSDK.js"></script> 16 <!--引入檢測API的位置服務--> 17 <script src="location.js"></script> 18 <style> 19 input{ 20 width: 100%; 21 padding: 0.2em; 22 background-color: #5eb95e; 23 font-size: 1.4em; 24 background-image: linear-gradient(to bottom, #62c462, #57a957); 25 background-repeat: repeat-x; 26 color: #ffffff; 27 text-align: center; 28 text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); 29 border-radius: 0.3em; 30 } 31 #info{ 32 border-left: 3px solid#03a9f4; 33 background-color: #5eb95e; 34 color: #ffffff; 35 border-radius: 0.3em; 36 text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); 37 } 38 </style> 39 </head> 40 <body> 41 <h1 style="font-size: 8em">:)</h1> 42 <b style="font-size: 3em">位置操作介面!</b><br/><br /> 43 <div id="info"> 44 <p>緯度:<em id="latitude">無</em></p> 45 <p>經度:<em id="longitude">無</em></p> 46 <p>速度:<em id="speed">無</em></p> 47 <p>位置精度:<em id="accuracy">無</em></p> 48 </div> 49 <input type="button" value="獲取當前地理位置資訊" id="getLocation" /> 50 </body> 51 </html>
然後在location.js中增加響應事件,程式碼如下:
01 window.onload = function(){ 02 var latitude,longitude, speed ,accuracy; // 位置資訊初始變數 03 $("#getLocation").click(function(){ // 獲取地理位置介面 04 wxJSSDK.location({ 05 getLocation:{ 06 success:function (res) { 07 latitude = res.latitude; // 緯度,浮點數,範圍為90 ~ -90 08 $("#latitude").html(latitude); 09 longitude = res.longitude; // 經度,浮點數,範圍為180 ~ -180。 10 $("#longitude").html(longitude); 11 speed = res.speed; // 速度,以米/每秒計 12 $("#speed").html(speed); 13 accuracy = res.accuracy; // 位置精度 14 $("#accuracy").html(accuracy); 15 } 16 } 17 }); 18 }); 19 }
最後記得在JSSDK的配置環境中加入“getLocation”API的許可權。
【程式碼解釋】
“getLocation”的位置成功後,會返回“緯度”、“經度”、“速度”、“位置精度”的相關資訊。當點選“獲取位置”的按鈕之後,微信會彈出提示資訊,如圖7.2所示。獲取位置服務成功之後的結果如圖7.3所示。
圖7.2 微信JSSDK獲取位置資訊提示
圖7.3 獲取位置服務成功的資訊
《微信公眾平臺網頁開發實戰——HTML5+JSSDK混合開發解密》歡迎一起交流本書