点此查看 微信公众号/微信网页/微信支付/企业微信/小程序开发合集及源代码下载
本文目录
- 1. 背景
- 2. 代码
- 3. 测试
1. 背景
微信网页提供了获取当前地理位置经纬度,以及通过内置地图查看当前位置的接口。
官方接口说明如下:
// 获取位置
wx.getLocation({type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'success: function (res) {var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。var speed = res.speed; // 速度,以米/每秒计var accuracy = res.accuracy; // 位置精度}
});
// 查看位置
wx.openLocation({latitude: 0, // 纬度,浮点数,范围为90 ~ -90longitude: 0, // 经度,浮点数,范围为180 ~ -180。name: '', // 位置名address: '', // 地址详情说明scale: 1, // 地图缩放级别,整型值,范围从1~28。默认为最大infoUrl: '' // 在查看位置界面底部显示的超链接,可点击跳转
});
2. 代码
编写完整代码如下:
<input type="button" value="查看位置" onclick="openLocation()"> |<input type="button" value="获取位置" onclick="getLocation()"> |<script src="http://cdn.bootcdn.net/ajax/libs/jquery/1.9.1/jquery.min.js"></script><script src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script><script>var apiList = [ 'checkJsApi', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'networkTest', 'openLocation', 'getLocation' ];$(function() {// 向后端请求配置信息$.ajax({type : "GET",url : "/wx-server/wxJsapiSignature",data : {url : location.href.split('#')[0]},dataType : "json",success : function(res) {configInfo(res);}});});// 通过wx.config注入配置信息function configInfo(res) {wx.config({debug : false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。appId : res.appId, // 必填,公众号的唯一标识timestamp : res.timestamp, // 必填,生成签名的时间戳nonceStr : res.nonceStr, // 必填,生成签名的随机串signature : res.signature,// 必填,签名jsApiList : apiList// 必填,需要使用的JS接口列表});// 处理成功后回调wx.ready(function() {console.log("处理成功:");wx.checkJsApi({jsApiList : apiList,success : function(checkRes) {console.log("checkRes:", checkRes);}});});// 处理失败后回调wx.error(function(err) {console.log("处理失败:", err);});}// 查看位置function openLocation() {wx.openLocation({latitude : 36, // 纬度,浮点数,范围为90 ~ -90longitude : 117, // 经度,浮点数,范围为180 ~ -180。name : '', // 位置名address : '', // 地址详情说明scale : 10, // 地图缩放级别,整型值,范围从1~28。默认为最大infoUrl : '' // 在查看位置界面底部显示的超链接,可点击跳转});}// 获取位置function getLocation() {wx.getLocation({type : 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'success : function(res) {console.log(res);var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。}});}</script>
3. 测试
通过微信开发者工具,点击【获取位置】,输出如下:
使用微信打开对应网址,点击【查看位置】,效果如下。注意此时使用开发者工具无法弹出内置地图,需要使用微信客户端。