PHP实现搜索地理位置及计算两点地理位置间距离的实例

地理位置搜寻
LBS,存储每个地点的经纬度坐标,搜寻附近的地点,建立地理位置索引可提高查询效率。
mongodb地理位置索引,2d和2dsphere,对应平面和球面。

1.创建lbs集合存放地点坐标

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: "天平架"
  }
)

  2.创建地理位置索引

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

  3.查询附近的坐标
当前位置为:时代广场,
坐标:113.323568, 23.146436

搜寻附近一公里内的点,由近到远排序

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

搜寻结果:

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

  php代码如下:

<?php
// 连接mongodb
function conn($dbhost, $dbname, $dbuser, $dbpasswd){
  $server = ‘mongodb://‘.$dbuser.‘:‘.$dbpasswd.‘@‘.$dbhost.‘/‘.$dbname;
  try{
    $conn = new MongoClient($server);
    $db = $conn->selectDB($dbname);
  } catch (MongoException $e){
    throw new ErrorException(‘Unable to connect to db server. Error:‘ . $e->getMessage(), 31);
  }
  return $db;
} 

// 插入坐标到mongodb
function add($dbconn, $tablename, $longitude, $latitude, $name){
  $index = array(‘loc‘=>‘2dsphere‘);
  $data = array(
      ‘loc‘ => array(
          ‘type‘ => ‘Point‘,
          ‘coordinates‘ => array(doubleval($longitude), doubleval($latitude))
      ),
      ‘name‘ => $name
  );
  $coll = $dbconn->selectCollection($tablename);
  $coll->ensureIndex($index);
  $result = $coll->insert($data, array(‘w‘ => true));
  return (isset($result[‘ok‘]) && !empty($result[‘ok‘])) ? true : false;
} 

// 搜寻附近的坐标
function query($dbconn, $tablename, $longitude, $latitude, $maxdistance, $limit=10){
  $param = array(
    ‘loc‘ => array(
      ‘$nearSphere‘ => array(
        ‘$geometry‘ => array(
          ‘type‘ => ‘Point‘,
          ‘coordinates‘ => array(doubleval($longitude), doubleval($latitude)),
        ),
        ‘$maxDistance‘ => $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(‘localhost‘,‘lbs‘,‘root‘,‘123456‘); 

// 随机插入100条坐标纪录
for($i=0; $i<100; $i++){
  $longitude = ‘113.3‘.mt_rand(10000, 99999);
  $latitude = ‘23.15‘.mt_rand(1000, 9999);
  $name = ‘name‘.mt_rand(10000,99999);
  add($db, ‘lbs‘, $longitude, $latitude, $name);
} 

// 搜寻一公里内的点
$longitude = 113.323568;
$latitude = 23.146436;
$maxdistance = 1;
$result = query($db, ‘lbs‘, $longitude, $latitude, $maxdistance);
print_r($result);
?> 

演示php代码,首先需要在mongodb的lbs中创建用户和执行auth。方法如下:

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

db.auth(
  {
    "user":"root",
    "pwd":"123456"
  }
) 

计算两点地理坐标的距离
功能:根据圆周率和地球半径系数与两点坐标的经纬度,计算两点之间的球面距离。

获取两点坐标距离:

<?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.‘m‘; // 2342.38m

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

?>

原文地址:https://www.cnblogs.com/ouruola863/p/9205336.html

时间: 2024-07-30 15:55:12

PHP实现搜索地理位置及计算两点地理位置间距离的实例的相关文章

2D和3D空间中计算两点之间的距离

自己在做游戏的忘记了Unity帮我们提供计算两点之间的距离,在百度搜索了下. 原来有一个公式自己就写了一个方法O(∩_∩)O~,到僵尸到达某一个点之后就向另一个奔跑过去 /// <summary> /// 3维中如何计算两点之间的距离 /// </summary> /// <param name="p1"></param> /// <param name="p2"></param> /// &l

利用结构类型的相关知识计算两点之间的距离

#include<stdio.h>#include<stdlib.h>#include<math.h> struct point{ /*点的结构类型名*/ float x; /*横坐标*/ float y; /*纵坐标*/ }; struct point readPoint(); /*函数原型声明*/float distance(struct point p1,struct point p2);/*主函数*/ int main(void){ struct point a

openlayer3计算两点之间的距离

openlayer3计算两点之间的距离 对应的openlayers的版本为3.7. 主要用的接口是ol.Sphere.haversineDistance([x1,y1],[x2,y2]): 4326坐标系中计算两点距离的方式为: var wgs84Sphere = new ol.Sphere(6378137); wgs84Sphere.haversineDistance(C1,C2); 示例为: var wgs84Sphere = new ol.Sphere(6378137); wgs84Sph

使用友元函数计算两点之间的距离

#include <iostream> #include <cmath> using namespace std; class CPoint//点类 { private: double x;//横坐标 double y;//纵坐标 public: //使用初始化表初始化数据成员 CPoint(double xx=0,double yy=0):x(xx),y(yy){} //定义友元函数用于计算两点之间的距离 friend double Distance(CPoint &p1

sql server2008根据经纬度计算两点之间的距离

--通过经纬度计算两点之间的距离 create FUNCTION [dbo].[fnGetDistanceNew] --LatBegin 开始经度 --LngBegin 开始维度 --29.490295,106.486654,29.615467, 106.581515 (@LatBegin1 varchar(128), @LngBegin1 varchar(128),@location varchar(128)) Returns real AS BEGIN --转换location字段,防止字段

计算两点之间的距离,两点之间的斜率(角度)--秀清

// // ViewController.m // 勾股定理 // // Created by 张秀清 on 15/6/8. // Copyright (c) 2015年 张秀清. All rights reserved. // #import "ViewController.h" //角度转弧度 #define degreesToradian(x) (M_PI*x/180.0) //弧度转角度 #define radiansToDegrees(x) (180.0*x/M_PI) @i

JAVA实现求一点到另两点连线的距离,计算两点之间的距离

直接上代码 /** *计算两点之间距离 */ public static double getDistance(Point start,Point end){ double lat1=start.getX().doubleValue(); double lat2=end.getX().doubleValue(); double lon1=start.getY().doubleValue(); double lon2=end.getY().doubleValue(); return Math.sq

php向js的函数内传递参数-用经纬度计算2点间距离

有时候需要从php传递数据到js,这时候该怎么办呢?实例;php微信开发,用经纬度计算2点间的距离,2个坐标分别从php和js获得. 基于tp5框架的开发. 说一下注意事项: 1.php实际不能直接传递数据到js,他们两个没办法直接交互 2.可以通过一个桥梁交互,就是html 3.做法就是把js写在html页面内,然后再把把php传递过来的数据变量写在js代码内. 主要易混点在html页面 核心代码如下,从857行开始: <!DOCTYPE html> <!-- saved from u

杭电2001 计算两点之间的距离

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2001 注意输入时候的空格就可以了 #include<stdio.h> #include<math.h> int main() { double x1,x2,y1,y2; while(scanf("%lf %lf %lf %lf",&x1,&y1,&x2,&y2)!=EOF) { getchar(); printf("%.2f