微信獲取用戶地理位置,官網上文檔不太完善,仍是附上php
微信獲取用戶地理位置開發文檔地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp142114084git
總的來講分爲兩大部分ajax
1,生成JS-SDK權限驗證簽名sql
2,使用地理位置接口獲取座標json
完整類文件代碼以下:api
<?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>
靜態頁下完整代碼以下app
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
結果如圖
而後把返回的數據傳遞到靜態頁面便可