Postal Code Auto-Suggest by Google

I'm attempting to create a unique autocomplete feature for a text box that specifically provides postal codes. To accomplish this, I have followed the guidelines outlined in the documentation found at https://developers.google.com/places/webservice/autocomplete#place_types

For a working example of my progress so far, please visit the following JSFiddle link: here

I am encountering a problem when trying to implement the postal_code option. However, when using the cities option, everything works fine. How can I modify my code to achieve an autocomplete feature that only retrieves postal codes?

function postal_code() {
  var input = document.getElementById('field-postal');
  var options = {
    types: ['(postal_code)'],
    componentRestrictions: {
      country: "in"
    }
  }
  var autocomplete = new google.maps.places.Autocomplete(input, options);
}

google.maps.event.addDomListener(window, 'load', postal_code);

Answer №1

The guide lacks clarity.

  • The (areas) category selection prompts the Places service to provide results that match any of the following types:
    • locality
    • sublocality
    • postal_code
    • country
    • administrative_area_level_1
    • administrative_area_level_2

Answer №2

Google's documentation can sometimes be difficult to understand, but after thorough research, I have managed to find the solution:

If you want to search exclusively by postal code:

types: ['postal_code']

If you want to search for addresses that include the postal code:

types: ['(regions)']

or

types: ['geocode']

Here is the relevant documentation from Google:

https://developers.google.com/maps/documentation/places/web-service/autocomplete#types

You are allowed to combine geocode and establishment types, but mixing type collections (address, (cities), or (regions)) with any other type will result in an error.

https://developers.google.com/maps/documentation/places/web-service/supported_types#table3

The supported types include:

  • geocode - This requests the Place Autocomplete service to only return geocoding results, rather than business results. It is commonly used to clarify ambiguous locations.
  • address - This instructs the Place Autocomplete service to only return geocoding results with precise addresses. It is typically used when the user expects to search for a specific address.
  • establishment - This requests the Place Autocomplete service to only return business results.
  • The (regions) type collection instructs the Places service to return results matching any of the following types:
    • locality
    • sublocality
    • postal_code
    • country
    • administrative_area_level_1
    • administrative_area_level_2
  • The (cities) type collection instructs the Places service to return results that match either locality or administrative_area_level_3.

Answer №3

I utilized the postal_code address section type.

Ensure that you have included the places library in your script URL as follows:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places&callback=initEditClntInfoAutoComplete"    async defer>  </script>

An illustrative example can be found at:

https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete

////////// SECTION FROM MY FUNCTIONING CODE
////////// Replace getByElementId with the IDs of your form inputs

  ////  Global Vars

  var  editClntInfoAutocomplete, addrStreet ="",
       addressComponets = {
                    street_number: 'short_name',
                    route: 'long_name',
                    locality: 'long_name',
                    administrative_area_level_1: 'short_name',
                    country: 'long_name',
                    postal_code: 'short_name'
       };

function initEditClntInfoAutoComplete() {   // Callback  

      editClntInfoAutocomplete = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */(document.getElementById('clntInfoEditAddr1')),
            {types: ['geocode']});

        // When the user selects an address from the dropdown, populate the address
        // fields in the form.
        editClntInfoAutocomplete.addListener('place_changed', fillInEditClntInfoAddress);
    }

    function fillInEditClntInfoAddress() {

        var place = editClntInfoAutocomplete.getPlace();        

            clearPrevEditFormAddrValues();

        for ( var i = 0; i < place.address_components.length; i++) {

              var addressType = place.address_components[i].types[0]; 
              if (  addressComponets[addressType] ) {
                    var val = place.address_components[i][addressComponets[addressType]];                 

                    assignEditFormAddrFieldsValue(addressType, val );
              }

         }

           if( addrStreet != "")
                 document.getElementById("clntInfoEditAddr1").value = addrStreet;

     }

     function assignEditFormAddrFieldsValue( addressType , val ) {

            switch( addressType ) {
                case "administrative_area_level_1":
                        document.getElementById("clntInfoEditState").value = val;  break;
                case "locality":
                    document.getElementById("clntInfoEditCity").value = val;  break;
                //   case "country":
                //        document.getElementById("addressType").value = val;  break;
                case "postal_code":
                    document.getElementById("clntInfoEditZip").value = val;  break;  
                case "street_number": 
                case "route":     
                    addrStreet += " "+val;      break;

            }

     }

     function clearPrevEditFormAddrValues(){
         var editClntFrmAddrIDs = ["clntInfoEditState","clntInfoEditCity","clntInfoEditZip","clntInfoEditAddr1"];
             addrStreet = "";

         for( var frmID in editClntFrmAddrIDs )
              wrap(editClntFrmAddrIDs[frmID]).val("");
     }

Answer №4

I recently came across this information and felt compelled to share my insights in the hopes that it will benefit someone.

As @geocodezip rightly pointed out, it is not possible to specifically request Google for postcode results only. However, you can request regions and inform the user when there is an error in their input!

The following code snippet demonstrates how I achieve this. It utilizes two inputs: one for the address prefix (house name/number) and another for the postcode.

Prerequisites:
A div element with two inputs for searching.
Below that, a div container containing inputs with the following IDs (these IDs may have prefixes):

  • Address1
  • Address2
  • City
  • County
  • Postcode
  • Country

All of my user inputs are assigned the "InputControl" class, which I utilize in my function to clear previous values.

How to Use It:

var autoAddr;

function initAutocomplete() {
    autoAddr = new google.maps.places.Autocomplete(document.getElementById('AddressSearchField'), { types: ['(regions)'] });
    autoAddr.addListener('place_changed', FillInAddress);
}
function FillInAddress() {
    GooglePlacesFillAddress(autoAddr, "#AddressCont", "");
}

The Main Function:

function GooglePlacesFillAddress(Place, ContainerId, AddressPrefix) {
    var
        place = Place.getPlace(),
        arr = ['premise', 'route', 'locality', 'postal_town', 'administrative_area_level_2', 'postal_code', 'country'],
        dict = {},
        adr = $(ContainerId).find("#" + AddressPrefix + "Address1"),
        switched = false,
        switchedAgain = false,
        searchAgain = $("<p id=\"" + AddressPrefix + "AddressSearchAgain\"><a href=\"javascript:void(0)\" class=\"Under\">I would like to search again</a></p>"),
        asc = $("#" + AddressPrefix + "AddressSearchCont"),
        adressPrefixValue = $("#" + AddressPrefix + "AddressSearchPrefixField").val().trim();

    SlideShow(ContainerId),
    $(ContainerId).find("input.InputControl").val(''),
    asc.find("#" + AddressPrefix + "AddressSearchField, #" + AddressPrefix + "AddressSearchPrefixField").attr("disabled", "disabled"),
    asc.find("#" + AddressPrefix + "AddressSearchFieldButton").addClass("disabled"),
    asc.find("#" + AddressPrefix + "AddressSearchPrefixField").after(searchAgain),
    searchAgain.on("click", function () {
        $(this).remove(),
        asc.find("#" + AddressPrefix + "AddressSearchField, #" + AddressPrefix + "AddressSearchPrefixField").removeAttr("disabled").val(''),
        asc.find("#" + AddressPrefix + "AddressSearchFieldButton").removeClass("disabled"),
        asc.find("#" + AddressPrefix + "AddressSearchPrefixField").focus();
    });

    if (place.address_components && place.address_components.length)
        for (var i = 0; i < place.address_components.length; i++)
            for (var j = 0; j < place.address_components[i].types.length; j++)
                if ($.inArray(place.address_components[i].types[j], arr) >= 0)
                    dict[place.address_components[i].types[j]] = place.address_components[i]["long_name"];

    $(ContainerId).find("#" + AddressPrefix + "City").val(dict["postal_town"] || '');
    $(ContainerId).find("#" + AddressPrefix + "County").val(dict["administrative_area_level_2"] || '');
    $(ContainerId).find("#" + AddressPrefix + "Postcode").val(dict["postal_code"] || '');
    $(ContainerId).find("#" + AddressPrefix + "Country").val(dict["country"] || 'United Kingdom');

    var isPostal = false;
    if (place.types && place.types.length)
        if ($.inArray("postal_code", place.types) >= 0 && $.inArray("postal_code_prefix", place.types) < 0)
            isPostal = true;

    // Add street number
    InputAdder(adr, adressPrefixValue, true);

    // Add premise
    if (adressPrefixValue.length == 0 || adr.val().length + (dict["premise"] || '').length > 100)
        adr = $(ContainerId).find("#" + AddressPrefix + "Address2"), switched = true;
    InputAdder(adr, (dict["premise"] || ''), true);

    // Add route
    if (adr.val().length + (dict["route"] || '').length > 100) {
        adr = $(ContainerId).find("#" + AddressPrefix + (switched ? "City" : "Address2"));
        if (switched)
            switchedAgain = true;
        else
            switched = true;
    }
    InputAdder(adr, (dict["route"] || ''), !switchedAgain, adressPrefixValue.length > 0 && adr.val() == adressPrefixValue);

    // Add locality
    InputAdder(switched ? adr : $(ContainerId).find("#" + AddressPrefix + "Address2"), (dict["locality"] || ''), !switchedAgain);

    if (!isPostal)
        WriteBorderedBox(false, ContainerId, "The postcode provided doesn't seem complete or valid. Please verify the address below."),
        $(ContainerId).find("#" + AddressPrefix + "Address1").focus();
}

Helper Functions:

function InputAdder(Obj, Text, Post, DontAddComma) {
    if (Obj && Text.length > 0) {
        var
            i = Obj.val().trim() || '',
            comma = !!DontAddComma ? "" : ",";

        Obj.val(
            (Post && i.length > 0 ? i + comma + ' ' : '') +
            Text.trim() +
            (!Post && i.length > 0 ? comma + ' ' + i : ''));
    }
}
function WriteBorderedBox(outcome, identifier, text) {
    var
        box = $("<div class=\"Bordered" + (outcome ? "Success" : "Error") + "\"><p>" + text + "</p></div>");
    $(identifier).before(box);
    box.hide().slideDown(function () { $(this).delay(6000).slideUp(function () { $(this).remove(); }); });
}

To Add a Button: (similar to my implementation)

$("#AddressSearchFieldButton").click(function (e) {
    var input = document.getElementById("AddressSearchField");

    google.maps.event.trigger(input, 'focus')
    google.maps.event.trigger(input, 'keydown', { keyCode: 40 });
    google.maps.event.trigger(input, 'keydown', { keyCode: 13 });
});

Answer №5

After some extensive research on the internet, I managed to come up with a straightforward solution. This ingenious method involves iterating through the "address_component" and extracting the postal code.

The code looks something like this:

function initialize() {

   var inputField = document.getElementById('input_1_2_5');
   var options = {
        types: ['geocode']
    };
  autoCompleteField = new google.maps.places.Autocomplete(inputField, options);
  google.maps.event.addListener(autoCompleteField, 'place_changed', function() {
    document.getElementById('input_1_2_5').value = getPostalCode(autoCompleteField.getPlace());
  })

      
} // initialize

    function getPostalCode(place){
        for (var i = 0; i < place.address_components.length; i++) {
            for (var j = 0; j < place.address_components[i].types.length; j++) {
              if (place.address_components[i].types[j] == "postal_code") {
                console.log(place.address_components[i]);
                return place.address_components[i].long_name;
              }
            }
          }
    }

Answer №6

To retrieve information from the Google API Place Textsearch endpoint without utilizing JavaScript, you may make use of the following HTTP request:

https://maps.googleapis.com/maps/api/place/textsearch/json?query=971&fields=formatted_address&inputtype=textquery&key=[my_key]

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

The integration of socket.io with static file routing in node.js is encountering issues

I am currently developing a chat application and I have encountered an issue. When the static file routing is functioning correctly, the socket.io for the chat feature throws a "not found" error in the console. http://localhost/socket.io/?EIO=3&tran ...

Unlocking the intricacies of navigating through nested arrays of objects in JavaScript

I need help figuring out how to loop through a nested array of objects in my code. I've tried different approaches but can't seem to grasp how it works. The object data I have looks like this: [ { "restaurantName":"Bron ...

Error in returnTo behavior. The URL is being deleted just before making the post request

I have implemented express-session and included a middleware that assigns the value of req.session.returnTo to the originalUrl. router.post( '/login', passport.authenticate('local', { failureFlash: true, failureRedirect: &ap ...

Leveraging onClick in combination with React's AutoBind

Just started learning React, so please point me towards documentation if I missed anything. I'm attempting to initiate an Ajax call using the onClick method following a tutorial on React. See the code snippet below. doSomething: function() { // ...

Having trouble extracting the ID from the URL using parameters

Just diving into the world of Express JS and MongoDB, so I appreciate your patience with me. Currently following a web development tutorial by Colt Steele. Take a look at my code: app.get("/:id",async(req,res)=> { const id= req.params[&apo ...

Utilize an array value as a parameter for getStaticProps within Next.js

Currently, I am fetching my Youtube playlist using a fetch request and utilizing getStaticProps(). However, I am encountering an issue where my playlist is dependent on the result of an array of objects. export async function getStaticProps(){ const MY_P ...

The process of extracting values from an HTML tag using Angular interpolation

I am working on an Angular application that has the following code structure: <p>{{item.content}}</p> The content displayed includes text mixed with an <a> tag containing various attributes like this: <p>You can find the content ...

Is there a way to retrieve the size of a three.js group element?

Obtaining the dimensions of a mesh (Three.Mesh) can be done using the following code: mymesh.geometry.computeBoundingBox() var bbox = mymesh.geometry.boundingBox; var bboxWidth = bbox.max.x - bbox.min.x; var bboxHeight = bbox.max.y - bbox.min.y; var bbo ...

What is the procedure for verifying the type of an element using chai?

Is there a way to determine if an element is either an "a" tag or a "div" tag? I've tried the following code, but it's not working as expected: it('has no link if required', () => { const wrapper = shallow(<AssetOverlay a ...

Node 18 is having trouble locating NPM and is unable to locate the module './es6/validate-engines.js'

Previously, I attempted to install Node.js without any issues. However, this time around, I am encountering difficulties accessing the npm package. While I can successfully retrieve the version of Node.js after installation, attempting to check npm -v or w ...

Autocomplete Dropdown Options

I am trying to create a dependent autocomplete drop-down that displays suggestions based on any typed letter, rather than just the first letter. For example, if I type "Yo," it should show "New York" in the dropdown. Below is the code I have been using, ...

Having trouble with selecting checkboxes in a div using jQuery? While it may work in IE and Firefox, Chrome seems to be causing issues

In my div, I have several checkboxes placed under labels for formatting purposes. There is a list of checkbox names that need to be checked upon certain actions. Here is the list: var columns= ['2','5','4'] This is the curren ...

Guide to creating a parallax scrolling effect with a background image

My frustration levels have hit an all-time high after spending days attempting to troubleshoot why parallax scrolling isn't functioning for a single image on a website I'm developing. To give you some context, here's the code I've been ...

How to Troubleshoot jQuery AJAX Not Sending JSON Data

I've been attempting to make an ajax request, but it keeps returning with an error response. $('form#contactForm button.submit').click(function () { var contactName = $('#contactForm #contactName').val(); ...

How can you apply filtering to a table using jQuery or AngularJS?

I am looking to implement a filtering system for my table. The table structure is as follows: name | date | agencyID test 2016-03-17 91282774 test 2016-03-18 27496321 My goal is to have a dropdown menu containing all the &apo ...

Personalized sorting to match the unique rendering of cells in Material UI Data Grid

I have integrated the Material UI V4 Data Grid component into my React Js application. The Data Grid component requires two props: rows (list type) and columns (list type). Below is a sample row item: const rows = [ { id: 1, customerName: " ...

What methods does Enzyme have for determining the visibility of components?

I am facing an issue with a Checkbox component in my project. I have implemented a simple functionality to hide the checkbox by setting its opacity : 0 based on certain conditions within the containing component (MyCheckbox) MyCheckBox.js import React fr ...

Experiment with the Users.Get function available in vk-io

I am having an issue with a create command: Ban [@durov] and I encountered an error. Here is how I attempted to solve the problem: let uid = `${message.$match[1]}` let rrr = uid.includes('@') if(rrr == true){ let realid = uid.replace(/[@]/g, &ap ...

Display a loading progress bar with jQuery AJAX as your single page website content loads

I am currently working on a simple web page layout that consists of a navigation bar at the top and a body wrapper. Whenever a user clicks on a link in the navigation bar, I use .load to load the content of the page into the wrapper div. $(this).ajaxStar ...

Once the page is refreshed, the checkbox should remain in its current state and

I have a challenge with disabling all checkboxes on my page using Angular-Js and JQuery. After clicking on a checkbox, I want to disable all checkboxes but preserve their state after reloading the page. Here is an example of the code snippet: $('# ...