Lubblobba
Lubblobba

Reputation: 65

Issue with code to find driving distance between two places with Google Distance Matrix

This is my previous post on the same matter: driving-distance-between-2-locations

I needed to find the driving distance between two locations using Google Maps but rather than in JavaScript I needed it in PHP. The accepted answer on that page worked for me in what I was looking for. I needed this for my project and haven't tested my project in a week or so, and after doing so now the code no longer works. It took a long time to search and find answers just for the code to suddenly stop working.

<?php
    $url = 'http://maps.google.com/maps/nav?q=from:London%20to:Dover';
    $data = file_get_contents($url);
    $data = utf8_decode($data);
    $obj = json_decode($data);
    echo $obj->Directions->Distance->meters;
?>

That is the code, I've tried some var_dumps but I'm not really experienced enough to understand.

Var_dumps for each line:

string(56) "http://maps.google.com/maps/nav?q=from:London%20to:Dover"

string(76) "{"name":"from:London to:Dover","Status":{"code":610,"request":"directions"}}"

string(76) "{"name":"from:London to:Dover","Status":{"code":610,"request":"directions"}}"

object(stdClass)#1 (2) { ["name"]=> string(20) "from:London to:Dover" ["Status"]=> object(stdClass)#2 (2) { ["code"]=> int(610) ["request"]=> string(10) "directions" } }

NULL

I've no idea how else to de-bug etc. If anyone could help I'd be so grateful as I'm so disappointed it's just stopped working.

Upvotes: 0

Views: 2219

Answers (1)

David Chase
David Chase

Reputation: 2073

Here you go

<?php
$url = 'http://maps.googleapis.com/maps/api/distancematrix/json?origins=London&destinations=Dover&mode=driving&language=en&sensor=false';
$data = file_get_contents($url);
$data = utf8_decode($data);
$obj = json_decode($data);

echo($obj->rows[0]->elements[0]->distance->text); //km
echo($obj->rows[0]->elements[0]->distance->value); // meters

Upvotes: 2

Related Questions