How to add working place autocomplete by passing paramerter - javascript

Im not able to get place autocomplete so what should i do?
<input class="form-control" name="loc[]" onkeypress="return initialize(input);" required>
js code:
function initialize(input) {
var autocomplete = new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', initialize);

You don't need to add onkeypress event, Autocomplete will handle that for you. Just pass your input element and some options to the Autocomplete constructor.
Example:
var input = document.getElementById('searchTextField');
var options = {
types: ['(cities)'],
componentRestrictions: {country: 'us'}
};
autocomplete = new google.maps.places.Autocomplete(input, options);
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?&libraries=places"></script>
<input id="searchTextField" type="text" size="50" placeholder="Cities in US">
-- Update --
Using dynamically created input elements.
var form = document.getElementsByTagName('form')[0];
var options=[{placeholder:"Cities in US",options:{types:["(cities)"],componentRestrictions:{country:"us"}}},{placeholder:"Cities in FR",options:{types:["(cities)"],componentRestrictions:{country:"fr"}}}];
function addAutocomplete (elem, options) {
autocomplete = new google.maps.places.Autocomplete(elem, options);
}
function crateAutoCompleteInputs ( count, optoins ) {
for (var i = 0; i < count; i++) {
var input = document.createElement('input');
input.type = 'text';
input.placeholder = optoins[i].placeholder;
form.appendChild(input);
addAutocomplete(input, options[i].options)
}
}
crateAutoCompleteInputs(2, options)
input {
margin-right: 12px;
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?&libraries=places"></script>
<form></form>

Related

Restrict geocode autocomplete to a contry

I need help with google places autocomplete API. I am getting the autocomplete address and lat and long from the API. Without restriction to a country the code works fine and I get the desired address, lat and long. However when I try to add country restriction, the lat and long fails to send along with my form.
Here is the working code without country restriction:
JS
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places"></script>
<script>
function initialize() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
document.getElementById('searchTextField').value = place.name;
document.getElementById('latitude').value = place.geometry.location.lat();
document.getElementById('longitude').value = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Here is the code with country restriction that I need help with:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places"></script>
<script>
function initialize() {
autocomplete = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */(document.getElementById('searchTextField')),
{types: ['geocode'],
componentRestrictions: {country: 'us'}});
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
document.getElementById('searchTextField').value = place.name;
document.getElementById('latitude').value = place.geometry.location.lat();
document.getElementById('longitude').value = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Here's the lines that's causing the problem:
autocomplete = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */(document.getElementById('searchTextField')),
{types: ['geocode'],
componentRestrictions: {country: 'us'}});
My form:
<html>
<head>
<title>Address Demo</title>
</head>
<body>
<form action="address.php" method="GET">
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading" style="background-color:#00CDCD">
<h2 class="panel-title">Address</h2>
</div>
<div class="panel-body">
<input name="address" id="searchTextField" placeholder="Enter area name" type="text" class="form-control" required>
<input type="hidden" name="latii" id="latitude">
<input type="hidden" name="lngii" id="longitude">
<input type="submit" name="submit" value="SUBMIT" class="bookingbtn top-10 bottom-20">
</div>
</div>
</form>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</body>
</html>
address.php
<?php
$address = $_GET['address'];
$latii = $_GET['latii'];
$lngii = $_GET['lngii'];
echo "$address </br>";
echo "$latii </br>";
echo "$lngii";
?>
Thanks for your help in advance.
I finally got it to work. Thanks to the answer here How to limit google autocomplete results to City and Country only.
My working code is:
<script>
function initialize() {
var options = {
types: ['geocode'],
componentRestrictions: {country: "us"}
};
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
document.getElementById('searchTextField').value = place.name;
document.getElementById('latitude').value = place.geometry.location.lat();
document.getElementById('longitude').value = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

Google Address API for dynamic input type [duplicate]

I am using the Google Maps API on my page, the page asks the user to fill out your "Current Address" and the "New Address".
I can get the autocomplete to work on the 1st address but it does not work for the second address, I have done lots of research and looked at simular posts on stackoverflow but I cannot find anyone who has had the same problem.
Here is my code;
<div id="locationField">
<input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text"></input>
</div>
<div id="addressone">
<input type="text" id="street_number" name="street_number"></input>
<input type="text" id="route" name="street_name"></input>
<input type="text" id="locality" name="town_city"></input>
<input type="text" id="postal_code" name="postcode"></input>
<input type="text" id="country" name="country"></input>
</div>
<div id="locationField2">
<input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text"></input>
</div>
<div id="addresstwo">
<input type="text" id="street_number2" name="street_number2"></input>
<input type="text" id="route2" name="street_name2"></input>
<input type="text" id="locality2" name="town_city2"></input>
<input type="text" id="postal_code2" name="postcode2"></input>
<input type="text" id="country2" name="country2"></input>
</div>
<script>
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
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);
}
// [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;
}
}
}
// [END region_fillform]
// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
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());
});
}
}
// [END region_geolocation]
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC7XIOPnu4WS_fBaIDPkCBdYa3MxdIcdK4&signed_in=true&libraries=places&callback=initAutocomplete" async defer></script>
</div>
You need to hande the two autocomplete inputs. Here is a generalized version of fillInAddress that will handle multiple autocomplete objects with fields with a unique extension (the "2" in your second version of the form):
function fillInAddress(autocomplete, unique) {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
if(!!document.getElementById(component + unique)){
document.getElementById(component + unique).value = '';
document.getElementById(component + unique).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] && document.getElementById(addressType + unique)) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType + unique).value = val;
}
}
}
Call it like this:
// Create the autocomplete object, restricting the search to geographical
// location types.
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', function () {
fillInAddress(autocomplete, "");
});
// Create the second autocomplete object, restricting the search to geographical
// location types.
autocomplete2 = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */
(document.getElementById('autocomplete2')), {
types: ['geocode']
});
autocomplete2.addListener('place_changed', function () {
fillInAddress(autocomplete2, "2");
});
working code snippet:
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.
var placeSearch, autocomplete, autocomplete2;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
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', function() {
fillInAddress(autocomplete, "");
});
autocomplete2 = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */
(document.getElementById('autocomplete2')), {
types: ['geocode']
});
autocomplete2.addListener('place_changed', function() {
fillInAddress(autocomplete2, "2");
});
}
function fillInAddress(autocomplete, unique) {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
if (!!document.getElementById(component + unique)) {
document.getElementById(component + unique).value = '';
document.getElementById(component + unique).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] && document.getElementById(addressType + unique)) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType + unique).value = val;
}
}
}
google.maps.event.addDomListener(window, "load", initAutocomplete);
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());
});
}
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="locationField">
<input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
</div>
<div id="addressone">
<input type="text" id="street_number" name="street_number" />
<input type="text" id="route" name="street_name" />
<input type="text" id="locality" name="town_city" />
<input type="text" id="administrative_area_level_1" name="administrative_area_level_1" />
<input type="text" id="postal_code" name="postcode" />
<input type="text" id="country" name="country" />
</div>
<div id="locationField2">
<input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
</div>
<div id="addresstwo">
<input type="text" id="street_number2" name="street_number2" />
<input type="text" id="route2" name="street_name2" />
<input type="text" id="locality2" name="town_city2" />
<input type="text" id="administrative_area_level_12" name="administrative_area_level_12" />
<input type="text" id="postal_code2" name="postcode2" />
<input type="text" id="country2" name="country2" />
</div>
This works, uses jQuery.
function initMultiComplete() {
jQuery('.maps-complete').each(function(){
var id = jQuery(this).prop('id');
var $this = jQuery(this);
var parent = jQuery(this).parent('div');
var jautocomplete = new google.maps.places.Autocomplete(document.getElementById(id), {types: ['geocode']});
jautocomplete.addListener('place_changed', function () {
var place = jautocomplete.getPlace();
var address = $this.val();
var lat = place.geometry.location.lat();
var lng = place.geometry.location.lng();
jQuery( '.maps-autocomplete-lat', parent ).val(lat);
jQuery( '.maps-autocomplete-lng', parent ).val(lng);
});
});
}
script calls initMultiComplete as callback, and is loaded w/ async defer:
https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places&callback=initMultiComplete
This is an old question but I thought I'd post my solution to this in case it's helpful to others in the future. My solution handles any number of maps api autocomplete fields on a page. You'd need tag all autocomplete fields with a class name, in my case I've used the class name "address".
Now grab the collection of fields:
var input = document.getElementsByClassName('address');
for (var x = 0; x < input.length; x++) {
addListener(input[x]);
}
which calls a function called "addListener"
function addListener(el) {
var autocomplete = new google.maps.places.Autocomplete(el);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
// Do whatever you want in here e.g.
// var place = autocomplete.getPlace();
});
}
Because it's a collection, you should be able to add any number of autocomplete fields to a page. Though naturally, you should check for undefined on the collection just in case you happen to have no autocomplete fields on the page.

I want to format my Google API autocomplete data

I am using Google API for address search and I got it completely.
I tried to format the data using CSS and its look something like this:
Here is my CSS code:
.pac-container:after {
/* Disclaimer: not needed to show 'powered by Google' if also a Google Map is shown */
background-image: none !important;
height: 0px;
}
.pac-item-query
{
color:red;
}
.pac-item
{
padding:20px;
}
but i want my address box to be looking like this
This is the code that call api and display result:
function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
callDebugger();
autocomplete = new google.maps.places.Autocomplete(
(
document.getElementById('autocomplete')), {
types: ['geocode'],
componentRestrictions: countryRestrict
});
// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
document.getElementById('countrys').addEventListener(
'change', setAutocompleteCountry);
}
function fillInAddress() {
callDebugger();
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
var check = [];
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++) {
callDebugger();
var addressType = place.address_components[i].types[0];
check.push(addressType);
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
// console.log(zipcode);
zipcode = check.includes("postal_code");
sessionStorage.setItem("zipcode", zipcode);
// console.log(check);
}
And this is HTML:
<div class="form-field half">
<label for="usr">Business Address</label>
<input id="autocomplete" type="text" class="w-input" data-rule-required="true" name="address" placeholder="Address" onFocus="geolocate()" />
</div>

How to change input field for google autocomplete

How can I change input field for autocomplete (Google Maps API)?
autocomplete = new google.maps.places.Autocomplete(inputField, options);
function func1() {
// switch element inputField to inputField2 (how?)
}
Try this:
<script
src="https://maps.googleapis.com/maps/api/js?libraries=places">
</script>
<input type="text" id="loc1">
<input type="text" id="loc2">
<input type="text" id="loc3">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function initialize(){
var autocomplete1 = new google.maps.places.Autocomplete($("#loc1")[0], {});
var autocomplete2 = new google.maps.places.Autocomplete($("#loc2")[0], {});
var autocomplete3 = new google.maps.places.Autocomplete($("#loc3")[0], {});
google.maps.event.addListener(autocomplete1, 'place_changed', function () {
var place = autocomplete1.getPlace();
console.log(place.address_components);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I think this would be helpful : autofill. Create a autocomplete variable each with inputbox and create a single listener or multiple listener.
I hope this helps

How to remove some extra detail in google address auto-complete?

I want to use textbox with id 'autocomplete' only for searching and after searching i d'dnt want to store whole address in first input box i just want to store postal_code in first inputbox with id autocomplete, not in
text-box with id 'postal_code' and one more thing it should also possible user can input postal_code manually in textbox with id autocomplete.
<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete Address Form</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<script>
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.
var placeSearch, autocomplete;
var componentForm = {
postal_code: 'short_name'
};
function initialize() {
// Create the autocomplete object, restricting the search
// to geographical location types.
var options = {
componentRestrictions: {country: "in"}
};
autocomplete = new google.maps.places.Autocomplete(
/** #type {HTMLInputElement} */(document.getElementById('autocomplete')),options);
// When the user selects an address from the dropdown,
// populate the address fields in the form.
google.maps.event.addListener(autocomplete, 'place_changed', function() {
fillInAddress();
});
}
// [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;
}
}
}
// [END region_fillform]
// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
// [END region_geolocation]
</script>
</head>
<body onload="initialize()">
<div id="locationField">
<input id="autocomplete" placeholder="Enter your address"
onFocus="geolocate()" type="text"></input>
</div>
<table id="address">
<tr>
<td class="label">Pin</td>
<td class="slimField"><input class="field" id="postal_code"
disabled="true" ></input></td>
</tr>
</table>
</body>
</html>
Try this code
<html>
<head>
<title>Place Autocomplete Address Form</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<script>
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.
var placeSearch, autocomplete;
var componentForm = {
postal_code: 'short_name'
};
function initialize() {
// Create the autocomplete object, restricting the search
// to geographical location types.
var options = {
componentRestrictions: {country: "in"}
};
autocomplete = new google.maps.places.Autocomplete(
/** #type {HTMLInputElement} */(document.getElementById('autocomplete')),options);
// When the user selects an address from the dropdown,
// populate the address fields in the form.
google.maps.event.addListener(autocomplete, 'place_changed', function() {
fillInAddress();
});
}
// [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] && addressType == "postal_code") {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById("autocomplete").value = val;
}
}
}
// [END region_fillform]
// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
// [END region_geolocation]
</script>
</head>
<body onload="initialize()">
<div id="locationField">
<input id="autocomplete" placeholder="Enter your address"
onFocus="geolocate()" type="text"></input>
</div>
<table id="address">
<tr>
<td class="label">Pin</td>
<td class="slimField"><input class="field" id="postal_code"
disabled="true" ></input></td>
</tr>
</table>
</body>
</html>
https://jsfiddle.net/qqptf2y5/1/

Categories