Recover distance with Google Map API

georgie

Member
Hello

I would do a kind of Ubber App with Fabrik. I try the "Direction" option in Map Viz, nice;)!
I would recover distance between my 2 point according Google Map, please is it possible?
Have you some documentation about this?

THX
 
I've never tried it, but I'm sure it's possible.

What exactly are you trying to do? Do you want this in JavaScript? Where would you display it?

-- hugh
 
Yes in Javascript I think, in a PHP plugin form for example, to recover the value in a field.

Indeed after, I would do a calculation with the distance, to display a "Estimated price".

You think to anything?
 
Hello

It going...
For now, by GM API, I can create an URL in a Fabrik form plugin, URL that leads to a dynamic JSON, with correct distance and time according Google, greats!

I use for that two Fabrik GM elements, from which I remove parentheses and zoom, and replace spaces by "%20".
Then I put them in the GM URL to ask distance. It works fine, and it corresponds to the map provided by the Fabrik Direction option!
Here my code in a PHP Fabrik form plugin (with a var_dump at end):
Code:
// Clean Start GM element
$VarStart =  '{booking___start_address_coord}' ;
$MaVarStart2 =  substr($VarStart, 0, strpos($VarStart, ":"));
$MaVarStart3 = str_replace('(' , '' , $MaVarStart2) ;
$MaVarStart4 = str_replace(')' , '' , $MaVarStart3) ;
$MaVarStart5 = str_replace(' ' , '%20' , $MaVarStart4) ;
$VarStart= $MaVarStart5 ;

// Clean End GM element
$VarArrival =  '{booking___end_address_coord}' ;
$MaVarArrival2 =  substr($VarArrival, 0, strpos($VarArrival, ":"));
$MaVarArrival3 = str_replace('(' , '' , $MaVarArrival2) ;
$MaVarArrival4 = str_replace(')' , '' , $MaVarArrival3) ;
$MaVarArrival5 = str_replace(' ' , '%20' , $MaVarArrival4) ;
$VarArrival= $MaVarArrival5 ;

// Create URL according GM API
$VarURLGM = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=$MaVarStart5&destinations=$MaVarArrival5" ;

// Read the JSON
//$obj = json_decode("$VarURLGM") ;

// Look up var
var_dump((string) $VarURLGM) ;
exit ;

And here an example to a dynamic JSON URL created:
https://maps.googleapis.com/maps/ap...2&destinations=49.0449034, 2.0419157999999697

But now I am blocked, indeed I can not read variables from this JSON in my var_dump.
I have tried some syntaxs with "json_decode" and "file_get_contents", without success...:confused:

Please can you help me?
 
Good work.

I think the you'll need to get a key, and append it to your API call:

https://developers.google.com/maps/documentation/distance-matrix/get-api-key

To avoid excessive use of the API, the best place to do this would be when submitting the form, in a PHP plugin onBeforeProcess, and set the form data for the distance.

To get the coords, there's a helper, FabrikString::mpStrToCoords() ...

PHP:
// get the simple "lat,long" strings
$coords = FabrikString::mapStrToCoords('{booking___start_address_coord}') ;
$startCoords= $coords->lat . ',' . $coords->long;
$coords = FabrikString::mapStrToCoords('{booking___end_address_coord}') ;
$endCoords = $coords->lat . ',' . $coords->long;

//build the URL, with API key
$distanceURL = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=$startCoords&destinations=$endCoords&key=xxxxxxxxxxxxxxx" ;

// get the result and decode it
$distanceData = file_get_contents($distanceURL);
$distanceResult = json_decode($distanceData);

// test ... comment this out once you have the right URL and are getting sane JSON
var_dump($distanceURL, $distanceResult); exit;

// if result OK, grab the 'value' from the first row's first element data and stuff it into your distance element
if ($distanceResult->status === 'OK') {
   $firstRow = FArrayHelper::getValue($distanceResults->rows, 0);
   $firstElement = FArrayHelper::getValue($firstRow, 0);
   $formModel->setFormData('booking___distance', $firstElement->distance->value);
}

I haven't tried that code, so I can't guarrantee it, but looking at the JSON example you gave, it should be right.

-- hugh
 
Hello

Thanks for "FabrikString::mapStrToCoords" :oops:, more short...

Indeed, with the "get the result and decode it" method, I can read the JSON, thanks ;)

But I can not select row and value, this code for example (var_dump at end) gives no error but just "NULL":

PHP:
// get the simple "lat,long" strings
$coords = FabrikString::mapStrToCoords('{booking___start_address_coord}') ;
$startCoords= $coords->lat . ',' . $coords->long;
$coords = FabrikString::mapStrToCoords('{booking___end_address_coord}') ;
$endCoords = $coords->lat . ',' . $coords->long;

//build the URL, with API key
$distanceURL = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=$startCoords&destinations=$endCoords&key=MYKEY" ;

// get the result and decode it
$distanceData = file_get_contents($distanceURL);
$distanceResult = json_decode($distanceData);

$firstRow = FArrayHelper::getValue($distanceResults->rows,0);
$firstElement = FArrayHelper::getValue($firstRow,0);

// Test ... comment this out once you have the right URL and are getting sane JSON
var_dump($firstElement ); exit;

Please what do you think about?
 
I don't know exactly what FArrayHelper is doing.
Maybe FArrayHelper::getValue($firstRow->elements,0); is doing.

"Manually" with var_dump($distanceResult->rows[0]->elements[0]); I see
object(stdClass)#3 (3) {
["distance"]=>
object(stdClass)#4 (2) {
["text"]=>
string(6) "4.8 km"
["value"]=>
int(4842)
}
["duration"]=>
object(stdClass)#5 (2) {
["text"]=>
string(7) "11 mins"
["value"]=>
int(673)
}
["status"]=>
string(2) "OK"
}
 
Thanks!
"Manually" it seems to work. You do not advice to do like this in PHP form plugin?
Because it seems to work without "FArrayHelper", just with "$distanceResult->rows[0]->elements[0]->distance->value".
I keep my tests.
 
You should still use the array helper, in case you don't get a result from Google, in which case just trying to blindly access [0] will error out. The array helper (which is actually the Joomla JArrayHelper, with a few extra function) getValue() will prevent getting an error trying to access a non-existant array index. The way you use it is ...

$whatever = FArrayHelper($yourArray, $yourIndex, $yourDefault);

... so if $yourIndex doesn't exist in $yourArray, you get back $yourDefault instead of a PHP error / warning and a null result.

You also need to test for "OK" in the status.

The reason it's NULL is because I made a typo. Look at the code, and you'll see I assigned $distanceResult, then used $distanceResults (plural) in the array helper.

Code:
if ($distanceResult->status === 'OK') {
   // get the first row, by using the array helper to get index 0, with an empty array as default
   $firstRow = FArrayHelper::getValue($distanceResult->rows, 0, array());
   // check to see if the result is empty
   if (!empty($firstRow)) {
      // if we got the first row, get the first element from it
      $firstElement = FArrayHelper::getValue($firstRow, 0);
      if (!empty($firstElement)) {
         // if we got the element, get the distance
         $formModel->setFormData('booking___distance', $firstElement->distance->value);
      }
   }
}
 
At some point I might add this functionality to the map element, and let you designate a 'distance' element in with the rest of the geocode settings. It's something I did think of doing when I added the Directions from feature, I just haven't had time to do it.

-- hugh
 
We are in need of some funding.
More details.

Thank you.

Members online

Back
Top