Geolocation

Geolocation

  • Is used to get the geographical position of a user.
  • Since this can compromise privacy, the position is not available unless the user approves it.
  • Geolocation is most accurate for devices with GPS, like smartphone.
  • Geolocation is also very useful for location-specific information, like: up-to-date local information, showing Points-of-interest near the user, turn-by-turn navigation (GPS).

Using HTML Geolocation

//the example below returns the latitude and longitude of the user's position
<script>
var x = document.getElementById("demo");
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude; 
}
</script>

The getCurrentPosition() method is used to return the user's position.

Handling Errors and Rejections

function showError(error) {
  switch(error.code) {
    case error.PERMISSION_DENIED:
      x.innerHTML = "User denied the request for Geolocation."
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML = "Location information is unavailable."
      break;
    case error.TIMEOUT:
      x.innerHTML = "The request to get user location timed out."
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML = "An unknown error occurred."
      break;
  }
}

The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location.

Displaying the Result in a Map

//in the example below, the returned latitude and longitude is used to show the //location in a Google Map (using a static image)

function showPosition(position) {
  var latlon = position.coords.latitude + "," + position.coords.longitude;

  var img_url = "https://maps.googleapis.com/maps/api/staticmap?center=
  "+latlon+"&zoom=14&size=400x300&sensor=false&key=YOUR_:KEY";

  document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}

To display the result in a map, you need access to a map service, like Google Maps.

Geolocation — Structure map

Clickable & Draggable!

Geolocation — Related pages: