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:
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 = 'INSERT INTO `markers`(`uin`, `lon`, `lat`) VALUES (?, ?, ?)'; $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[':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. 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('markers', $lon, $lat, $uin); return true; }
Query nearby people (query conditions and paging are not supported):
public function geoNearFind($uin, $maxDistance = 0, $unit = 'km') { $redis = $this->getRedis(); $options = ['WITHDIST']; //显示距离 $list = $redis->geoRadiusByMember('markers', $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('location').ensureIndex({"uin":1},{"unique":true}) db.getCollection('location').ensureIndex({loc:"2d"}) #若查询位置附带查询,可以将常查询条件添加至组合索引 #db.getCollection('location').ensureIndex({loc:"2d",uin:1})
Member addition method:
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; }
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( '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; }
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( '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; }
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
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!