批改状态:合格
老师批语:
获取地理位置信息,是通过js获取的,因此 需要先在公众号后台配置调用js接口的域名,只需配置一级域名,不要添加http://协议前缀等
在页面当中引入需要的js文件,文档中有
最重要的就是生成调用js接口需要的签名
<?php
class Weixin{
//获取地理位置 生成签名
public function location()
{
$appid = Config::get("wx.appid");
$timestamp = time();
$nonce = md5(time().rand(1,999));
$access_token = $this -> model -> get_access_token();
$jsapi_ticket = $this -> model -> jsapi_ticket($access_token);
$data['noncestr'] = $nonce; //随机字符串必须要与上面的随机字符串一直
$data['timestamp'] = $timestamp; //时间戳必须要与上面的时间戳一直
$data['jsapi_ticket'] = $jsapi_ticket;
$data['url'] = "http://668e52e6.ngrok.io/index.php/index/weixin/location"; //地址必须是调用js接口的地址
ksort($data); //对键值按照ASCII排序
//排序之后生成一个字符串 格式为"key1=value1&key2=value2..." 使用urldecode()解码 防止url转义
$string = urldecode(http_build_query($data));
//生成签名
$signature = sha1($string); //在对上面生成好的字符串进行sha1加密 就是要的签名
\think\facade\View::assign([
"appid" => $appid,
"timestamp" =>$timestamp,
"nonce" => $nonce,
"signature" => $signature
]);
//注意: 在公众号后台配置js接口调用域名时 不要加http://等前缀 只需加一级域名即可 切记
return \think\facade\View::fetch();
}
?>点击 "运行实例" 按钮查看在线实例
用到的js文件
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script>
var a = '{$appid}';
var b = '{$timestamp}';
var c = '{$nonce}';
var d = '{$signature}';
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: a, // 必填,公众号的唯一标识
timestamp:b , // 必填,生成签名的时间戳
nonceStr: c, // 必填,生成签名的随机串
signature: d,// 必填,签名
jsApiList: ['getLocation','openLocation'] // 必填,需要使用的JS接口列表
});
wx.ready(function(){
// config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
getLocation(openlocation);
});
function getLocation(callback) {
wx.getLocation({
// 默认为wgs84的gps坐标,此方式定位有出乎 如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
type: 'gcj02',
success: function (res) {
var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
var speed = res.speed; // 速度,以米/每秒计
var accuracy = res.accuracy; // 位置精度
if (callback != undefined){
callback(res);
}
}
});
}
function openlocation(res) {
wx.openLocation({
latitude: res.latitude, // 纬度,浮点数,范围为90 ~ -90
longitude: res.longitude, // 经度,浮点数,范围为180 ~ -180。
name: '', // 位置名
address: '', // 地址详情说明
scale: 15, // 地图缩放级别,整形值,范围从1~28。默认为最大
infoUrl: '' // 在查看位置界面底部显示的超链接,可点击跳转
});
}
</script>点击 "运行实例" 按钮查看在线实例
到此,在微信中查看 使用微信内置地图可以查看自己的位置信息
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号