david-s
4/27/2020 - 11:52 AM

Google Geocode API with search and axios

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
      integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
      crossorigin="anonymous"
    />
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <title>Google Geocode</title>
  </head>
  <body>
    <div class="container">
      <h2 id="text-center">Enter Location:</h2>
      <form id="location-form" class="mb-5">
        <input
          type="text"
          id="location-input"
          class="form-control form-control-lg"
        />
        <br />
        <button type="submit" class="btn btn-primary btn-block">Submit</button>
      </form>
      <div class="card mb-5" id="formatted-address"></div>
      <div class="card mb-5" id="address-components"></div>
      <div class="card mb-5" id="geometry"></div>
    </div>

    <script>
      // Get location form
      const locationForm = document.getElementById("location-form");

      // Listen for submit
      locationForm.addEventListener("submit", geocode);

      // Call Google Geocode API
      function geocode(event) {
        // Prevent default form submit
        event.preventDefault();
        const location = document.getElementById("location-input").value;
        axios
          .get("https://maps.googleapis.com/maps/api/geocode/json", {
            params: {
              address: location,
              key: "YOUR_API_KEY",
            },
          })
          .then((res) => {
            // Log full response
            console.log(res);

            // Formatted Address
            const formattedAddress = res.data.results[0].formatted_address;
            const formattedAddressOutput = `
                <ul class="list-group">
                    <li class="list-group-item">${formattedAddress}</li>
                </ul>
            `;

            // Address Componenets
            const addressComponents = res.data.results[0].address_components;
            let addressComponentsOutput = '<ul class="list-group">';
            for (let index = 0; index < addressComponents.length; index++) {
              addressComponentsOutput += `
                    <li class="list-group-item"><strong>${addressComponents[index].types[0]}</strong>:
                    ${addressComponents[index].long_name}</li>
                `;
            }
            addressComponentsOutput += "</ul>";

            // Geometry
            const lat = res.data.results[0].geometry.location.lat;
            const lng = res.data.results[0].geometry.location.lng;
            const geometryOutput = `
                <ul class="list-group">
                    <li class="list-group-item"><strong>Latitude: </strong>${lat}</li>
                    <li class="list-group-item"><strong>Longitude: </strong>${lng}</li>
                </ul>
            `;

            // Output to app
            document.getElementById(
              "formatted-address"
            ).innerHTML = formattedAddressOutput;
            document.getElementById(
              "address-components"
            ).innerHTML = addressComponentsOutput;
            document.getElementById("geometry").innerHTML = geometryOutput;
          })
          .catch((error) => console.error(error));
      }
    </script>
  </body>
</html>