简体   繁体   中英

Distance from point A to B using Google Maps, PHP and MySQL

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM