Skip to content

Instantly share code, notes, and snippets.

@dontcallmedom
Forked from rolfen/ReadMe.md
Created March 2, 2018 13:51
Show Gist options
  • Save dontcallmedom/47ffb55cd1caec64a737d63aa2d2fae8 to your computer and use it in GitHub Desktop.
Save dontcallmedom/47ffb55cd1caec64a737d63aa2d2fae8 to your computer and use it in GitHub Desktop.
Get GPS coordinates for major cities

GPS coordinates of major cities in the world

... to place markers on a map.

This code runs in the browser debugging console.

I parse this page to extract geographical coordibates for major cities:
https://en.wikipedia.org/w/index.php?title=List_of_cities_by_longitude&printable=yes

Just open this page in your browser, launch your debugging console and get ready to copy-paste.

First, define this function, it is a dependency:

function toArray(nl) 
{
	var arr = [];
	if(isNaN(nl.length)) {
		throw "Cannot get length";
	} else {
		for(var i=-1,l=nl.length;++i!==l;arr[i]=nl[i]);		
	}
	return(arr);
}

Stage 1: parse HTML

var C1 = toArray(document.querySelectorAll("#mw-content-text table.wikitable tbody tr")).map((tr)=>(
    toArray(tr.children).map((td)=>(
        td.innerText.trim()
    )
)
));

The array assigend to C1 is of type:

[
   [
      "16°30′S",
      "180°00′W",
      "Rabi Island",
      "N/A",
      "Fiji"
   ],
   [
      "51°53′N",
      "176°39′W",
      "Adak",
      "Alaska",
      "United States"
   ],
   // etc.
]

Stage 2: translate to GPS coordinates

Source: http://stackoverflow.com/a/1140335

function ConvertDMSToDD(degrees, minutes, seconds, direction) {
    var dd = parseInt(degrees) + parseInt(minutes)/60 + parseInt(seconds)/(60*60);

    if (direction == "S" || direction == "W") {
        dd = dd * -1;
    } // Don't do anything for N or E
    return dd;
}

var C2 = C1.map(function(city){
	var latLong = [city[0],city[1]];
	coords = latLong.map(function(l){
		var p = l.split(/[^\d\w]+/);
		return ConvertDMSToDD(p[0],p[1],0,p[2]);
	});
	return ({
		"lat/long" : latLong,
		"name" : city[2],
		"state" : city[3],
		"country" :city[4],
		"coords" : coords
	})
});

The result is in C2 and it's an array of objects.

Google Chrome console: Copy result to clipboard:

copy(JSON.stringify(C2,null,2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment