复制一份JSSDK环境,建立一份index.html文件,结构如图7.1所示。html
图7.1 7.1节文件结构jquery
在location.js中,封装“getLocation”接口,以下:git
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
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
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中增长响应事件,代码以下:cookie
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的权限。spa
“getLocation”的位置成功后,会返回“纬度”、“经度”、“速度”、“位置精度”的相关信息。当点击“获取位置”的按钮以后,微信会弹出提示信息,如图7.2所示。获取位置服务成功以后的结果如图7.3所示。scala
图7.2 微信JSSDK获取位置信息提示code
图7.3 获取位置服务成功的信息htm