Table of Contents
Summary
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

Oct 22, 2020 am 11:49 AM
php

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!

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles