微信获取用户地理位置,官网上文档不太完善,还是附上
微信获取用户地理位置开发文档地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp142114084
总的来说分为两大部分
1,生成JS-SDK权限验证签名
2,使用地理位置接口获取坐标
完整类文件代码如下:
<?php class JSSDK { private $appId; private $appSecret; public function __construct($appId, $appSecret) { $this->appId = $appId; $this->appSecret = $appSecret; } public function getSignPackage() { $jsapiTicket = $this->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 = $this->createNonceStr(); // 这里参数的顺序要按照 key 值 ASCII 码升序排序 $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url"; $signature = sha1($string); $signPackage = array( "appId" => $this->appId, "nonceStr" => $nonceStr, "timestamp" => $timestamp, "url" => $url, "signature" => $signature, "rawString" => $string ); return $signPackage; } private function createNonceStr($length = 16) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $str = ""; for ($i = 0; $i < $length; $i++) { $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); } return $str; } private function getJsApiTicket() { // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例 $data = json_decode(file_get_contents("jsapi_ticket.json")); if ($data->expire_time < time()) { $accessToken = $this->getAccessToken(); // 如果是企业号用以下 URL 获取 ticket // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken"; $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken"; $res = json_decode($this->httpGet($url)); $ticket = $res->ticket; if ($ticket) { $data->expire_time = time() + 7000; $data->jsapi_ticket = $ticket; $fp = fopen("jsapi_ticket.json", "w"); fwrite($fp, json_encode($data)); fclose($fp); } } else { $ticket = $data->jsapi_ticket; } return $ticket; } private function getAccessToken() { // access_token 应该全局存储与更新,以下代码以写入到文件中做示例 $data = json_decode(file_get_contents("access_token.json")); if ($data->expire_time < time()) { // 如果是企业号用以下URL获取access_token // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret"; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret"; $res = json_decode($this->httpGet($url)); $access_token = $res->access_token; if ($access_token) { $data->expire_time = time() + 7000; $data->access_token = $access_token; $fp = fopen("access_token.json", "w"); fwrite($fp, json_encode($data)); fclose($fp); } } else { $access_token = $data->access_token; } return $access_token; } private function httpGet($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 500); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_URL, $url); $res = curl_exec($curl); curl_close($curl); return $res; } }
第二,检查你的微信公众号js接口安全域名是否填写
获取签名包
<?php require_once "jssdk.php"; $jssdk = new JSSDK("yourAppID", "yourAppSecret"); $signPackage = $jssdk->GetSignPackage(); ?>
引入js文件
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
静态页下完整代码如下
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: [ // 所有要调用的 API 都要加到这个列表中 ‘checkJsApi‘, ‘openLocation‘, ‘getLocation‘ ] }); wx.ready(function () { wx.checkJsApi({ jsApiList: [ ‘getLocation‘ ], success: function (res) { // alert(JSON.stringify(res)); // alert(JSON.stringify(res.checkResult.getLocation)); 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; // 位置精度 }, cancel: function (res) { alert(‘用户拒绝授权获取地理位置‘); } }); });
这样就会弹出授权框,获取你的地理位置,点击确定就能得到当前位置的经纬度
根据经纬度获取附近商家列表,用ajax请求
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; // 位置精度 // alert(latitude); //ajax请求服务器 var postData={lat:latitude}; postData.lng=longitude; console.log(postData); $.post(‘?m=plugin&p=wap&cn=index&id=food:sit:shop_list‘,postData,function(re){ if(re.error==0) { $(re.msg).each(function(index,el){ $("#list").append(‘<div class="mui-content"><div class="mui-card"><ul class="mui-table-view"><li class="mui-table-view-cell"><a href="#"><span class="mui-badge mui-badge-success" style="top: 25%;">‘+el.distance/1000+‘km</span>‘+el.telphone+‘<br /><span class="mui-ellipsis-2">‘+el.title+‘</span></a></li></ul></div></div>‘); }); }else { console.log(re.msg); } },‘json‘); }, cancel: function (res) { alert(‘用户拒绝授权获取地理位置‘); } });
现在关键的问题是如何根据用户返回的经纬度获取与商家之间的距离,sql语句的构建
例如我的坐标是:30.664385188806,104.07559730274
表名:merchants
表字段:itemid,title,hits,lat,lng lat是经度 lat是纬度
以下SQL语句是全部查询并运算出坐标的的语句
select itemid,title,hits,telephone,ROUND(6378.138*2*ASIN(SQRT(POW(SIN((30.664385188806*PI()/180-lat*PI()/180)/2),2)+COS(30.664385188806*PI()/180)*COS(lat*PI()/180)*POW(SIN((104.07559730274*PI()/180-lng*PI()/180)/2),2)))*1000) AS distance from merchants order by distance
通过如下方式的SQL运行就可查询出相应的距离+排序+多少公里范围的条件检索 如:下面的检索出5公里范围的语句
select * from (select itemid,title,hits,telephone, ROUND(6378.138*2*ASIN(SQRT(POW(SIN((30.664385188806*PI()/180-lat*PI()/180)/2),2)+COS(30.664385188806*PI()/180)*COS(lat*PI()/180)*POW(SIN((104.07559730274*PI()/180-lng*PI()/180)/2),2)))*1000) AS distance from merchants order by distance ) as a where a.distance<=5000
结果如图
然后把返回的数据传递到静态页面即可