search
HomeBackend DevelopmentPHP TutorialTeach you how to use PHP to find the people nearby you want

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);
    }

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;

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 ...]

2. Get geographical location

GEOPOS key member [member ...]

3. Get the distance between two geographical locations

GEODIST key member1 member2 [unit]

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]

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]

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 } } )

2. Create index

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

3. Find nearby points

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

4 .Maximum distance and limited number of items

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

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" } } )

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 } })

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));
}

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;
}

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;
}

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;
}

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})

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;
}

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;
}

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;
}

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!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools