Home > Backend Development > PHP Tutorial > Teach you how to use PHP to find the people nearby you want

Teach you how to use PHP to find the people nearby you want

藏色散人
Release: 2023-04-09 16:00:01
forward
4632 people have browsed it

Recently there was a business scenario that used to find nearby people, so I checked the relevant information and reviewed the use of PHP to implement related functions. A technical summary of various methods and specific implementations. Comments and corrections are welcome. Now let’s get to the point:

LBS (Location-Based Services)

Finding nearby people has a larger term called LBS (location-based service). LBS refers to obtaining the location information of mobile terminal users through the radio communication network of telecommunications mobile operators or external positioning methods. With the support of GIS platform, it is a value-added service that provides users with corresponding services. Therefore, the user's location must be obtained first. The user's location can be obtained through GPS, operator base station, WIFI, etc. Generally, the client obtains the longitude and latitude coordinates of the user's location and uploads them to the application server. The application server saves the user coordinates, and the client When obtaining nearby people's data, the application server goes to the database to filter and sort based on the geographical location of the requester and certain conditions (distance, gender, active time, etc.).

How to find the distance between two points based on longitude and latitude?

We all know that the coordinates of two points in plane coordinates can be calculated using the plane coordinate distance formula, but longitude and latitude are spherical coordinate systems that use the spherical surface of three-dimensional space to define the space on the earth. Assume that the earth It is a right sphere. The formula for calculating the spherical distance is as follows:

Teach you how to use PHP to find the people nearby you want

If you are interested in the specific inference process, I recommend this article: [Mathematical formula and derivation] Calculate the distance between the ground and the ground based on the longitude and latitude The distance between points

PHP function code is as follows:

/**
     * 根据两点间的经纬度计算距离
     * @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);
    }
Copy after login

MySQL code is as follows:

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;
Copy after login

In addition to the above calculation of spherical distance formula, we can use a certain Some database services are available, such as Redis and MongoDB:

Redis 3.2 provides GEO geographical location function, which can not only obtain the distance between two locations, but also obtain the geographical information location collection within the specified location range. Redis Command Document

1. Add geographical location

GEOADD key longitude latitude member [longitude latitude member ...]
Copy after login

2. Get geographical location

GEOPOS key member [member ...]
Copy after login

3. Get the distance between two geographical locations

GEODIST key member1 member2 [unit]
Copy after login

4. Get the geographic information location collection of the specified longitude and latitude

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

5. Get the geographic information location collection of the specified member

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

MongoDB has established a geospatial index specifically for this kind of query . 2d and 2dsphere indexes are for planes and spheres respectively. MongoDB Document

1. Add data

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

2. Create index

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

3. Find nearby points

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

4 .Maximum distance and limited number of items

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

5. Use geoNear to return the distance between each point and the query point in the query result

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

6. Use geoNear with query conditions and the number of returned items, geoNear does not support the paging-related limit and skip parameters in the find query when using the runCommand command

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

PHP multiple methods and specific implementation

1. Based on MySql

Member addition method:

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

Query nearby people (supports query conditions and paging):

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[&#39;:lat&#39;] = $lat;
    $input[&#39;:lon&#39;] = $lon;

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

    if ($maxDistance) {
        $sqlHaving = " HAVING distance < :maxDistance";
        $sql .= $sqlHaving;
        $input[&#39;:maxDistance&#39;] = $maxDistance;
    }

    $sql .= &#39; ORDER BY distance&#39;;

    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;
}
Copy after login

2. Based on Redis (3.2 or above)

PHP uses Redis You can install the redis extension or install the predis class library through composer. This article uses the redis extension to implement it.

Member adding method:

public function geoAdd($uin, $lon, $lat)
{
    $redis = $this->getRedis();
    $redis->geoAdd(&#39;markers&#39;, $lon, $lat, $uin);
    return true;
}
Copy after login

Query nearby people (query conditions and paging are not supported):

public function geoNearFind($uin, $maxDistance = 0, $unit = &#39;km&#39;)
{
    $redis = $this->getRedis();
    $options = [&#39;WITHDIST&#39;]; //显示距离
    $list = $redis->geoRadiusByMember(&#39;markers&#39;, $uin, $maxDistance, $unit, $options);
    return $list;
}
Copy after login

3. Based on MongoDB

PHP uses MongoDB The extensions include mongo(Documentation) and mongodb(Documentation). The writing methods of the two are very different. Choosing a good extension requires corresponding Check the documentation. Since the mongodb extension is a new version, this article selects the mongodb extension.

Suppose we create the db library and location collection

Set the index:

db.getCollection(&#39;location&#39;).ensureIndex({"uin":1},{"unique":true}) 
db.getCollection(&#39;location&#39;).ensureIndex({loc:"2d"})
#若查询位置附带查询,可以将常查询条件添加至组合索引
#db.getCollection(&#39;location&#39;).ensureIndex({loc:"2d",uin:1})
Copy after login

Member addition method:

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

    $bulk = new MongoDB\Driver\BulkWrite;
    $bulk->update(
        [&#39;uin&#39; => $uin],
        $document,
        [ &#39;upsert&#39; => 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(&#39;db.location&#39;, $bulk, $writeConcern);

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

Query nearby people (return results without distance , supports query conditions, supports paging)

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

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

Query nearby people (return results with distance, supports query conditions, payment return quantity, does not support paging):

public function geoNearFindReturnDistance($lon, $lat, $maxDistance = 0, $where = array(), $num = 0)
{
    $params = array(
        &#39;geoNear&#39; => "location",
        &#39;near&#39; => array($lon, $lat),
        &#39;spherical&#39; => true, // spherical设为false(默认),dis的单位与坐标的单位保持一致,spherical设为true,dis的单位是弧度
        &#39;distanceMultiplier&#39; => 6371, // 计算成公里,坐标单位distanceMultiplier: 111。 弧度单位 distanceMultiplier: 6371
    );

    if ($maxDistance) {
        $params[&#39;maxDistance&#39;] = $maxDistance;
    }
    if ($num) {
        $params[&#39;num&#39;] = $num;
    }
    if ($where) {
        $params[&#39;query&#39;] = $where;
    }

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

Notes:

1. Choose a good extension. The writing methods of mongo and mongodb extensions are very different

2. If noreply appears when writing data, please check the write confirmation level

3. The data queried using find needs to calculate the distance yourself, and the data queried using geoNear does not support paging

4. Use The distance queried by geoNear needs to be converted into km using the spherical and distanceMultiplier parameters

The above demo can be clicked here: demo

Summary

The above three types are introduced Methods to implement the function of querying nearby people. Each method has its own applicable scenarios. For example, there are relatively few data rows. For example, Mysql is enough to query the distance between a user and several cities. If you need to respond quickly in real time and generally To find the distance within the range, you can use Redis, but if the amount of data is large and there are multiple attribute filtering conditions, it will be more convenient to use mongo. The above are just suggestions. The specific implementation plan must be reviewed according to the specific business.

The above is the detailed content of Teach you how to use PHP to find the people nearby you want. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template