Home > Backend Development > PHP Tutorial > PHP geolocation search and calculate distance

PHP geolocation search and calculate distance

墨辰丷
Release: 2023-03-29 19:46:02
Original
2237 people have browsed it

This article mainly introduces PHP geographical location search and distance calculation. Friends who are interested can refer to it. I hope it will be helpful to everyone.

Geographical location search
LBS stores the latitude and longitude coordinates of each location, searches for nearby locations, and establishes a geographical location index to improve query efficiency.
Mongodb geographical location index, 2d and 2dsphere, corresponding to plane and sphere.

1. Create the coordinates of the storage location of the lbs collection


use lbs; 
 
db.lbs.insert( 
  { 
    loc:{ 
      type: "Point", 
      coordinates: [113.332264, 23.156206] 
    }, 
    name: "广州东站" 
  } 
) 
 
db.lbs.insert( 
  { 
    loc:{ 
      type: "Point", 
      coordinates: [113.330611, 23.147234] 
    }, 
    name: "林和西" 
  } 
) 
 
db.lbs.insert( 
  { 
    loc:{ 
      type: "Point", 
      coordinates: [113.328095, 23.165376] 
    }, 
    name: "天平架" 
  } 
)
Copy after login


2. Create a geographical location index


db.lbs.ensureIndex( 
  { 
    loc: "2dsphere" 
  } 
)
Copy after login


3. Query nearby coordinates
The current location is: Times Square,
Coordinates:


113.323568, 23.146436
Copy after login


Search for points within one kilometer nearby, sort from nearest to far


db.lbs.find( 
  { 
    loc: { 
      $near:{ 
        $geometry:{ 
          type: "Point", 
          coordinates: [113.323568, 23.146436] 
        }, 
        $maxDistance: 1000 
      } 
    } 
  } 
)
Copy after login


Search results:

The code is as follows:


{ "_id" : ObjectId("556a651996f1ac2add8928fa"), "loc" : { "type " : "Point", "coordinates" : [ 113.330611, 23.147234 ] }, "name" : "Lin Hexi" }


##The php code is as follows:


<?php 
// 连接mongodb 
function conn($dbhost, $dbname, $dbuser, $dbpasswd){ 
  $server = &#39;mongodb://&#39;.$dbuser.&#39;:&#39;.$dbpasswd.&#39;@&#39;.$dbhost.&#39;/&#39;.$dbname; 
  try{ 
    $conn = new MongoClient($server); 
    $db = $conn->selectDB($dbname); 
  } catch (MongoException $e){ 
    throw new ErrorException(&#39;Unable to connect to db server. Error:&#39; . $e->getMessage(), 31); 
  } 
  return $db; 
} 
 
// 插入坐标到mongodb 
function add($dbconn, $tablename, $longitude, $latitude, $name){ 
  $index = array(&#39;loc&#39;=>&#39;2dsphere&#39;); 
  $data = array( 
      &#39;loc&#39; => array( 
          &#39;type&#39; => &#39;Point&#39;, 
          &#39;coordinates&#39; => array(doubleval($longitude), doubleval($latitude)) 
      ), 
      &#39;name&#39; => $name 
  ); 
  $coll = $dbconn->selectCollection($tablename); 
  $coll->ensureIndex($index); 
  $result = $coll->insert($data, array(&#39;w&#39; => true)); 
  return (isset($result[&#39;ok&#39;]) && !empty($result[&#39;ok&#39;])) ? true : false; 
} 
 
// 搜寻附近的坐标 
function query($dbconn, $tablename, $longitude, $latitude, $maxdistance, $limit=10){ 
  $param = array( 
    &#39;loc&#39; => array( 
      &#39;$nearSphere&#39; => array( 
        &#39;$geometry&#39; => array( 
          &#39;type&#39; => &#39;Point&#39;, 
          &#39;coordinates&#39; => array(doubleval($longitude), doubleval($latitude)),  
        ), 
        &#39;$maxDistance&#39; => $maxdistance*1000 
      ) 
    ) 
  ); 
 
  $coll = $dbconn->selectCollection($tablename); 
  $cursor = $coll->find($param); 
  $cursor = $cursor->limit($limit); 
   
  $result = array(); 
  foreach($cursor as $v){ 
    $result[] = $v; 
  }  
 
  return $result; 
} 
 
$db = conn(&#39;localhost&#39;,&#39;lbs&#39;,&#39;root&#39;,&#39;123456&#39;); 
 
// 随机插入100条坐标纪录 
for($i=0; $i<100; $i++){ 
  $longitude = &#39;113.3&#39;.mt_rand(10000, 99999); 
  $latitude = &#39;23.15&#39;.mt_rand(1000, 9999); 
  $name = &#39;name&#39;.mt_rand(10000,99999); 
  add($db, &#39;lbs&#39;, $longitude, $latitude, $name); 
} 
 
// 搜寻一公里内的点 
$longitude = 113.323568; 
$latitude = 23.146436; 
$maxdistance = 1; 
$result = query($db, &#39;lbs&#39;, $longitude, $latitude, $maxdistance); 
print_r($result); 
?>
Copy after login


To demonstrate the php code, you first need to create a user and execute auth in the lbs of mongodb. The method is as follows:



use lbs; 
db.createUser( 
  { 
    "user":"root", 
    "pwd":"123456", 
    "roles":[] 
  } 
) 
 
db.auth( 
  { 
    "user":"root", 
    "pwd":"123456" 
  } 
)
Copy after login



Calculate the distance between two geographical coordinates
Function: Calculate the spherical distance between two points based on the pi ratio, the earth's radius coefficient and the longitude and latitude of the two point coordinates.

Get the coordinate distance between two points:


<?php
/**
 * 计算两点地理坐标之间的距离
 * @param Decimal $longitude1 起点经度
 * @param Decimal $latitude1 起点纬度
 * @param Decimal $longitude2 终点经度 
 * @param Decimal $latitude2 终点纬度
 * @param Int   $unit    单位 1:米 2:公里
 * @param Int   $decimal  精度 保留小数位数
 * @return Decimal
 */
function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit=2, $decimal=2){

  $EARTH_RADIUS = 6370.996; // 地球半径系数
  $PI = 3.1415926;

  $radLat1 = $latitude1 * $PI / 180.0;
  $radLat2 = $latitude2 * $PI / 180.0;

  $radLng1 = $longitude1 * $PI / 180.0;
  $radLng2 = $longitude2 * $PI /180.0;

  $a = $radLat1 - $radLat2;
  $b = $radLng1 - $radLng2;

  $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
  $distance = $distance * $EARTH_RADIUS * 1000;

  if($unit==2){
    $distance = $distance / 1000;
  }

  return round($distance, $decimal);

}

// 起点坐标
$longitude1 = 113.330405;
$latitude1 = 23.147255;

// 终点坐标
$longitude2 = 113.314271;
$latitude2 = 23.1323;

$distance = getDistance($longitude1, $latitude1, $longitude2, $latitude2, 1);
echo $distance.&#39;m&#39;; // 2342.38m

$distance = getDistance($longitude1, $latitude1, $longitude2, $latitude2, 2);
echo $distance.&#39;km&#39;; // 2.34km

?>
Copy after login




Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

php How to use curl to simulate logging into Renren.com

A simple way to implement process control switch in php

##Summary of methods for generating short URLs in PHP


##

The above is the detailed content of PHP geolocation search and calculate distance. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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