Skip to content

Instantly share code, notes, and snippets.

@davidsword
Created February 15, 2018 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidsword/5af8e953045e2e8d11dac249dd71b6a4 to your computer and use it in GitHub Desktop.
Save davidsword/5af8e953045e2e8d11dac249dd71b6a4 to your computer and use it in GitHub Desktop.
get the distance between two user supplied geo locations with google maps api. includes location suggestions in input dropdown.
<?php
<h3>KM Calculator</h3><?php
$key = '************-******************************';
$thispage = '?'; // ex https://localhost/index.php
if (isset($_GET['from'])) {
$from = urlencode($_GET['from']);
$to = urlencode($_GET['to']);
$query = "?origins={$from}&destinations={$to}&key={$key}";
$result = curl_page('https://maps.googleapis.com/maps/api/distancematrix/json'.$query);
$route = json_decode($result);
echo "
{$route->origin_addresses[0]} to {$route->destination_addresses[0]} is est:
{$route->rows[0]->elements[0]->distance->text}
<div> <a href='{$thispage}'>Back to search</a> </div>";
} else { ?>
<form id='distanceCalc' action='' method='GET'>
<input name='from' type='text' id='from' placeholder='From' value='' />
<input name='to' type='text' id='to' placeholder='To' value='' />
<input type='submit' value='submit' />
</form>
<script>
function initAutocomplete() {
var autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('from')),
{types: ['geocode']}
);
var autocomplete2 = new google.maps.places.Autocomplete(
(document.getElementById('to')),
{types: ['geocode']}
);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=<?= $key ?>&libraries=places&callback=initAutocomplete" async defer></script>
<?php
}
// curl page
function curl_page($url) {
$ch = curl_init($url) or die("curl issue");
$curl_options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_ENCODING => "",
CURLOPT_AUTOREFERER => true,
CURLOPT_CONNECTTIMEOUT => 7,
CURLOPT_TIMEOUT => 7,
CURLOPT_MAXREDIRS => 3,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_USERAGENT => "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13"
);
curl_setopt_array($ch, $curl_options);
$curlcontent = curl_exec( $ch );
curl_close( $ch );
return $curlcontent;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment