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>
<html>
<body>
    <button onclick="whereAmI()">Where am I?</button>
    <p id="data"></p>
   
</body>
</html>

Insert this script:

var x = document.getElementById("data");
function whereAmI() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  }
}
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, http://www.latlong.net/Show-Latitude-Longitude.html 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:

Location.png

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

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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