Professional Development

Using Javascript to Find Your Current Location

How accurately can Internet browsers determine your physical location? Pretty accurately apparently, and with just a couple lines of code. Take this example:

<!DOCTYPE html>
    <button onclick="whereAmI()">Where am I?</button>
    <p id="data"></p>

Insert this script:

var x = document.getElementById("data");
function whereAmI() {
  if (navigator.geolocation) {
function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;

Run this code (e.g. save to a Notepad file with extension .html and then open with your favorite browser), click the button, and you will get latitude and longitude coordinates for your current location. Plug these into, for example, and see how close the coordinates are to your actual location. I think you’ll find they’re pretty close. Here’s my results at the time of writing this:


Right on top of the apartment building I’m in! Are you surprised at how accurately your web browser knows where you are?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s