WordPress.org

Support

Support » How-To and Troubleshooting » Placing distance into variable from geocoordinates script

Placing distance into variable from geocoordinates script

  • Hi Everyone,
    I’m building out a loop that I want to be able to display the distance in miles for each post based on variables containing the coordinates of one point and the coordinates of another. I have point A and B’s individual latitude and longitude values inside of custom fields.

    I found a script that is a good starting point, but no matter how I try to place Point A and B’s values, it crashes and the page either quits loading at that point, or I get the PHP white screen of death.

    Here’s the script I’m starting from:

    <?php
    function distance($lat1, $lon1, $lat2, $lon2, $unit) {
    
      $theta = $lon1 - $lon2;
      $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
      $dist = acos($dist);
      $dist = rad2deg($dist);
      $miles = $dist * 60 * 1.1515;
      $unit = strtoupper($unit);
    
      if ($unit == "K") {
        return ($miles * 1.609344);
      } else if ($unit == "N") {
          return ($miles * 0.8684);
        } else {
            return $miles;
          }
    }
    
    echo distance(32.9697, -96.80322, 29.46786, -98.53506, "M") . " Miles<br>";
    
    ?>

    And here’s an example of how I’ve tried getting the variables into the script:

    <?php
    function distance($lat1, $lon1, $lat2, $lon2, $unit) {
    
      $theta = $lon1 - $lon2;
      $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
      $dist = acos($dist);
      $dist = rad2deg($dist);
      $miles = $dist * 60 * 1.1515;
      $unit = strtoupper($unit);
    
      if ($unit == "K") {
        return ($miles * 1.609344);
      } else if ($unit == "N") {
          return ($miles * 0.8684);
        } else {
            return $miles;
          }
    }
    
    echo distance('.$a_lat.', '.$a_long.', '.$b_lat.', '.$b_long.', "M") . " Miles<br>";
    
    ?>

    My question is: How can I properly echo out the variables into this script so that it shows up with each post in the loop?

    Thanks!

  • The topic ‘Placing distance into variable from geocoordinates script’ is closed to new replies.
Skip to toolbar