Search code examples
phpgoogle-distancematrix-api

Why is google distance matrix not accepting my variables as locations?


I am trying to pass some html form input through google distance matrix api. I have put them into variables and replaced the spaces with "+" signs. When I echo the variables they are perfect. When I hard code those variable values the api returns the distance, but it returns nothing when I use the variable representations.

<?php

$start = $_POST["origin"];
$end = $_POST["destination"];


$value = strtolower(str_replace(' ', '+', $start));

echo $value;

$value2 = strtolower(str_replace(' ', '+', $end));

echo $value2;

$url = 'http://maps.googleapis.com/maps/api/distancematrix/json?   
origins=$value&destinations=$value2&mode=driving&language=English- 
en&key=$key"';
$json = file_get_contents($url); // get the data from Google Maps API
$result = json_decode($json, true); // convert it from JSON to php array
echo $result['rows'][0]['elements'][0]['distance']['text'];

?>

Solution

  • The issue lies in the use / misuse of single quotes when working with PHP variables. If you use single quotes then variables within must be unquoted / escaped so that they are interpreted correctly. Perhaps the more favourable approach is to use double quotes around the entire string/url - use curly braces if necessary to ensure certain types of variables are processed properly ( ie: using an array variable {$arr['var']} )

    For the situation above the following ought to work - shown on one line deliberately to highlight that there are now no spaces in the url.

    $url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins={$value}&destin‌​ations={$value2}&mode=driving&language=English-en&key={$key}";