Skip to content

Instantly share code, notes, and snippets.

@azimidev
Last active August 8, 2017 18:59
Show Gist options
  • Select an option

  • Save azimidev/a88f56318ca3b722af2e7b4945b40200 to your computer and use it in GitHub Desktop.

Select an option

Save azimidev/a88f56318ca3b722af2e7b4945b40200 to your computer and use it in GitHub Desktop.
FInd if an $origin includes $destination withing a specific $distance or default to 50 KM
<?php
/*{
"destination_addresses" : [ "" ],
"origin_addresses" : [ "" ],
"rows" : [
{
"elements" : [{
"distance" : {
"text" : "1.9 mi",
"value" : 3000
},
"duration" : {
"text" : "7 mins",
"value" : 429
},
"status" : "OK"
}
]}
],
"status" : "OK"
}*/
function matrix($origin, $destination, $distance = 50)
{
$origin = str_replace(' ', '', $origin);
$destination = str_replace(' ', '', $destination);
$distance *= 1000; // meters to kilometers
$url = 'https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=' .
$origin . '&destinations=' . $destination . '&key=' . config('services.google.key');
$cacheKey = md5(vsprintf('%s.%s.%s', [$origin, $destination, $distance]));
if ( ! cache($cacheKey)) {
// $client = new GuzzleHttp\Client();
// $request = $client->request('GET', $url);
// $response = json_decode($request->getBody()->getContents(), true);
$context = stream_context_create(['http' => ['header' => 'Connection: close\r\n']]);
$response = json_decode(file_get_contents($url, false, $context), true);
$duration = Carbon\Carbon::now()->addDays(3);
cache([$cacheKey => $response], $duration);
} else {
$response = cache($cacheKey);
}
if ($response['status'] === 'OK' && $response['rows'][0]['elements'][0]['status'] === 'OK') {
return $response['rows'][0]['elements'][0]['distance']['value'] <= $distance;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment