Reputation: 49
I have the following code :
$output = file_get_contents("http://maps.google.com/maps/nav?q=from:39.519894,-5.105667%20to:51.129079,1.306925");
$distance = json_decode($output);
I get the JSON response from Google API, but when I used json_decode()
for decoding the JSON I get a NULL
value means the function is not able to decode it.
What is the reason behind this?
Upvotes: 4
Views: 5200
Reputation: 95161
The returned value has Malformed UTF-8 characters possibly because of incorrectly encoding. All you need is utf8_encode
$json = file_get_contents('http://maps.google.com/maps/nav?q=from:39.519894,-5.105667%20to:51.129079,1.306925');
$data = json_decode(utf8_encode($json),true);
var_dump($data);
Upvotes: 2
Reputation: 291
This should work for you, you can pass the addresses or just latitude/longitude into $from & $to
$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";
Upvotes: 3