block by joyrexus 8692008

Geolocation and reverse geocoding

Full Screen

A simple demo utilizing geolocation sensing and reverse geocoding.

Displays your current location and address.

We’re using the Geolocation API to get the users current location coordinates and Google’s reverse geocoding service to get the address associated with those coordinates.

index.html

<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0,
minimum-scale=1.0">
<style>
  html {
    margin: 80px;
    font-family: "Helvetica Neue";
    font-weight: 100;
    font-size: 70px;
    color: #999;
  }
</style>
<div id="address">Address</div>
<div id="latitude">Latitude</div>
<div id="longitude">Longitude</div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
  navigator.geolocation.watchPosition(render);

  function render(pos){
    var lat = pos.coords.latitude;
    var lng = pos.coords.longitude;
    latitude.innerText  = lat.toFixed(7);
    longitude.innerText = lng.toFixed(7);
    var geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
          address.innerText = results[1].formatted_address;
        } else {
          alert('No results found');
        }
      } else {
        alert('Geocoder failed due to: ' + status);
      }
    });
  }
</script>