在PHP中测量两个坐标之间的距离

186

你好,我需要计算具有经纬度的两个点之间的距离。

我想避免调用外部API。

我尝试使用PHP实现Haversine公式:

下面是代码:

class CoordDistance
 {
    public $lat_a = 0;
    public $lon_a = 0;
    public $lat_b = 0;
    public $lon_b = 0;

    public $measure_unit = 'kilometers';

    public $measure_state = false;

    public $measure = 0;

    public $error = '';



    public function DistAB()

      {
          $delta_lat = $this->lat_b - $this->lat_a ;
          $delta_lon = $this->lon_b - $this->lon_a ;

          $earth_radius = 6372.795477598;

          $alpha    = $delta_lat/2;
          $beta     = $delta_lon/2;
          $a        = sin(deg2rad($alpha)) * sin(deg2rad($alpha)) + cos(deg2rad($this->lat_a)) * cos(deg2rad($this->lat_b)) * sin(deg2rad($beta)) * sin(deg2rad($beta)) ;
          $c        = asin(min(1, sqrt($a)));
          $distance = 2*$earth_radius * $c;
          $distance = round($distance, 4);

          $this->measure = $distance;

      }
    }

测试一些具有公共距离的给定点时,我得不到可靠结果。

我不明白是原始公式出错还是我的实现出了问题。


6
我在这里找到了很多语言的工作代码,包括php http://www.geodatasource.com/developers/php。 - krishna
13个回答

1

你好,这里是使用两个不同的纬度和经度获取距离和时间的编码。

$url ="https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=16.538048,80.613266&destinations=23.0225,72.5714";



    $ch = curl_init();
    // Disable SSL verification

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // Will return the response, if false it print the response
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Set the url
    curl_setopt($ch, CURLOPT_URL,$url);
    // Execute
    $result=curl_exec($ch);
    // Closing
    curl_close($ch);

    $result_array=json_decode($result);
print_r($result_array);

You can check Example Below Link get time between two different locations using latitude and longitude in php


13
使用数学计算可以很简单地找到某些信息,因此调用API可能是不必要的。 - Ivotje50

1
你可以尝试使用库 geo-math-php
composer require rkondratuk/geo-math-php:^1

例子:

<?php

use PhpGeoMath\Model\Polar3dPoint;

$polarPoint1 = new Polar3dPoint(
    40.758742779050706, -73.97855507715238, Polar3dPoint::EARTH_RADIUS_IN_METERS
);

$polarPoint2 = new Polar3dPoint(
    40.74843388072615, -73.98566565776102, Polar3dPoint::EARTH_RADIUS_IN_METERS
);

$geoDistance = $polarPoint2->calcGeoDistanceToPoint($polarPoint1);

1
"最简单的方法之一是:

。"

$my_latitude = "";
$my_longitude = "";
$her_latitude = "";
$her_longitude = "";

$distance = round((((acos(sin(($my_latitude*pi()/180)) * sin(($her_latitude*pi()/180))+cos(($my_latitude*pi()/180)) * cos(($her_latitude*pi()/180)) * cos((($my_longitude- $her_longitude)*pi()/180))))*180/pi())*60*1.1515*1.609344), 2);
echo $distance;

它会将结果四舍五入至小数点后两位。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接