Generate Latitude and Longitude With Google Maps API 


In this Article
Related Articles

Overview

At times you may wish to collect not just an address, but also the latitude and longitude of the address in question. However, many form respondents will not know the latitude and longitude of a given address. In situations like these, it is possible to use custom code to generate the latitude and longitude of a collected address and output this data into form fields automatically. 

Please Note: This solution uses custom code which the FormAssembly Support Team is unable to assist in writing or editing. The code in this help document is for reference only.


Before You Begin

Before you can utilize this code, you'll need to gather the following:

  1. The field aliases for each address field in your form.
  2. The field aliases for your latitude and longitude outputs. 
  3. A Google Maps API Key 

In the reference code below, replace the "tfa_alias" text with the associated field aliases. The type of field needed is noted in the comments. You will also need to replace the "YOUR_API_KEY_GOES_HERE" text with your Google Maps API Key. This code should then be placed in the custom code area of your form. 


Reference Code

<script>

const addressFields = [
"tfa_alias", // Street Address Field ID
"tfa_alias", // City/State Field ID
"tfa_alias", // Zip Code Field ID
]

const outputFields = {
  lat: "tfa_alias", // Latitude Field ID
  lng: "tfa_alias"  // Longitude Field ID
}

// Google Maps API Endpoint
const baseUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address=';
// Your Google Maps API Key
const apiKey = '<<<<<<YOUR_API_KEY_GOES_HERE>>>>>>>';

// Get the Lat/Lng Values
function updateGeolocation() {

  // Generates request URL
  const requestURL = addressFields.map(function (item) {
    // Get value of field
    const val = document.getElementById(item).value;

    // Replace spaces with +, for Google Maps API
    return val.split(' ').join('+')
  });

  const finalUrl = baseUrl + requestURL.join(',') + '&key=' + apiKey;

  fetch(finalUrl)
  .then(response => response.json())
  .then(data => {
    const latLng = (data.results[0].geometry.location);
    document.getElementById(outputFields.lat).value = latLng.lat
      document.getElementById(outputFields.lng).value = latLng.lng
  });
}

document.addEventListener("DOMContentLoaded", function(event) {
    addressFields.forEach( (element) => 
    {
      let input = document.getElementById(element);
      input.addEventListener('change', updateGeolocation)
    });
  });

</script>
Terms of Service · Privacy Policy