Read Google Contacts with 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);
}

Amit Agarwal is a web geek, solo entrepreneur and loves making things on the Internet. Google recently awarded him the Google Developer Expert and Google Cloud Champion title for his work on Google Workspace and Google Apps Script.

Awards & Recognition

Google Developer Expert

Google Developer Expert

Google awarded us the Developer Expert title recogizing our work in Workspace

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional title for 5 years in a row

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator award for technical expertise

Want to stay up to date?
Sign up for our email newsletter.

We will never send any spam emails. Promise 🫶🏻