Google Contacts in Google Apps Script

This Google Apps Script with fetch all the entries from your Google Contacts including the physical addresses. It then uses the geocoding service of Google Maps to turn these addresses into latitude and longtude points which are finally written to a KML file for reading inside Google Maps.


function Generate_KML() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.toast("Scanning your Google Contacts. Please wait..", "Scan Started", -1);

  var contacts = ContactsApp.getContacts();
  
  // Standard header of the KML File
  var kml  = '<kml xmlns="http://www.opengis.net/kml/2.2"';
  kml += '<Document><name>Google Contacts</name>';
  
  for (var i=0; i<contacts.length; i++) {
        
    var name = contacts[i].getFullName();    
    var addr = contacts[i].getAddresses(ContactsApp.Field.HOME_ADDRESS);

    // Get the Work Address if Home Address is unavailable
    if (!addr.length) 
      addr = contacts[i].getAddresses(ContactsApp.Field.WORK_ADDRESS);
    
    if (addr.length) {
      addr = addr[0].getAddress();
      addr = addr.replace(/\n/g, ", ");   
      
      // Get the Latitude, Longitude for the address
      var geocode = Maps.newGeocoder().geocode(addr);
      
      if (geocode.status == "OK") {
        var point = geocode.results[0].geometry.location;      
        addr = geocode.results[0].formatted_address;
        
        kml += "<Placemark><name>" + name + "</name><description><![CDATA[";
        kml += addr + "]]></description><Point><coordinates>";
        kml += point.lng + "," + point.lat + "</coordinates>";
        kml += "</Point></Placemark>";      
      }            
    }
  }  
  
  kml += '</Document></kml>';
  
  var attach = [{fileName:"address.kml", content:kml}];
    
  // Send the KML file as an email attachment to the current user
  GmailApp.sendEmail(Session.getEffectiveUser(), "Google Contacts Map", 
                     "Open the KML inside Google Earth", {attachments: attach});    

  // On-screen notification
  ss.toast("The KML file has been sent to your mailbox. Goodbye!", "Done", -1);
}