Reverse Geocoding

by lemon kazi

HTML

<div id="dvMap"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">


</script>

CSS

/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

#dvMap {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

JavaScript

function initMap() {
  var map = new google.maps.Map(document.getElementById('dvMap'), {
    zoom: 8,
    center: {
      lat: 40.731,
      lng: -73.997
    }
  });
  var geocoder = new google.maps.Geocoder();
  var infowindow = new google.maps.InfoWindow();
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(p) {
		var pos = {
             lat: p.coords.latitude,
             lng: p.coords.longitude
           };
           console.log(pos);
      var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
      console.log(LatLng);
      var mapOptions = {
        center: LatLng,
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      map.setOptions(mapOptions);
      geocoder.geocode({
        'location': LatLng
      }, function(results, status) {
        console.log("geocoder callback status=" + status);
        if (status === 'OK') {
          if (results[0]) {
            map.setZoom(11);
            var details = results[0].address_components;
            var city;
            var country;
            console.log(JSON.stringify(details));
            for (var i = details.length - 1; i >= 0; i--) {
              for (var j = 0; j < details[i].types.length; j++) {
                if (details[i].types[j] == 'locality') {
                  city = details[i].long_name;
                } else if (details[i].types[j] == 'sublocality') {
                  city = details[i].long_name;
                } else if (details[i].types[j] == 'neighborhood') {
                  city = details[i].long_name;
                } else if (details[i].types[j] == 'postal_town') {
                  city = details[i].long_name;
                  console.log("postal_town=" + city);
                } else if (details[i].types[j] == 'administrative_area_level_2') {
                  city = details[i].long_name;
                  console.log("admin_area_2=" + city);
                }
                // from...