手把手教你如何實現查看附近的人
今天分享的教程是教你如何實現附近的人或者其他內容。服務器端用的php。 使用前提請確認你的用戶數據表中是否有存儲用戶的***坐標和更新時間,***單獨建一張表來存儲用戶的***坐標和更新時間。
在獲取附近的人之前首先要獲取自己的坐標。可以使用baiduLocation來獲取當前用戶的坐標,然后用當前坐標請求服務器返回按照距離排序的用戶數據。
- apiready = function() {
- var baiduLocation = api.require('baiduLocation');
- baiduLocation.startLocation({
- accuracy: '100m',
- filter:1,
- autoStop: true
- }, function(ret, err){
- var sta = ret.status;
- var lat = ret.latitude;
- var lon = ret.longitude;
- if(sta){
- //成功獲取
- }else{
- //獲取失敗
- }
- });
- };
//獲取位置成功后,開發向服務器發送請求
- api.ajax({
- url: 請求地址,
- method: 'post',
- timeout: 30,
- dataType: 'json',
- returnAll:false,
- data:{
- values: {lat: lat,lon:lon}
- }
- },function(ret,err){
- if (ret) {
- var urlJson = JSON.stringify(ret);
- api.alert({msg: urlJson});
- }else {
- api.alert({
- msg'錯誤碼:'+err.code+';錯誤信息:'+err.msg+'網絡狀態碼:'+err.statusCode)
- });
- };
- });
其實在APP端代碼非常簡單,主要就是獲取坐標然后發送到服務器,然后服務器根據傳過來的坐標來計算距離,按照距離排序返回數據。那么重點就是服務器端如何實現了
服務器端就以php為例來講一下, 首先獲取有坐標用戶的數據,這個就是foreach一下了,然后根據傳過來的坐標計算距離,下面是foreach里面的一段代碼
- 假設 用戶數據為 $data;
- //foreach之前先組裝下post過來的坐標
- $lat = $_POST['lat'];
- $lon = $_POST['lon'];
- $myLocation = $lon.','.$lat;
- foreach($data as $key=>$v){
- //E:對方用戶坐標為: 104.077638,30.673573
- $v['position'] = "104.077638,30.673573";
- $newData[$key]['distance] = distanceBetween($myLocation,$v['position']);
- .......
- //其他用戶數據
- }
然后再foreach一下新數組根據距離來排序
- foreach ($newData as $key => $r) {
- $distance[] = $r['distance'];
- }
- array_multisort($distance, SORT_ASC, $newData);
- 輸出JSON數組
- echo json_encode($newData);
注:上面foreach里面有個自定義函數distanceBetween();
這個是用來計算兩個坐標的距離的,代碼如下:
- /**
- * 計算兩個坐標之間的距離(米)
- * @param float $fP1Lat 起點(緯度)
- * @param float $fP1Lon 起點(經度)
- * @param float $fP2Lat 終點(緯度)
- * @param float $fP2Lon 終點(經度)
- * @return int
- */
- function distanceBetween($mylonlat, $findlonlat){
- $mylonlat = explode(',', $mylonlat);
- $findlonlat = explode(',', $findlonlat);
- list($lng1,$lat1) = $mylonlat;
- list($lng2,$lat2) = $findlonlat;
- $EARTH_RADIUS=6378.137;
- $PI=3.1415926;
- $radLat1 = $lat1 * $PI / 180.0;
- $radLat2 = $lat2 * $PI / 180.0;
- $a = $radLat1 - $radLat2;
- $b = ($lng1 * $PI / 180.0) - ($lng2 * $PI / 180.0);
- $s = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
- $s = $s * $EARTH_RADIUS;
- $s = round($s * 1000);
- if ($len_type > 1) {
- $s /= 1000;
- }
- $distance = round($s/1000,2);
- return $distance;
- }