Note that there are some explanatory texts on larger screens.

plurals
  1. POCalculating distance between coordinates - hardcoded values give different results
    text
    copied!<p>I'm trying to calculate the distance between two geographical coordinates in PHP (I'm aware this has been covered many times before, bear with me). The distances are typically between 100m and 50km, I'd like an accuracy of perhaps 1m. The coordinates I'm using are retreived from a database as strings accurate to 15 decimal places (eg <code>"48.862815856933594, 2.344875574111938"</code>).</p> <p>I tried the common Haversine algorithm and it seemed to work, and also tried the Vincenty algorithm described here: <a href="https://stackoverflow.com/a/10054282/1239254">https://stackoverflow.com/a/10054282/1239254</a> again it seemed to work.</p> <p>The results however were a bit off from web based calculators using the same algorithms though, so I dug a bit deeper. It turns out that if I hardcode the latitude and longitude values in as floats my results match the expected distances, but if I use the string values retrieved from the database I'm a couple of percent out.</p> <p>I have echoed out the values to check they're not being truncated or anything daft like that and they look fine. Any other suggestions what might be my issue?</p> <p>EDIT: Here's the Vincenty based code I'm currently using</p> <pre><code>public function calculate_distance(){ $this-&gt;treasures = $this-&gt;get_treasures(); $step = $this-&gt;treasures[5]; //48.862815856933594, 2.344875574111938 $nextStep = $this-&gt;treasures[6]; //48.853218078613281, 2.348813056945801 $latFrom = deg2rad(floatval($step['lat'])); $lonFrom = deg2rad(floatval($step['lon'])); $latTo = deg2rad(floatval($nextStep['lat'])); $lonTo = deg2rad(floatval($nextStep['lon'])); $earthRadius = 6371000; $lonDelta = $lonTo - $lonFrom; $a = pow(cos($latTo) * sin($lonDelta), 2) + pow(cos($latFrom) * sin($latTo) - sin($latFrom) * cos($latTo) * cos($lonDelta), 2); $b = sin($latFrom) * sin($latTo) + cos($latFrom) * cos($latTo) * cos($lonDelta); $angle = atan2(sqrt($a), $b); $this-&gt;distance = $angle * $earthRadius; return $this-&gt;distance; } </code></pre> <p>Using this code I get a return value of 1067.2242562782, but hard coding the numbers in the comments gives a value of 1105.4164933704</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload