Show a map with your current location

In this article I am going to show you with a few lines of JavaScript how you can show the user's current location based on the IP address. We will also look at the more precise way to get the location in HTML5.

Demo

The code

Create three files; index.html, styles.css, and main.js, and copy, and paste the following into them.

index.html

<!DOCTYPE html>  
<html>  
  <head>
    <title>My location</title>
    <link rel="stylesheet" href="styles.css">
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <script src="main.js"></script> 
  </head>
  <body>
    <div>Current location: <span id="location"></span></div>
    <div id="map"></div>
  </body>
</html>  

styles.css

#map {
  width: 1000px;
  height: 500px;
}

main.js

(function(){
  window.addEventListener("load", function() {
    var element = document.querySelector("#location");
    var map = document.querySelector("#map");
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
      if(request.status === 200) {
        if(request.readyState === 4) {
          var location = request.response;
          element.innerText = "[" + location.ip + "] " 
            + location.city + " " 
            + location.region_code + ", " 
            + location.country_code;
          map.innerText = "generating map..."
          loadMap(location, map, element.innerText);
        }
      } else if (request.status === 0) {
        element.innerText = "loading...";
      } else {
        element.innerText = "unknown";
        map.innerText = "";
      } 
    };
    element.innerText = "requesting...";
    request.responseType = "json";
    request.open("GET", "http://freegeoip.net/json");
    request.send();
  });

  var loadMap = function(location, element, title) {
    var latlng = new google.maps.LatLng(location.latitude, location.longitude);
    var mapOptions = {
      zoom: 8,
      center: latlng
    }
    var map = new google.maps.Map(element, mapOptions);

    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        title: title
    });
  };
}());

Place these files in the same folder on a web server. If you don't have a web server available, you can use Google Chrome Dev Editor, which allows you to run a JavaScript Web App in the built-in web server.

You might be wondering why this solution doesn't show your exact location, but rather somewhere close (or not so close) to where you actually are. That is because the location is determined by your IP address. This will usually be the address that your request gets when leaving your ISP (Internet Service Provider), and when it is routed through the Internet to the freegeoip.net web site.

A more precise way

Look up the description of the XMLHttpRequest object here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

A more precise way of getting the location is described here:
http://www.w3schools.com/htmL/html5_geolocation.asp

We can use this more precise way like this:

main.js

(function(){
  window.addEventListener("load", function() {
    var element = document.querySelector("#location");
    var map = document.querySelector("#map");
    if(navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
          map.innerText = "generating map..."
          loadMap(position.coords, map, element.innerText);
      });
    }
  });

  var loadMap = function(location, element, title) {
    var latlng = new google.maps.LatLng(location.latitude, location.longitude);
    var mapOptions = {
      zoom: 8,
      center: latlng
    }
    var map = new google.maps.Map(element, mapOptions);

    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        title: "title"
    });
  };
}());

Other JSON services

Google Maps
Weather Forecast
Wikipedia
Movie search