Created
June 26, 2015 08:18
-
-
Save standa/999b68adec019107baa6 to your computer and use it in GitHub Desktop.
Calculate distance between two cities using google maps API
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
{ | |
"routes" : [ | |
{ | |
"bounds" : { | |
"northeast" : { | |
"lat" : 4.3561, | |
"lng" : 1.01389 | |
}, | |
"southwest" : { | |
"lat" : 9.293703, | |
"lng" : 5.96733 | |
} | |
}, | |
"copyrights" : "Map data ©2014 Google", | |
"legs" : [ | |
{ | |
"distance" : { | |
"text" : "9.4 km", | |
"value" : 9356 | |
}, | |
"duration" : { | |
"text" : "11 mins", | |
"value" : 651 | |
}, | |
"end_address" : "Brno, Czech Republic", | |
"end_location" : { | |
"lat" : 49.3561181, | |
"lng" : 16.0130389 | |
}, | |
... | |
} | |
], | |
"status" : "OK" | |
} |
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 | |
$from = 'Praha'; | |
$to = 'Brno'; | |
// @link https://developers.google.com/maps/signup?hl=cs | |
$key = 'AI...KEY...'; | |
$url = 'https://maps.googleapis.com/maps/api/directions/json?origin=%s&destination=%s&sensor=false&key=%s'; | |
$contents = file_get_contents(sprintf($url, urlencode($from), urlencode($to), $key)); | |
// output the response into a file or echo it | |
file_put_contents('directions.txt', $contents); | |
$json = json_decode($contents, true); | |
$from = $json['routes'][0]['legs'][0]['start_address']; | |
$to = iconv('UTF-8', 'windows-1250//TRANSLIT', $json['routes'][0]['legs'][0]['end_address']); | |
$totalDistance = $json['routes'][0]['legs'][0]['distance']['text']; | |
echo "$from -> $to total: $totalDistance."; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment