Home Backend Development PHP Tutorial PHP geolocation search and calculate distance

PHP geolocation search and calculate distance

Jun 05, 2018 pm 02:34 PM
php geographical location

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


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

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


1

2

3

4

5

db.lbs.ensureIndex(

  {

    loc: "2dsphere"

  }

)

Copy after login


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


1

113.323568, 23.146436

Copy after login


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


1

2

3

4

5

6

7

8

9

10

11

12

13

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:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

<?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:



1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

<?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!

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

Video Face Swap

Video Face Swap

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

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)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1225
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

See all articles