调用微信定位功能 lat _ lng php方法

时间:2022-10-10 21:16:46

 

 

{:wx_jssdk_config("false")}  //最主要的这一句 没有这一句在微信浏览器里是无法调用的定位功能的。下面有这个方法说明
<script>
wx.ready(
function(){
wx.getLocation({
type:
'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success: function (res) {
var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
var data = {
"lat":latitude,
"lng": longitude,
};
// console.log(data);
$.ajax({
url:
'{:U("Index/lat_lng_add")}',
type:
"POST",
data: data,
success:
function (data) {}
});
}
})
});
</script>

 

以下代码是需要放在function.php中的

/**
* 直接生成微信jssdk_config
* @echo string $jssdk Jssdk_config
* @author 5heAtMin9 <sheatming@foxmail.com>
*/

function wx_jssdk_config($debug='true'){
$getSignPackage = wx_getSignPackage();
$jssdk = '<script src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>';
$jssdk .= '<script>
wx.config({
debug:
'.$debug.',
appId: "
'.$getSignPackage['appId'].'",
timestamp: "
'.$getSignPackage['timestamp'].'",
nonceStr: "
'.$getSignPackage['nonceStr'].'",
signature: "
'.$getSignPackage['signature'].'",
jsApiList: ["checkJsApi","onMenuShareTimeline","onMenuShareAppMessage","onMenuShareQQ", "onMenuShareWeibo","onMenuShareQZone","hideMenuItems","showMenuItems","hideAllNonBaseMenuItem","showAllNonBaseMenuItem","translateVoice","startRecord","stopRecord","onVoiceRecordEnd","playVoice","onVoicePlayEnd","pauseVoice","stopVoice","uploadVoice","downloadVoice","chooseImage","previewImage","uploadImage","downloadImage","getNetworkType","openLocation","getLocation","hideOptionMenu","showOptionMenu","closeWindow","scanQRCode","chooseWXPay","openProductSpecificView","addCard","chooseCard","openCard"],
});
</script>
';
echo $jssdk;
}





/**
* Jssdk所需信息
* @return array $signPackage Jssdk所需信息
* @author 5heAtMin9 <sheatming@foxmail.com>
*/

function wx_getSignPackage()
{
$jsapiTicket = wx_getJsApiTicket();
// 注意 URL 一定要动态获取,不能 hardcode.
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$timestamp = time();
$nonceStr = getRandom(32);
// 这里参数的顺序要按照 key 值 ASCII 码升序排序
$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
$signature = sha1($string);
$signPackage = array(
"appId" => C('WX_APPID'),
"nonceStr" => $nonceStr,
"timestamp" => $timestamp,
"url" => $url,
"signature" => $signature,
"rawString" => $string
);
return $signPackage;
}

function wx_getJsApiTicket() {
$jturl = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.wx_get_access_token() -> access_token.'&type=jsapi';
$ticket = json_decode(os_get($jturl));
return $ticket->ticket;
}