Distance from point A to B using Google Maps, PHP

2020-02-06 11:06发布

问题:

Can anyone please help. I just need a simple script. I have a form posted to another page. two formfields are:

fromaddress and toaddress

The only thing I need is a script that shows me the distance in km and the time it takes using google maps. I have found dozens of scripts but I cannot get it working. The map is already there with this code which seems to work perfect.

<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key=AIzaSyDdDwV6_l5n2bS3gM6NBCla3RFLtIFc_HE&sensor=false"></script><script type="text/javascript">
    var directionDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map;

    function initialize() {
        directionsDisplay = new google.maps.DirectionsRenderer();
        var myOptions = {
            zoom: 8,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        directionsDisplay.setMap(map);

        var start = "<? echo $_POST[fromaddress]; ?>";
        var end = "<? echo $_POST[toaddress]; ?>";
        var request = {
            origin:start, 
            destination:end,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            }
        });

    }

    $(document).ready(function(){
        initialize();
    });        
</script>

But how do i display the distance and the time. Best option is to get it in a php value like:

$distance = some-code;
$time = some-code-too;

Thanks a lot for helping.

回答1:

You need to use different API for that. First of all, don't use JS but PHP, here's the code snippet that should work for you ;)

$from = "Więckowskiego 72, Łódź";
$to = "Gazowa 1, Łódź";

$from = urlencode($from);
$to = urlencode($to);

$data = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&sensor=false");
$data = json_decode($data);

$time = 0;
$distance = 0;

foreach($data->rows[0]->elements as $road) {
    $time += $road->duration->value;
    $distance += $road->distance->value;
}

echo "To: ".$data->destination_addresses[0];
echo "<br/>";
echo "From: ".$data->origin_addresses[0];
echo "<br/>";
echo "Time: ".$time." seconds";
echo "<br/>";
echo "Distance: ".$distance." meters";

Output:

To: Gazowa 1, 91-076 Łódź, Poland
From: Więckowskiego 72, Łódź, Poland
Time: 206 seconds
Distance: 1488 meters


回答2:

You can calculate the complete route duration and distance by adding up all the legs:

  function computeTotals(result) {
  var totalDist = 0;
  var totalTime = 0;
  var myroute = result.routes[0];
  for (i = 0; i < myroute.legs.length; i++) {
    totalDist += myroute.legs[i].distance.value;
    totalTime += myroute.legs[i].duration.value;
  }
  totalDist = totalDist / 1000.
  document.getElementById("total").innerHTML = "total distance="+totalDist.toFixed(2) + " km ("+(totalDist*0.621371).toFixed(2)+" miles), time="+totalTime+" seconds";
  }

call it like this:

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            computeTotals(response);
        }
    });

working example