讀古今文學網 > 微信公眾平台開發:從零基礎到ThinkPHP5高性能框架實踐 > 14.4.2 獲取用戶坐標及地址 >

14.4.2 獲取用戶坐標及地址

使用JS-SDK獲取用戶地理位置坐標的代碼如下。


 1 <?php
 2 require_once('wxjssdk.class.php');
 3 $weixin = new class_weixin;
 4 $signPackage = $weixin->GetSignPackage;
 5 ?>
 6 <!DOCTYPE html>
 7 <html>
 8 <head>
 9     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
10     <meta name="viewport" content="width=device-width, initial-scale=1.0, maxi
       mum-scale=2.0, minimum-scale=1.0, user-scalable=no" />
11     <meta name="format-detection" content="telephone=no" />
12     <title>位置</title>
13     <meta name="viewport" content="width=device-width, initial-scale=1, user-s
       calable=0">
14     <link rel="stylesheet" href="http:// demo.open.weixin.qq.com/jssdk/css/style.
       css">
15 </head>
16 <body ontouchstart="">
17 </body>
18 <script src="https:// res.wx.qq.com/open/js/jweixin-1.1.0.js"></script>
19 <script>
20     wx.config({
21         debug: false,
22         appId: '<?php echo $signPackage["appId"];?>',
23         timestamp: <?php echo $signPackage["timestamp"];?>,
24         nonceStr: '<?php echo $signPackage["nonceStr"];?>',
25         signature: '<?php echo $signPackage["signature"];?>',
26         jsApiList: [
27             'checkJsApi',
28             'openLocation',
29             'getLocation',
30           ]
31     });
32 
33     wx.ready(function  {
34         
35         // 自動執行的
36         wx.checkJsApi({
37             jsApiList: [
38                 'getLocation',
39             ],
40             success: function (res) {
41             }
42         });
43     
44         // 如果不支持,則不會執行
45         wx.getLocation({
46             success: function (res) {
47                 alert(JSON.stringify(res));
48           },
49           cancel: function (res) {
50                 alert('用戶拒絕授權獲取地理位置');
51           }
52         });
53       
54     });
55 
56     wx.error(function (res) {
57         alert(res.errMsg);
58     });
59  </script>
60 </html>
  

獲得坐標時的效果圖如圖14-3所示。

圖14-2 分享到朋友圈

圖14-3 獲取用戶地理位置

獲得坐標之後,一項重要的工作是將坐標轉換為地址。

讀者可以利用本書6.3.2節的方法來獲得詳細的地理位置信息。