My *nix world

List of distances between cities

As a programmer sometimes you need to a list of distances between cities for a predefined set of cities or any possible location around the world.

Where to find such a list? How big is it? Is it available for download? The answer is yes and no. No, I couldn't find such a list (if it's available it won't be free) and Yes, you can in fact get such a list even for free. I did it with only few lines of code. Bellow I will describe the necessary steps and requirements.

Google provides a free API service called Google Distance Matrix API. Basically this is an interface between you and their Distance Matrix database (used mostly by their Google Map). The service is free within some limits. The limits can be overcome if you pay for the service, of course.

You send a query like this:

https://maps.googleapis.com/maps/api/distancematrix/json?origins=Stockholm&destinations=Landskrona&mode=bicycling

and get in exchange an answer  (in JSON or XML format) like this:

{
   "destination_addresses" : [ "Stockholm, Sverige" ],
   "origin_addresses" : [ "Landskrona, Sverige" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "666 km",
                  "value" : 665574
               },
               "duration" : {
                  "text" : "1 dag 13 tim",
                  "value" : 133847
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

Using the above data you can easily build a data matrix that you can use it later in your projects.

You can query their database by using that link address right in your web browser or you can automate a bit the process by writing a small program. In Linux it can be done even at the terminal using a shell scripting language like BASH/SH via get/curl commands. Anyway I will provide below a code written in PHP.

The code below basically read a list from a text file where we have a city name on each line. Also we are interested in finding the distances between these cities. For each city send a query to Google API server and store some parts of the response to a matrix which later is saved to disk in JSON format (the format is user-friendly and also space-friendly).

The list of cities is called cities.txt and may look like this:

Stockholm
Goteborg
Malmo
Uppsala
Vasteras
Orebro
Linkoping
...

The PHP script looks like this:

<?php
function getDirection($from, $to) {
	$url = sprintf ( 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=%s&destinations=%s', $from, $to );
	$ch = curl_init ( $url );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt ( $ch, CURLOPT_HEADER, false );
	$data = curl_exec ( $ch );
	curl_close ( $ch );
	$data = json_decode ( $data, true );
	'OK' == $data ['rows'] [0] ['elements'] [0] ['status'] && ($result = array (
			$data ['rows'] [0] ['elements'] [0] ['distance'] ['value'],
			$data ['rows'] [0] ['elements'] [0] ['duration'] ['value'] 
	)) || $result = false;
	return $result;
}

$matrix = array ();
$locations = explode ( PHP_EOL, file_get_contents ( __DIR__ . DIRECTORY_SEPARATOR . 'cities.txt' ) );

// query the Google and gather the distance between each two locations
$i = 1;
$max = pow ( count ( $locations ), 2 );
foreach ( $locations as $from )
	foreach ( $locations as $to )
		if ($from != $to && ! ((isset ( $matrix [$from] ) && isset ( $matrix [$from] [$to] )) || (isset ( $matrix [$to] ) && isset ( $matrix [$to] [$from] )))) {
			printf ( "\r %d%% Gathering the distance between %s and %s%s", 100 * $i ++ / $max, $from, $to, str_repeat ( ' ', 20 ) );
			! isset ( $matrix [$from] ) && $matrix [$from] = array ();
			$response = getDirection ( $from, $to );
			if (false != $response) {
				$matrix [$from] [$to] = $response;
				// we save it after each call, just in case (each query costs!!!)
				file_put_contents ( __DIR__ . DIRECTORY_SEPARATOR . 'matrix.dat', json_encode ( $matrix, JSON_UNESCAPED_UNICODE ) );
				usleep ( 100000 ); // see the Google API query limits!!!
			}
		}

?>

The script above generates a file called matrix.dat that contains an entry for each city and one/many children for the other cities, each child has two information: the first represents the distance (m) between the city and the child-city, the second one represents the duration (s).

{
    "Stockholm":{
        "Goteborg":[
            466859,
            17100
        ],
        "Malmo":[
            610423,
            21238
        ],
        "Uppsala":[
            69624,
            3234
        ],
        "Vasteras":[
            106696,
            4410
        ],
        "Orebro":[
            200087,
            7667
        ],
        "Linkoping":[
            196587,
            7412
        ],
...

Note that Google will return different values for both the distance and duration depending on which distance "mode" you ask. By default is assumed "driving" but you can also search for "bicycling" mode, or "walking", etc (see Travel modes). Besides these there are a lot more options to use for your query, like what to avoid (ie. tolls, highways,etc) and many, many others.

The next thing we might be interested of would be what is the shortest path between city A and city B, or is there any route between A and B (sometimes there's no possible connection between two points by using a transport mean T - for instance a boat). Here comes in request one of the greatest mathematicians and computer scientists we were contemporary with: Edsger W. Dijkstra. His shortest-path algorithm is clever and simple. But more about this in other article.

Now, if you think that this article was interesting don't forget to rate it. It shows me that you care and thus I will continue write about these things.

The following two tabs change content below.
List of distances between cities

Eugen Mihailescu

Founder/programmer/one-man-show at Cubique Software
Always looking to learn more about *nix world, about the fundamental concepts of math, physics, electronics. I am also passionate about programming, database and systems administration. 16+ yrs experience in software development, designing enterprise systems, IT support and troubleshooting.
List of distances between cities

Latest posts by Eugen Mihailescu (see all)

Tagged on: ,

Leave a Reply

Your email address will not be published. Required fields are marked *