The Power of Geolocation in Simplifying Address Entry Form Autocompletion

I am facing a challenge with implementing Geolocation to automatically populate the address fields for my users. Specifically, I need assistance with (Mailing Address 1:) & (Physical Address 1:). Currently, the user addresses are displayed as they type, but once selected, I only want the Street Number and Street Address to appear in Mailing Address 1:, with the rest of the information (city, state, zip) filling in the corresponding fields and leaving Mailing Address 2: blank for apartment or suite details.

If the user selects that the physical and mailing addresses are identical, the autofill should mirror the process mentioned above.

If the addresses are different, I would like the same process to be followed.

Any assistance on this matter would be highly appreciated!

Answer №1

Give this a try,

It's working perfectly for me.

var placeSearch, autocomplete, autocomplete2;
var componentForm = {
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  postal_code: 'short_name'
};
var componentForm2 = {
  route2: 'long_name',
  locality2: 'long_name',
  administrative_area_level_12: 'short_name',
  postal_code2: 'short_name'
};

function initialize() {
  // Creating the autocomplete object with restrictions to geographical location types.
  autocomplete = new google.maps.places.Autocomplete(
    /** @type {HTMLInputElement} */
    (document.getElementById('autocomplete')), {
      types: ['geocode']
    });
  autocomplete2 = new google.maps.places.Autocomplete(
    /** @type {HTMLInputElement} */
    (document.getElementById('autocomplete2')), {
      types: ['geocode']
    });
  // When an address is selected from the dropdown, populate the form fields.
  google.maps.event.addListener(autocomplete, 'place_changed', function() {
    fillInAddress();
  });
  google.maps.event.addListener(autocomplete2, 'place_changed', function() {
    fillInAddress2();
  });
}

// [START region_fillform]
function fillInAddress() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }

  // Get each component of the address from the place details
  // and fill the corresponding field on the form.
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
    }
  }
  document.getElementById('autocomplete').value = 
    place.address_components[0]['long_name'] + ' ' +
    place.address_components[1]['long_name'];

  document.getElementById('route').value = '';
}

function fillInAddress2() {
    // Get the place details from the autocomplete object.
    var place = autocomplete2.getPlace();

    for (var component in componentForm2) {

      document.getElementById(component).value = '';
      document.getElementById(component).disabled = false;
    }

    // Get each component of the address from the place details
    // and fill the corresponding field on the form.
    for (var i = 0; i < place.address_components.length; i++) {
      var addressType = place.address_components[i].types[0];
      if (componentForm2[addressType + '2']) {
        var val = place.address_components[i][componentForm2[addressType + '2']];
        document.getElementById(addressType + '2').value = val;
      }
    }
  document.getElementById('autocomplete2').value = 
    place.address_components[0]['long_name'] + ' ' +
    place.address_components[1]['long_name'];

  document.getElementById('route2').value = '';
}
initialize();

document.querySelector('#chbSame').addEventListener('change', checkedAddr);


function checkedAddr() {
  if (document.getElementById('chbSame').checked) {
    document.getElementById('route2').value = document.getElementById('route').value;
    document.getElementById('locality2').value = document.getElementById('locality').value;
    document.getElementById('administrative_area_level_12').value = document.getElementById('administrative_area_level_1').value;
    document.getElementById('postal_code2').value = document.getElementById('postal_code').value;

document.getElementById('autocomplete2').value = document.getElementById('autocomplete').value;
  } else {
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
    <body onload="initialize()">
    <div id="locationField">
      <div class="clearfix">
    <label for="street_<cfoutput>#Add#</cfoutput>">Mailing Address 1:</label>
    <input type="text" name="street_#Add#" validateat="onSubmit" validate="maxlength" required="yes" id="autocomplete" size="54" maxlength="120" message="Please enter owner #Peoplecount#'s mailing address." onFocus="geolocate()" value="">
    </div>

    <div class="clearfix">
    <label for="m2street_<cfoutput>#Add#</cfoutput>">Mailing Address 2:</label>
    <input type="text" name="m2street_#Add#" validateat="onSubmit" required="no" validate="maxlength" id="route" size="54" maxlength="120" value="">
    </div>
      
    <div class="clearfix">
    <label for="city_<cfoutput>#Add#</cfoutput>">City:</label>
    <input type="text" name="city_#Add#" validateat="onSubmit" validate="maxlength" required="yes" id="locality" size="30" maxlength="50" message="Please enter owner #Peoplecount#'s mailing city." value="">
        </div>
        
        <div class="clearfix">
    <label for="state_<cfoutput>#Add#</cfoutput>">State:</label>
    <input type="text" name="state_#Add#" required="yes" id="administrative_area_level_1" size="8" maxlength="12" message="Please enter owner #Peoplecount#'s mailing state." value="">
    </div>
            
            <div class="clearfix">
    <label for="street_<cfoutput>#Add#</cfoutput>">Zip Code:</label>
    <input type="text" name="postal_#Add#" required="yes" id="postal_code" size="8" maxlength="12" message="Please enter owner #Peoplecount#'s mailing zip code." value="">
    </div>
      </div>

          <div class="">
  <input type="checkbox" name="billingtoo_<cfoutput>#Add#</cfoutput>" id="chbSame" />
  <em>Check this box if Physical Address and Mailing Address are the same.</em>
</div>
 
        

          <div id="locationField2">
            <div class="clearfix">
    <label for="pstreet_<cfoutput>#Add#</cfoutput>">Physical Address 1:</label>
    <input type="text" name="pstreet_#Add#" validateat="onSubmit" validate="maxlength" required="yes" id="autocomplete2" size="53" maxlength="120" message="Please enter owner #Peoplecount#'s physical address." onFocus="geolocate2()" value="">
    </div> 

    <div class="clearfix">
    <label for="p2street_<cfoutput>#Add#</cfoutput>">Physical Address 2:</label>
    <input type="text" name="p2street_#Add#" validateat="onSubmit" required="no" validate="maxlength" id="route2" size="53" maxlength="120" value="">
    </div>
            
    <div class="clearfix">
    <label for="pcity_<cfoutput>#Add#</cfoutput>">City:</label>
    <input type="text" name="pcity_#Add#" validateat="onSubmit" validate="maxlength" required="yes" id="locality2" size="30" maxlength="50" message="Please enter owner #Peoplecount#'s physical city." value="">
      </div>
            
            <div class="clearfix">
    <label for="pstate_<cfoutput>#Add#</cfoutput>">State:</label>
    <input type="text" name="pstate_#Add#" required="yes" id="administrative_area_level_12" size="8" maxlength="12" message="Please enter owner #Peoplecount#'s physical state." value="">
    </div>
                
            <div class="clearfix">
    <label for="pstreet_<cfoutput>#Add#</cfoutput>">Zip Code:</label>
    <input type="text" name="ppostal_#Add#" required="yes" id="postal_code2" size="8" maxlength="12" message="Please enter owner #Peoplecount#'s physical zip code." value="">
    </div>​​
            </div>

MODIFIED: updated based on feedback below

ALSO CHANGED: Following additional suggestions below

LATEST UPDATE: Adjustments made as per recent comments :)

CURRENT REVISION: Implemented further improvements after more input :)

Answer №2

Initializing address autocomplete function for mailing and physical addresses using Google Maps API.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a Full Height Background Image with a Responsive Width Using Jquery

I am facing an issue with my background image dimensions of 1400 in height and 1000 in width. When using any full-screen background jQuery plugin or code, the image crops from either the top or bottom to fit the entire screen. However, I am looking for a s ...

How do I utilize ng-repeat in Angular to pass a variable that specifies the number of repetitions?

When working on my app, I encountered a situation where I needed to retrieve elements from a database and display them using ng-reat. Everything was going smoothly until I realized that within this list, there was another set of data that required a separa ...

Language setting required for dijit.form.DateTextBox

I am attempting to create a calendar control dynamically using Dojo 1.5 and set the language to Spanish, but so far I have been unsuccessful. I tried using "lang:es-es" among other things with no success... here is the element: <input type="text" const ...

What could be causing the repetitive output in an Angular click event loop?

I am facing an issue while trying to log the data of the user based on the user tab that has been clicked. The problem is that it always displays the same data and not the data of other users. https://i.sstatic.net/ACo7y.png For example, when I click on ...

Steps for changing the background of a div using an array value

I'm struggling to update the background of a div using both javascript and jquery. html <div id="images"> <img class="mypics" src="kitty.png" style="display:none"></div> <img class="my ...

Expanding a table by including a new column using Node.js and Knex

Currently building a service for my router using Node.js and Knex, but I'm struggling to add a column to an existing table. Any assistance would be greatly appreciated. Even though I am working with PostgreSQL, I believe the solution will be similar r ...

Make sure to utilize the className attribute when styling a Material-UI component

I am attempting to apply CSS styles to a Material-UI component. defined in MyCss.css .trackTitle { color:white; } located in myComponent.js import "./MyCss.css" <Grid container item xs={1} className="trackTitle"> change col ...

Having difficulty leveraging the full capabilities of the Jquery.load() function

I'm currently facing an issue where the results I want to display to the user are not filtering properly based on their selection. I've been using GET on the same page (users.php?rid=) to process this, but for some reason, it seems to be loading ...

Issue with resizing browser window when using three.js EffectComposer

My current rendering setup encounters a resizing issue when adjusting the browser window size. In my setup, I am rendering two scenes - one for objects with postprocessing effects applied. The postprocessing effects are achieved using THREE.EffectComposer ...

How do I utilize ng-if in Angular to apply to only the parent tag and not the following markup?

Suppose I have two HTML elements with the same tag but different properties. How can I conditionally select between them? Here are the two tags in question: <a ui-sref="root.one(::{param: value})"> <a target="_blank" href="{{::model}}"> I ne ...

Filtering Key Presses in Quasar: A Comprehensive Guide

Seeking Assistance I am looking to integrate an "Arabic keyboard input filtering" using the onkeyup and onkeypress events similar to the example provided in this link. <input type="text" name="searchBox" value="" placeholder="ب ...

Retrieve data from a Rails controller using Ajax

Seeking assistance and insight for a coding dilemma I'm facing. In my Rails application, I have a controller named get_songs that retrieves a hash of songs belonging to the currently logged-in user. What I'm trying to achieve is to fetch this dat ...

Bringing in a feature within the Vue 3 setup

At the moment, I am attempting to utilize a throttle/debounce function within my Vue component. However, each time it is invoked, an error of Uncaught TypeError: functionTD is not a function is thrown. Below is the code snippet: useThrottleDebounce.ts imp ...

Google Chrome prevents requests from unauthorized sources

Upon attempting to access a frame from a separate origin, Chrome intervenes by blocking the action and generating an exception message: "Uncaught SecurityError: Blocked a frame with origin 'provider domain' from accessing a frame with origin & ...

Trouble with Ajax requests firing on document load in Firefox

When loading a JSP page in Firefox, I am invoking an AJAX function that calls a servlet. The servlet returns data in response. However, when I attempt to alert the data as shown in the code snippet below, I receive a null value. $.ajax({ url : 'S ...

Issue with MUI-table: The alternate rows in the MUI table component are not displaying different colors as intended

Struggling to apply different colors for alternate table rows function Row(props) { const { row } = props; const StyledTableRow = styled(TableRow)(({ theme }) => ({ '&:nth-of-type(odd)': { backgroundColor: "green", ...

Vue js: Stop Sorting array items; only display the resulting array

I recently came across a tutorial on voting for a Mayoral Candidate. The tutorial includes a sort function that determines the winner based on votes. However, I noticed that the sort function also rearranges the candidate list in real time, which is not id ...

Right-click context menu not working properly with Internet Explorer

Seeking assistance with extracting the URL and title of a website using JavaScript. The script is stored in a .HTM file accessed through the registry editor at file://C:\Users\lala\script.htm Below is the script: <script type="text/java ...

Encountering a console error even after implementing proper handling (MERN + Redux)

My axios get request is sending an endpoint that retrieves the user associated with the token stored in localStorage, and then updates the redux state with the user information. In cases where there is no token available, the endpoint returns a response wi ...

Unable to pass the new value to the onclick function

I am currently working with Gridster.js in combination with Twitter Bootstrap. My goal is to have a modal pop up when I double-click on a grid, allowing for customization of the grid. Currently, I am focusing only on the delete option. The issue I am fac ...