Google Maps API JS - Place autocomplete with two combined fields - javascript

I come to you because I can not use the autocomplete place function instead of Google maps JS api v3 as I would like.
Indeed, I would like to implement autocompletion on a field by adding the value of another.
Concretely, I would like to have two fields, one for the company name, the other for the address. I would like autocompletion is performed only on the address fields but taking into consideration the company name.
So if I fill "Company XYZ" in the company field and "New York, USA" in the address, it should lookup "Company XYZ, New York, USA".
Classical example with one input :
Function JS :
function initialize() {
// Create the autocomplete object, restricting the search
// to geographical location types.
autocomplete = new google.maps.places.Autocomplete(
/** #type {HTMLInputElement} */(document.getElementById('addr')),
{ types: ['establishment', 'geocode'] });
// 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();
});
}
HTML Form :
<input class="field" id="company_name" />
<input class="field" id="addr" />
In your opinion is it possible? If so, how?
With thanks.

You can use the Autocomplete Service and get query predictions for the values of both fields.
See https://developers.google.com/maps/documentation/javascript/examples/places-queryprediction
var autocompleteService = new google.maps.places.AutocompleteService();
getPlacePredictions(document.getElementById('company').value + ', ' + document.getElementById('address').value);
function getPlacePredictions(search) {
autocompleteService.getPlacePredictions({
input: search,
types: ['establishment', 'geocode']
}, callback);
}
Below is a full example of a custom autocomplete predictions list (styled based on Google implementation), with search highlighting, place details request and display on the map with a marker.
JSFiddle demo

Related

How can i get address components using Google's AutocompleteService via JavaScript?

Google offers different ways to use the Place Autocomplete API. Two of these being the Autocomplete and AutocompleteService classes. Whenever I use the Autocomplete class I get the address components without a problem. However, whenever I use the AutocompleteService the address components are missing. I do get an address but not in the same way I do with Autocomplete (I can parse into city, street, state, etc.).
Is there a way I can get the address components field using AutocompleteService WITHOUT making an additional call with the place ID ?
Autocomplete example
function initAutocomplete() {
autocomplete = new google.maps.places.Autocomplete(document.getElementById('search'), {
componentRestrictions: { country: ["us", "ca"] },
fields: ["address_components", "geometry"],
types: ["address"],
});
autocomplete.addListener("place_changed", () => {
const place = autocomplete.getPlace(); // Includes Address Components and Geometry (Lat and Lng)
});
}
AutocompleteService example
function initAutocompleteService() {
const service = new google.maps.places.AutocompleteService();
service.getPlacePredictions({
input: "1600 Amphitheatre",
componentRestrictions: {
country: 'us'
},
types: ['address']
}, (predictions, status) => {
console.log(predictions); // It shows the address a single string but missing address components
});
}
Is there a way I can get the address components field using AutocompleteService WITHOUT making an additional call with the place ID ?
Short answer: No, you can't.
If you are worried about billing, you should use Session tokens.
As per the documentation:
AutocompleteService.getPlacePredictions() uses session tokens to group together autocomplete requests for billing purposes.
The interesting part:
You can use the same session token to make a single Place Details request on the place that results from a call to AutocompleteService.getPlacePredictions(). In this case, the autocomplete request is combined with the Place Details request, and the call is charged as a regular Place Details request. There is no charge for the autocomplete request.
Google provides an example on how to create the Session token:
// Create a new session token.
var sessionToken = new google.maps.places.AutocompleteSessionToken();
// Pass the token to the autocomplete service.
var autocompleteService = new google.maps.places.AutocompleteService();
autocompleteService.getPlacePredictions({
input: 'pizza near Syd',
sessionToken: sessionToken
},
displaySuggestions);
When user selects a place, you can reuse that same session token to retrieve the place details with the fields you are interested in, in order to get billed only for the place details request (as stated above).
You might also want to read Cost optimization best practices.
Programmatic implementation
Use a session token with your Place Autocomplete requests. When requesting Place Details about the selected prediction, include the following parameters:
The place ID from the Place Autocomplete response
The session token used in the Place Autocomplete request
The fields parameter specifying the place data fields you need
As you can see, the PlaceDetailsRequest interface takes an optional sessionToken parameter.

I have a custom Address Book field on sales orders for freight bill purposes, but I can't source the full address to a text field in NetSuite

We frequently need to have a third address drop down on our sales orders indicating where to send shipping bills. To accomplish this, I have created two custom fields, custbody_vcc_3_p_b_a and custbody_vcc_xtra_add_txt.
The first field is a list/record type tied to the address book. The second is a text area.
I need to filter the first field based on the entity and then have the selected address book record's full address populate into the text area field.
The sourcing & filtering tab in the address book field is no good, it will not allow me to filter on entity, so I need to filter using script somehow.
As for the sourcing, NetSuite is giving me an error message indicating my address book field is not compatible with the getSubrecord function.
/**
*#NApiVersion 2.x
*#NScriptType ClientScript
*/
define(['N/record'],
function(record) {
function fieldChanged(context) {
var subrec = currentRecord.getSubrecord({
fieldId: 'custbody_vcc_3_p_b_a' //address book field
});
var address = subrec.getValue({
fieldId: 'address' //I've also tried addrtext
});
if (recordfieldname === 'custbody_vcc_3_p_b_a')
currentRecord.setValue({
fieldId: 'custbody_vcc_xtra_add_txt',
value: address
});
};
return {
fieldChanged: fieldChanged,
};
});
The error is SSS_INVALID_FIELD_ON_SUBRECORD_OPERATION. When I tried the script as a 1.0 API as a user event script the error was similar, but more explicit.
So you want to copy the text of the address selected in custbody_vcc_3_p_b_a into your text area (custbody_vcc_xtra_add_txt)?
try
var address = subrec.getValue({
fieldId: 'shipaddress'
});

Google place autocomplete- get location name and address in two different field

Suppose, I have two fields, Location Name and Location Address. Now, If I type Sydney Opera House in the field location name and select an address from dropdown then Sydney Opera House should appear in location name and Location Address should be autocompleted with the address- Bennelong Point, Sydney NSW 2000, Australia
I can get the location name from the full address, but not quite sure how to show the rest of the address in the Location Address field. Here is my code: PLUNKER
I have a directive named place-autocomplete.directive, where in place changed listener I am doing this:
google.maps.event.addListener(this.autocomplete, 'place_changed', ()=> {
input.value=input.value.split(',')[0]; //this is location name
var inputAdd=input.value.split(',')[1];// the address, how should I pass this?
var place = this.autocomplete.getPlace();
this.invokeEvent(place);
});
You can either bind the input type (Venue Address) to [this.address]
Or can set the value of that field like below
getAddress(place: Object) {
this.address = place['formatted_address'];
document.getElementById('<id of the Venue Address text box>').value=this.address;
}

Get ZIP codes of particular country using google map

I am using maps.googleapis.com/maps/api in codeigniter to display auto complete location when user types zip address. I have two input field from first user will select country and in second filed he will type his zip code and from google autocomplete he will select his address.
var directionsService = new google.maps.DirectionsService();
google.maps.event.addDomListener(window, 'load', function () {
new google.maps.places.SearchBox(document.getElementById('zip'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
It is working fine but now I want to show zip codes only from selected country. Means if user select Australia as country and type zip like 2127 then google api should show addresses in Australia having 2127 in address
Google maps JS api provides two kinds of widgets for autocomplete. One is google.maps.places.SearchBox you are using, which only offers restriction by Latitude and Longitude bounds and then there is google.maps.places.Autocomplete which provides country restriction (and much more), eg. like this:
var input = document.getElementById('searchTextField');
var options = {
componentRestrictions: {country: 'au'}
};
autocomplete = new google.maps.places.Autocomplete(input, options);
For more information about advantages/disadvantages of both approaches see the docs (check section "Summary of classes") and choose the best approach for your needs.
I would also add to previous answer that there is a feature request in the public issue tracker to extend components restrictions for places autocomplete (make it similar to Geocoding API)
https://code.google.com/p/gmaps-api-issues/issues/detail?id=4433
If you are interested in this feature request please star it to express your interest and receive updates from Google.

Google autocomplete API returns places in my state first instead of the most "expected" places

I am using Google Autocomplete when entering addresses, this is the simple implementation:
autocomplete_origin_address = new google.maps.places.Autocomplete(
document.getElementById('origin_address'), {types: ["geocode"]}
);
When I start typing "Lon", the first suggested place is Long Beach, CA, and the next one is "London United Kingdom" - that's just an example.
I am located in California. Generally said, when I start typing an address, the places that are offered to my are located in CA. How do I get offered the places in the whole North America?
I tried to modify my autocomplete setup, like:
autocomplete_origin_address = new google.maps.places.Autocomplete(
document.getElementById('origin_address'), {types: ["route", "geocode"]}
);
But in this case the autocomplete didn't offer anything (even when I kept in the array only route.
How to set up autocomplete to suggest the places not mainly from CA, but from the North America?
Try this:
navigator.geolocation.getCurrentPosition(position=> {
$.getJSON("https://maps.googleapis.com/maps/api/geocode/json?latlng="
+ position.coords.latitude + "," + position.coords.longitude
+ "&sensor=false").then(data=> {
for (let component of data.results[0].address_components) {
if (component.types.includes("country")) {
new google.maps.places.Autocomplete(
$('#origin_address')[0], {types: ["geocode"],
componentRestrictions: {country: component.short_name}}
);
break;
}
}
})
})
Firstly it gets current location using broswser's Geolocation API. Then it makes request to Google Maps API to get the country based on latitude and longitude. Then it initializes autocomplete, limiting it to this country.
See JS Fiddle demo.

Categories