废话不多说,直接上代码和解说方法:
1、ajax解析坐标和构造微信config接口注入权限验证配置
public function doMobileGetAddrAjax(){
global $_W, $_GPC;
$durl = 'http://apis.map.qq.com/ws/geocoder/v1/?location='
.$_GPC['lat'].','.$_GPC['lng'].'&key=请填写你申请的KEY值&get_poi=1';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $durl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
$r = curl_exec($ch);
curl_close($ch);
$addr = json_decode($r);
$addr=$this->object_array($addr);
echo $addr['result']['address'];exit; //输出地址到模版
}
private function object_array($array)
{
if(is_object($array))
{
$array = (array)$array;
}
if(is_array($array))
{
foreach($array as $key=>$value)
{
$array[$key] = $this->object_array($value);
}
}
return $array;
}
private function createNonceStr($length = 16) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for ($i = 0; $i
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
//构造微信配置信息,看不懂的去看微信开发文档里的“微信JS-SDK说明文档”
private function getJssdkConfig(){
global $_W;
$jsapiTicket = $_W['account']['jsapi_ticket']['ticket'];
$nonceStr = $this->createNonceStr();
$timestamp = TIMESTAMP;
$url = $_W['siteurl'];
$string1 = "jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}×tamp={$timestamp}&url={$url}";
$signature = sha1($string1);
$config = array(
"appId"=> $_W['account']['key'],
"nonceStr"=> $nonceStr,
"timestamp" => "$timestamp",
"signature" => $signature,
);
return $config;
}
/*然后在指定的方法里赋值到模版*/
$signPackage = $this->getJssdkConfig();
2、在模版文件获取微信地址和使用ajax请求解析坐标
wx.config({
debug: false,
appId: '<?php echo $signPackage["appId"];?>',
timestamp: '<?php echo $signPackage["timestamp"];?>',
nonceStr: '<?php echo $signPackage["nonceStr"];?>',
signature: '<?php echo $signPackage["signature"];?>',
jsApiList: [
'checkJsApi',
'openLocation',
'getLocation'
]
});
wx.ready(function () {
wx.checkJsApi({
jsApiList: ['getLocation'],
success: function(res) {
if (res.checkResult.getLocation == false) {
alert('你的微信版本太低,不支持微信JS接口,请升级到最新的微信版本!');
return;
}
}
});
wx.getLocation({
success: function(res) {
var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
var speed = res.speed; // 速度,以米/每秒计
var accuracy = res.accuracy; // 位置精度
/*逆地理编码 获取地址位置名称*/
$.ajax({
type: "post",
url: "{php echo $this->createMobileUrl('GetAddrAjax');}",
data: {"lng": longitude,"lat": latitude},
dataType: "text",
success: function(data) {
if (data != null) {
$("#address").val(data); //自动赋值id为address的文本框
}
}
});
},
cancel: function (res) {
alert('用户拒绝授权获取地理位置');
}
});
});
3、易错地方:本人在调试的时候发现cofig的debug打开为true,但是在微信端老是没反应,后来经过一天的研究,得到了血的教训,是因为jweixin-1.0.0.js里的require、define和模版里的require、define冲突,故在引入jweixin-1.0.0.js前重新定义require、define即可。
var define = null;
var require = null;