使用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节的方法来获得详细的地理位置信息。