使用PHP實現查找附近的人

https://zhuanlan.zhihu.com/p/31380780php

 

LBS(基於位置的服務)

查找附近的人有個更大的專有名詞叫作LBS(基於位置的服務),LBS是指是指經過電信移動運營商的無線電通信網絡或外部定位方式,獲取移動終端用戶的位置信息,在GIS平臺的支持下,爲用戶提供相應服務的一種增值業務。所以首先得獲取用戶的位置,獲取用戶的位置有基於GPS、基於運營商基站、WIFI等方式,通常由客戶端獲取用戶位置的經緯度座標上傳至應用服務器,應用服務器對用戶座標進行保存,客戶端獲取附近的人數據的時候,應用服務器基於請求人的地理位置配合必定的條件(距離,性別,活躍時間等)去數據庫進行篩選和排序。html

 

根據經緯度如何得出兩點之間的距離?

咱們都知道平面座標內的兩點座標可使用平面座標距離公式來計算,但經緯度是利用三度空間的球面來定義地球上的空間的球面座標系統,假定地球是正球體,關於球面距離計算公式以下:mysql

d(x1,y1,x2,y2)=r*arccos(sin(x1)*sin(x2)+cos(x1)*cos(x2)*cos(y1-y2))

具體推斷過程有興趣的推薦這篇文章:根據經緯度計算地面兩點間的距離-數學公式及推導git

PHP函數代碼以下:github

/**
     * 根據兩點間的經緯度計算距離
     * @param $lat1
     * @param $lng1
     * @param $lat2
     * @param $lng2
     * @return float
     */
    public static function getDistance($lat1, $lng1, $lat2, $lng2){
        $earthRadius = 6367000; //approximate radius of earth in meters
        $lat1 = ($lat1 * pi() ) / 180;
        $lng1 = ($lng1 * pi() ) / 180;
        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180;
        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;
        return round($calculatedDistance);
    }

MySQL代碼以下:redis

SELECT id, ( 3959 * acos ( cos ( radians(78.3232) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(65.3234) ) + sin ( radians(78.3232) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 30 ORDER BY distance LIMIT 0 , 20; 

除了上面經過計算球面距離公式來獲取,咱們可使用某些數據庫服務獲得,好比Redis和MongoDB:sql

 

Redis 3.2提供GEO地理位置功能,不只能夠獲取兩個位置之間的距離,獲取指定位置範圍內的地理信息位置集合也很簡單。Redis命令文檔mongodb

1.增長地理位置數據庫

GEOADD key longitude latitude member [longitude latitude member ...]

2.獲取地理位置bash

GEOPOS key member [member ...]

3.獲取兩個地理位置的距離

GEODIST key member1 member2 [unit]

4.獲取指定經緯度的地理信息位置集合

GEORADIUS key longitude latitude radius m|km|ft|mi [WITHCOORD] [WITHDIST] [WITHHASH] [COUNT count] [ASC|DESC] [STORE key] [STOREDIST key]

5.獲取指定成員的地理信息位置集合

GEORADIUSBYMEMBER key member radius m|km|ft|mi [WITHCOORD] [WITHDIST] [WITHHASH] [COUNT count] [ASC|DESC] [STORE key] [STOREDIST key]

 

MongoDB專門針對這種查詢創建了地理空間索引。 2d和2dsphere索引,分別是針對平面和球面。 MongoDB文檔

1.添加數據

db.location.insert( {uin : 1 , loc : { lon : 50 , lat : 50 } } )

2.創建索引

db.location.ensureIndex( { loc : "2d" } )

3.查找附近的點

db.location.find( { loc :{ $near : [50, 50] } )

4.最大距離和限制條數

db.location.find( { loc : { $near : [50, 50] , $maxDistance : 5 } } ).limit(20)

5.使用geoNear在查詢結果中返回每一個點距離查詢點的距離

db.runCommand( { geoNear : "location" , near : [ 50 , 50 ], num : 10, query : { type : "museum" } } )

6.使用geoNear附帶查詢條件和返回條數,geoNear使用runCommand命令不支持find查詢中分頁相關limit和skip參數的功能

db.runCommand( { geoNear : "location" , near : [ 50 , 50 ], num : 10, query : { uin : 1 } })

 

PHP多種方式和具體實現

1.基於MySql

成員添加方法:

public function geoAdd($uin, $lon, $lat)
{
    $pdo = $this->getPdo();
    $sql = 'INSERT INTO `markers`(`uin`, `lon`, `lat`) VALUES (?, ?, ?)';
    $stmt = $pdo->prepare($sql);
    return $stmt->execute(array($uin, $lon, $lat));
}

查詢附近的人(支持查詢條件和分頁):

public function geoNearFind($lon, $lat, $maxDistance = 0, $where = array(), $page = 0)
{
    $pdo = $this->getPdo();
    $sql = "SELECT  
              id, (  
                3959 * acos (  
                  cos ( radians(:lat) )  
                  * cos( radians( lat ) )  
                  * cos( radians( lon ) - radians(:lon) )  
                  + sin ( radians(:lat) )  
                  * sin( radians( lat ) )  
                )  
              ) AS distance  
            FROM markers";

    $input[':lat'] = $lat;
    $input[':lon'] = $lon;

    if ($where) {
        $sqlWhere = ' WHERE ';
        foreach ($where as $key => $value) {
            $sqlWhere .= "`{$key}` = :{$key} ,";
            $input[":{$key}"] = $value;
        }
        $sql .= rtrim($sqlWhere, ',');
    }

    if ($maxDistance) {
        $sqlHaving = " HAVING distance < :maxDistance"; $sql .= $sqlHaving; $input[':maxDistance'] = $maxDistance; } $sql .= ' ORDER BY distance'; if ($page) { $page > 1 ? $offset = ($page - 1) * $this->pageCount : $offset = 0; $sqlLimit = " LIMIT {$offset} , {$this->pageCount}"; $sql .= $sqlLimit; } $stmt = $pdo->prepare($sql); $stmt->execute($input); $list = $stmt->fetchAll(PDO::FETCH_ASSOC); return $list; }

 

2.基於Redis(3.2以上)

PHP使用Redis能夠安裝redis擴展或者經過composer安裝predis類庫,本文使用redis擴展來實現。

成員添加方法:

public function geoAdd($uin, $lon, $lat)
{
    $redis = $this->getRedis();
    $redis->geoAdd('markers', $lon, $lat, $uin);
    return true;
}

查詢附近的人(不支持查詢條件和分頁):

public function geoNearFind($uin, $maxDistance = 0, $unit = 'km')
{
    $redis = $this->getRedis();
    $options = ['WITHDIST']; //顯示距離
    $list = $redis->geoRadiusByMember('markers', $uin, $maxDistance, $unit, $options);
    return $list;
}

 

3.基於MongoDB

PHP使用MongoDB的擴展有mongo(文檔)和mongodb(文檔),二者寫法差異很大,選擇好擴展須要對應相應的文檔查看,因爲mongodb擴展是新版,本文選擇mongodb擴展。

假設咱們建立db庫和location集合

設置索引:

db.getCollection('location').ensureIndex({"uin":1},{"unique":true}) db.getCollection('location').ensureIndex({loc:"2d"}) #若查詢位置附帶查詢,能夠將常查詢條件添加至組合索引 #db.getCollection('location').ensureIndex({loc:"2d",uin:1})

成員添加方法:

public function geoAdd($uin, $lon, $lat)
{
    $document = array(
        'uin' => $uin,
        'loc' => array(
            'lon' =>  $lon,
            'lat' =>  $lat,
        ),
    );

    $bulk = new MongoDB\Driver\BulkWrite;
    $bulk->update(
        ['uin' => $uin],
        $document,
        [ 'upsert' => true]
    );
    //出現noreply 能夠改爲確認式寫入
    $manager = $this->getMongoManager();
    $writeConcern = new MongoDB\Driver\WriteConcern(1, 100);
    //$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 100);
    $result = $manager->executeBulkWrite('db.location', $bulk, $writeConcern);

    if ($result->getWriteErrors()) {
        return false;
    }
    return true;
}

查詢附近的人(返回結果沒有距離,支持查詢條件,支持分頁)

public function geoNearFind($lon, $lat, $maxDistance = 0, $where = array(), $page = 0)
{
    $filter = array(
        'loc' => array(
            '$near' => array($lon, $lat),
        ),
    );
    if ($maxDistance) {
        $filter['loc']['$maxDistance'] = $maxDistance;
    }
    if ($where) {
        $filter = array_merge($filter, $where);
    }
    $options = array();
    if ($page) {
        $page > 1 ? $skip = ($page - 1) * $this->pageCount : $skip = 0;
        $options = [
            'limit' => $this->pageCount,
            'skip' => $skip
        ];
    }

    $query = new MongoDB\Driver\Query($filter, $options);
    $manager = $this->getMongoManager();
    $cursor = $manager->executeQuery('db.location', $query);
    $list = $cursor->toArray();
    return $list;
}

查詢附近的人(返回結果帶距離,支持查詢條件,支付返回數量,不支持分頁):

public function geoNearFindReturnDistance($lon, $lat, $maxDistance = 0, $where = array(), $num = 0)
{
    $params = array(
        'geoNear' => "location",
        'near' => array($lon, $lat),
        'spherical' => true, // spherical設爲false(默認),dis的單位與座標的單位保持一致,spherical設爲true,dis的單位是弧度
        'distanceMultiplier' => 6371, // 計算成千米,座標單位distanceMultiplier: 111。 弧度單位 distanceMultiplier: 6371
    );

    if ($maxDistance) {
        $params['maxDistance'] = $maxDistance;
    }
    if ($num) {
        $params['num'] = $num;
    }
    if ($where) {
        $params['query'] = $where;
    }

    $command = new MongoDB\Driver\Command($params);
    $manager = $this->getMongoManager();
    $cursor = $manager->executeCommand('db', $command);
    $response = (array) $cursor->toArray()[0];
    $list = $response['results'];
    return $list;
}

注意事項:

1.選擇好擴展,mongo和mongodb擴展寫法差異很大

2.寫數據時出現noreply請檢查寫入確認級別

3.使用find查詢的數據須要本身計算距離,使用geoNear查詢的不支持分頁

4.使用geoNear查詢的距離須要轉化成km使用spherical和distanceMultiplier參數

 

上述demo能夠戳這裏:demo

 

總結

以上介紹了三種方式去實現查詢附近的人的功能,各類方式都有各自的適用場景,好比數據行比較少,例如查詢用戶和幾座城市之間的距離使用Mysql就足夠了,若是須要實時快速響應而且普通查找範圍內的距離,可使用Redis,但若是數據量大而且多種屬性篩選條件,使用mongo會更方便,以上只是建議,具體實現方案還要視具體業務去進行方案評審。

相關文章
相關標籤/搜索