How to add google map with Places Autocomplete field in your website?
We use Google Map for some reason in our daily life. We can use this map on our e-commerce or any others website if we want and we can use many beautiful features.
Below I have tried to provide some information about “Place AutoComplete” in these features.
First of all we need API Key to use Google Map features. There are some steps to get this key.
- Go to the Google Maps Platform > Credentials page.Go to the Credentials page
- On the Credentials page, click Create credentials > API key.
The API key created dialog displays your newly created API key. - Click Close.
The new API key is listed on the Credentials page under API keys.
(Remember to restrict the API key before using it in production.)
After receiving the API key. The file used for the page where you use the map on your website "<script src="https://maps.googleapis.com/maps/api/js?key=googleMapApiKeyValue&callback=initMap&libraries=places&v=weekly" defer></script>
"
This script should be used in head tag. Script where “googleMapApiKeyValue” has this message, the collected API key should be used.
Now you need an input on which the address will be given. "<input type="text" name="address" id="address" value="" autocomplete="off" >"
This input field is placed on where you provide the address.
If you want to show it on the map after giving the address. Then need a div in to show your map. I have used this "<div id="map" style="width: 100%;height: 100%;"></div>
"
.
You can use the “<div id=”infowindow-content”><span id=”place-name” class=”title”></span><br /><span id=”place-address”></span></div>” to show the name of the address you are selecting in the map. See the image below will look somewhat like this .
Now you have to create a Jquery file. Where the map’s Function will be called. In the function given below, “Name”, “ID”, “Class” are correct. Your map and autocomplete will work on the functionality.
initMap( );
function initMap( ) {
const map = new google.maps.Map( document.getElementById( "map" ), {
center: { lat: 40.749933, lng: -73.98633 },
zoom: 3,
mapTypeControl: true,
} );
const input = document.getElementById( "address" );
const options = {
fields: [ "address_components", "formatted_address", "geometry", "name" ],
strictBounds: false,
};
const autocomplete = new google.maps.places.Autocomplete(
input,
options
);
// Bind the map's bounds (viewport) property to the autocomplete object,
// so that the autocomplete requests use the current map bounds for the
// bounds option in the request.
autocomplete.bindTo( "bounds", map );
const infowindow = new google.maps.InfoWindow();
const infowindowContent = document.getElementById( "infowindow-content" );
infowindow.setContent( infowindowContent );
autocomplete.addListener( "place_changed", () => {
autocompletePlaceChanged( markers, autocomplete, map, infowindowContent, infowindow );
} );
}
function autocompletePlaceChanged( markers, autocomplete, map, infowindowContent, infowindow ) {
infowindow.close();
deleteOverlays( markers );
markerCluster.clearMarkers();
const place = autocomplete.getPlace();
if ( !place.geometry || !place.geometry.location ) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert( "No details available for input: '" + place.name + "'" );
return;
}
// If the place has a geometry, then present it on a map.
if ( place.geometry.viewport ) {
map.fitBounds( place.geometry.viewport );
} else {
map.setCenter( place.geometry.location );
map.setZoom( 5 );
}
const marker = new google.maps.Marker( {
position: place.geometry.location,
map: map,
icon: includeBaseURL + "/assets/images/iconLocation.svg"
} );
infowindowContent.children[ "place-name" ].textContent = place.name;
infowindowContent.children[ "place-address" ].textContent = place.formatted_address;
infowindow.open( map, marker );
markers.push( marker );
// address data set in hidden field
let address1 = "";
let stateFromAddress = "";
let cityFromAddress = "";
let postcode = "";
for ( const component of place.address_components ) {
// @ts-ignore remove once typings fixed
const componentType = component.types[ 0 ];
switch ( componentType ) {
case "street_number": {
address1 = `${component.long_name} ${address1}`;
break;
}
case "route": {
address1 = `${address1} ${component.short_name}`;
break;
}
case "locality": {
cityFromAddress = component.long_name;
break;
}
case "postal_code": {
postcode = `${component.long_name}${postcode}`;
break;
}
case "postal_code_suffix": {
postcode = `${postcode}-${component.long_name}`;
break;
}
case "administrative_area_level_1": {
stateFromAddress = component.short_name;
break;
}
}
}
// "address1" variable is for street address
// "cityFromAddress" variable is for street city
// "postcode" variable is for street Zip Code
// "stateFromAddress" variable is for street state
}
// To delete the marker is to use this Function
function deleteOverlays( markersArray ) {
for ( var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap( null );
}
}