Skip to content

Instantly share code, notes, and snippets.

@rolfen
Last active June 25, 2018 16:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rolfen/cdaf1895b44659c1c4d2b90970af443e to your computer and use it in GitHub Desktop.
Save rolfen/cdaf1895b44659c1c4d2b90970af443e 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) // Convert NodeList to Array
{
	var arr = [];
	for(var i=-1,l=nl.length;++i!==l;arr[i]=nl[i]);		
	return(arr);
}

Stage 1: parse HTML

var C1 = toArray(document.querySelectorAll("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))
@rolfen
Copy link
Author

rolfen commented Mar 19, 2018

Code is provided as-is, please spot-check your results!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment