Generally people find annoying to fill the web forms, while filling manually all the details may be error-prone and may lead to the error in validation. So here is the example by which we can reduce the manually filling of addresses by using the Google autocomplete API.
Benefits of Google Address AutoComplete :
1. Reduces Validation Issues.
2. Enable Quick filling of the fields.
3. Ensures Accuracy and many more.
Now here are the steps to Integrate the API In Magento 2:
Step 1 : Create a basic structure of Magento 2 module ,
please check this link for the reference : https://webkul.com/blog/create-hello-module-in-magento2/
Steps 2 : I want to add the address field in registration page , We need to create the layout handle first in this path : app/code/<vendor_name>/<module_name>/view/frontend/layout/customer_account_create.xml
<?xml version="1.0"?> <!-- /** * Webkul Software. * * @category Webkul * @package Webkul_Autofill * @author Webkul * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com) * @license https://store.webkul.com/license.html */ --> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceContainer name="content"> <block class="<vendor_name>\<module_name>\Block\Autofillform" name="autofill_form_register" template="autofill.phtml" ></block> </referenceContainer> </body> </page>
Step 3 : Create .phtml file in this path : app/code/<vendor_name>/<module_name>/view/templates/autofill.phtml
<div class="formcontainer"> <div class="field" id="wk-store-address-box"> <label for="wk-storeaddress" class="label"> <span>Store Address </span> </label> <div class="input-box"> <input type="text" name="store_address" class="input-text" id="autocomplete" placeholder="Enter Store Address here." title="Enter Store Address here." autocomplete="off"> </div> </div> <input type="hidden" name="street_number" class="input-text" id="street_number" autocomplete="off"> <input type="hidden" name="street_name" class="input-text" id="street_name" autocomplete="off"> <input type="hidden" name="locality" class="input-text" id="locality" autocomplete="off"> <input type="hidden" name="administrative_area_level_1" class="input-text" id="administrative_area_level_1" autocomplete="off"> <input type="hidden" name="postal_code" class="input-text" id="postal_code" title="Enter Store Address here." autocomplete="off"> </div> <script> require.config({ map: { '*': { 'googleMapPlaceLibrary': 'https://maps.googleapis.com/maps/api/js?key=<?php echo $block->getGoogleApiKey()?>&v=3.exp&libraries=places' } } }); </script> <script type="text/x-magento-init"> { "*": { "autofill": {} } } </script>
Step 4 : Create the block From where I have retrieved the Google API Key .
app/code/<vendor_name>/<module_name>/Block/Autofill.php
<?php /** * @category Webkul * @package Webkul_Autofill * @author Webkul * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com) * @license https://store.webkul.com/license.html */ namespace Webkul\Autofill\Block; use Magento\Framework\View\Element\Template\Context; class Autofillform extends \Magento\Framework\View\Element\Template { const API_KEY= 'autofill/general_settings/google_api_key'; /** * @var ScopeConfig */ public $_scopeConfig; /** * @param Context $context, * @param array $data = [] */ public function __construct( Context $context, array $data = [] ) { $this->_scopeConfig = $context->getScopeConfig(); parent::__construct($context, $data); } /** * Return ajax url for button. * * @return string */ public function getGoogleApiKey() { return trim($this->_scopeConfig->getValue(self::API_KEY)); } }
Step 5 : create requirejs-config.js file in the following path : app/code/<vendor_name>/<module_name>/view/frontend/requirejs-config.js
<!-- /** * @category Webkul * @package Webkul_Autofill * @author Webkul * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com) * @license https://store.webkul.com/license.html */ --> var config = { map: { '*': { autofill : 'Webkul_Autofill/js/autofill' } } };
Step 6: Create the js file to Integration the Google address autofill API.
You can modify the file as per your convenience.
app/code/<vendor_name>/<module_name>/view/frontend/web/js/autofill.js
/** * Webkul autofill address form script * @category Webkul * @package Webkul_Autofill * @author Webkul * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com) * @license https://store.webkul.com/license.html */ define( [ "jquery", "mage/translate", "Magento_Ui/js/modal/modal", "googleMapPlaceLibrary" ], function ($, $t, modal) { "use strict"; $.widget( 'autofill.register', { _create: function () { var placeSearch, autocomplete; var componentForm = { street_number: 'street_number', route: 'street_name', locality: 'city', administrative_area_level_1: 'state', country: 'country', postal_code: 'postal_code' }; $('#form-validate .fieldset.create.info').append($('.formcontainer')); initAutocomplete(); function fillInAddress() { // Get the place details from the autocomplete object. var place = autocomplete.getPlace(); // Get each component of the address from the place details // and fill the corresponding field on the form. for (const component of place.address_components) { const componentType = component.types[0]; switch (componentType) { case "street_number": { document.getElementById("street_number").value = component.long_name; break; } case "route": { document.getElementById("street_name").value = component.long_name; break; } case "locality": { document.getElementById("locality").value = component.long_name; break; } case "administrative_area_level_1": { document.getElementById("administrative_area_level_1").value = component.long_name; break; } case "postal_code": { document.getElementById("postal_code").value = component.long_name; break; } } } } function geolocate () { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var geolocation = { lat: position.coords.latitude, lng: position.coords.longitude }; var circle = new google.maps.Circle({ center: geolocation, radius: position.coords.accuracy }); autocomplete.setBounds(circle.getBounds()); }); } } function initAutocomplete () { autocomplete = new google.maps.places.Autocomplete( /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')), {types: ['geocode']}); // When the user selects an address from the dropdown, populate the address // fields in the form. autocomplete.addListener('place_changed', fillInAddress); } } } ); return $.autofill.register; });
This is a complete reference to integrate the Google Address API in Magento 2,
Note : You can integrate this API and checkout page as well while filling the shipping and address information. Here is the google docs link from where you can read more about Google API.
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform?hl=fr
Where do you generate the value for this line to make sense: getValue(‘autofill/general_settings/google_api_key’)