Google Maps v3: Geocoding

Cosa è il Geocoding?

Il geoconding è la possibilità di convertire un indirizzo in coordinate geografiche che si possono utilizzare per identificare un punto su una mappa.

In questo esempio utilizzando le API Google (Google Maps Geocoding API) da un indirizzo recuperiamo tutte le informazioni relative e aggiungiamo un marker sulla mappa.

La chiamata Google Maps Geocoding API :

var address = document.getElementById("address").value;
  
var geocoder = new google.maps.Geocoder();
  
geocoder.geocode( {'address': address}, function(results,status) {
if (status == google.maps.GeocoderStatus.OK) {
//do something
}

Il json restituito dalle API:

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "10",
               "short_name" : "10",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Corso Como",
               "short_name" : "Corso Como",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Milano",
               "short_name" : "Milano",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Milano",
               "short_name" : "Milano",
               "types" : [ "administrative_area_level_3", "political" ]
            },
            {
               "long_name" : "Città Metropolitana di Milano",
               "short_name" : "MI",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Lombardia",
               "short_name" : "Lombardia",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "Italy",
               "short_name" : "IT",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "20124",
               "short_name" : "20124",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "Corso Como, 10, 20124 Milano MI, Italy",
         "geometry" : {
            "location" : {
               "lat" : 45.48199109999999,
               "lng" : 9.187483199999999
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 45.4833400802915,
                  "lng" : 9.188832180291502
               },
               "southwest" : {
                  "lat" : 45.4806421197085,
                  "lng" : 9.186134219708498
               }
            }
         },
         "place_id" : "ChIJzYVCYjPBhkcR-YQk8vcsgqc",
         "types" : [ "street_address" ]
      }
   ],
   "status" : "OK"
}

Dal codice json restituito dalle API di Google Maps Geocoding possiamo ricavare le coordinate e creare il marker sulla mappa e magari inserire nel tooltip le informazioni relative.

var map = new google.maps.Map(document.getElementById('map'), options);
  
var marker = new google.maps.Marker(
  {
  position: results[0].geometry.location,
  map: map,
  title: document.getElementById("address").value
  }
);

var tooltip = '<div id="tooltip">'+
  '<p>formatted_address:<br>'+				
  results[0].formatted_address+'</p>'+
  '<p>latLng:<br>'+
  results[0].geometry.location+'</p>'+			
  '</div>';
  console.log(results[0].geometry.location.lat());
  console.log(results[0].geometry.location.lng());
var infowindow = new google.maps.InfoWindow({
  content: tooltip
});

google.maps.event.addListener(marker, 'click', function() {
  infowindow.open(map,marker);
});

Di seguito il codice completo. Si raccomanda di aggiungere/registrare la API key di google per utilizzare correttamente il servizio.

<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API v3: geocoding</title>
<style type="text/css">
html, body { margin:0; padding:0; width:100%; height:100%; }
body { background:#FFFFFF; color:#000000; font-family:Arial, Helvetica, sans-serif; font-size:12px; line-height:150%; text-align:center;}
#map { width:100%; height:95%; }
input { width:250px; }
#tooltip { padding:10px; text-align:left; }
#tooltip p { padding:0; margin:0 0 5px 0; }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">

var createMap = function() {
  
  searchAddress();

   	var address = document.getElementById("address").value;
  
  var geocoder = new google.maps.Geocoder();
  
  geocoder.geocode( {'address': address}, function(results,status) {
        if (status == google.maps.GeocoderStatus.OK) {
    
      var options = {
  				zoom: 12,
  				center: results[0].geometry.location,
  				mapTypeId: google.maps.MapTypeId.ROADMAP
      };	

      var map = new google.maps.Map(document.getElementById('map'), options);
  
      var marker = new google.maps.Marker(
        {
  				position: results[0].geometry.location,
  				map: map,
  				title: document.getElementById("address").value
        }
      );
  
      var tooltip = '<div id="tooltip">'+
        '<p>formatted_address:<br>'+				
   				results[0].formatted_address+'</p>'+
        '<p>latLng:<br>'+
        results[0].geometry.location+'</p>'+			
    			'</div>';
  console.log(results[0].geometry.location.lat());
  console.log(results[0].geometry.location.lng());
      var infowindow = new google.maps.InfoWindow({
        content: tooltip
      });
  
      google.maps.event.addListener(marker, 'click', function() {
  				infowindow.open(map,marker);
      });
        	
      
        } else {
          alert("Indirizzo non trovato: " + status);
        }
      });
    
}

var searchAddress = function(){
  document.getElementById("submit").onclick = function() {
    createMap();
  }
}

window.onload = createMap;
</script>
</head>
<body>
<div>
    <input id="address" type="textbox" value="Corso Como,10 - Milano">
    <input id="submit" type="button" value="Trova indirizzo">
</div>
<div id="map"></div>
</body>
</html>