Created
February 15, 2018 22:33
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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