I have a weird problem when dealing with Google Maps Autocomplete / Places API, it autocompletes the given address just fine:
Street Streetnumber, City, Country = Römerstraße 101, Reith bei Seefeld, Österreich
With the autocompleted value, I am trying to get the address_component data.
const autocomplete = new this.api.places.Autocomplete(
options.input,
{types: ['address'], sessiontoken: sessionToken}
),
inputObj = $(options.input);
inputObj.prop('placeholder', inputObj.data('geocode-autocomplete-placeholder'));
autocomplete.setFields(['address_component']);
autocomplete.addListener('place_changed', () => {
try {
callback(options, {'queryResult': {'res': [autocomplete.getPlace()]}}, this);
} catch (e) {
this.disableGeocoding();
console.log(e);
}
});
Problem is with the returned result, where "city" is missing:
I would expect every information that has been autocompleted to be in the "address_components" data.
Questions:
Why is city missing, and not found in another node, although autocompleted?
How can/should i get the city information?
According to these two links,
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
https://developers.google.com/places/web-service/details
It says locality of response is represents the city part of the address.
So you can see locality part in the response.
Refer those links to get more information.
Related
I am trying to set the types in google places autocomplete and it's getting me crazy!
I want my users to be able to filter there search by typing the address or a establishment they are looking for, but for some reason it's not working properly.
Code I am using:
<script defer src="https://maps.googleapis.com/maps/api/js?libraries=places&key=[my_api_key]"></script>
<script>
var searchInputStart = 'start_address';
start_address = new google.maps.places.Autocomplete((document.getElementById(searchInputStart)), {
types: ['geocode'],
types: ['address'],
types: ['establishment']
});
google.maps.event.addListener(start_address, 'place_changed', function () {
var place_start = start_address.getPlace();
document.getElementById('loc_lat_start').value = place_start.geometry.location.lat();
document.getElementById('loc_long_start').value = place_start.geometry.location.lng();
//get_directions to address
set_route();
});
</script>
If I take out --> types: [address] --> it shows the establishments correct, but not the addresses.
If I take out --> types: [establishement] --> it shows the addresses correct, but not the establishements.
How can my users filter places correctly from typing an address or establishment?
Can anyone help me please? What am I doing wrong?
Thank you.
According to Google Maps API documentation you can set only one type in place autocomplete options.
types Array<string>: The types of predictions to be returned. For a list of supported types, see the developer's guide. If nothing is specified, all types are returned. In general only a single type is allowed. The exception is that you can safely mix the 'geocode' and 'establishment' types, but note that this will have the same effect as specifying no types.
source: https://developers.google.com/maps/documentation/javascript/reference/places-widget#AutocompleteOptions
That means that you can use
start_address = new google.maps.places.Autocomplete(
document.getElementById(searchInputStart),
{
types: ['address']
}
);
or
start_address = new google.maps.places.Autocomplete(
document.getElementById(searchInputStart),
{
types: ['geocode', 'establishment']
}
);
but not all of them in the same options object.
I hope my answer clarifies your doubt.
I am using google auto complete API to search address. Some time after selecting the address it returns wrong latitude and longitude. Then I tried second time its working fine. What could be the cause for this?
The address tried: 21 King Street West, Toronto, ON, Canada
First time the Geo-code coming as below
40.7917804,-74.14482129999999 - wrong (USA Address)
Second time I am getting correct Geo-code
43.64877740000001,-79.37871480000001
var address = new google.maps.places.Autocomplete((document.getElementById(id)),{ types: ['geocode'], componentRestrictions: { country: 'ca' } });
address.addListener('place_changed', function () {
var place = address.getPlace();
place = results[0];
$j('#' + txtboxid).attr({
'data-lat': place.geometry.location.lat(),
'data-lon': place.geometry.location.lng()
});
});
Try changing the type to address which is a precise location for premises: types: ['address']
I am stumped at the moment with the Google Geocoder. Right now, if I query by address, "New York City, NY", I get back results that say the types of the result is "types":["locality","political"] but there is no locality in the address_components. If I query "Tempe, AZ", same thing. If I search for a state, the types is administrative_area_level_1 but it only gives me the country in the address_compenents. Any ideas?
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': "New York City, NY"}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//do stuff
} else {
console.log("Geocode was not successful for the following reason: " + status);
}
My results for "New York City, NY"
[{"address_components":[{"long_name":"New York","short_name":"NY","types":["administrative_area_level_1","political"]},{"long_name":"United States","short_name":"US","types":["country","political"]}],"formatted_address":"New York, USA","geometry":{"bounds":{"south":40.4773991,"west":-74.25908989999999,"north":40.9175771,"east":-73.7002721},"location":{"lat":40.7127837,"lng":-74.00594130000002},"location_type":"APPROXIMATE","viewport":{"south":40.4960439,"west":-74.2557349,"north":40.9152555,"east":-73.7002721}},"place_id":"ChIJOwg_06VPwokRYv534QaPC8g","types":["locality","political"]}]
I am confused as why it is telling me it is type city (locality), but missing the locality attribute. I would expect the locality to be there with the value, "New York" and the formatted address to include the locality in it. Thanks!
Never assume that "locality", or any other type, will always be present in address components.
See gmaps-api-issues #3320 and the longer explanation in the Place Autocomplete Address Form example.
If you really need a specific component, reverse geocoding is the only reliable way to get it always (that is, in places where it actually exists).
I am using "google direction matrix api" to generated direction route between two address points including waypoints. To take address input from user, I am using google's Place Autocomplete.
var options = {
componentRestrictions: {country: 'UK'}
};
var fromText = document.getElementById('start');
var fromAuto = new google.maps.places.Autocomplete(fromText,options);
Issue : This happen only with some addresses
When user start typing like terminal and select address from google suggested address "Terminal 2, Hounslow, United Kingdom"
Suppose this is Source address and another address is "London, UK". After filling these addresses and when I click on "Generate Map" button. An error popup "Direction request failed due to NOT_FOUND".
But if I change address "Terminal 2, Hounslow, United Kingdom" to "Terminal Two, Hounslow, United Kingdom" manually (changing numeric value "2" to alphabet "two"). It works fine.
I dont know why this is happen ? while "Terminal 2, Hounslow, United Kingdom" is auto suggested by the Google.
Any help would be appreciated
As you are using the autocomplete input, I can suggest using the places IDs in Distance Matrix requests instead of the texts.
When user selects a place you can store the corresponding place ID and use it later in distance matrix calculation.
E.g.
https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Terminal%202%2C%20Hounslow%2C%20United%20Kingdom&components=country%3AGB&key=YOUR_API_KEY
will return place ID ChIJu8J5RChydkgROPKSCZojxCg
https://maps.googleapis.com/maps/api/place/autocomplete/json?input=London%2C%20UK&key=YOUR_API_KEY
will return place ID ChIJdd4hrwug2EcRmSrV3Vo6llI
Now execute Distance Matrix request for place IDs:
https://maps.googleapis.com/maps/api/distancematrix/json?origins=place_id%3AChIJu8J5RChydkgROPKSCZojxCg&destinations=place_id%3AChIJdd4hrwug2EcRmSrV3Vo6llI&key=YOUR_API_KEY
The response is:
{
"destination_addresses":[
"London, UK"
],
"origin_addresses":[
"London Heathrow Terminal 2, Compass Centre, Nelson Road, Longford, Hounslow TW6 2GW, UK"
],
"rows":[
{
"elements":[
{
"distance":{
"text":"28.7 km",
"value":28661
},
"duration":{
"text":"49 mins",
"value":2940
},
"status":"OK"
}
]
}
],
"status":"OK"
}
You can do the similar thing in Maps JavaScript API. Please have a look at this example that calculates routes using the directions service with place IDs:
http://jsbin.com/xuyisem/1/edit?html,output
You can easily apply this approach for distance matrix.
Hope it helps!
I am using a gmap autocomplete and sometimes the user doesn't hit any choice in the suggestion list. For example he types "Paris" in the input field and believes the search will be performed with Paris, however has the 'place_changed' of the gmap autcomplete was never called, the search cannot be perfomed.
How can I select by default the first choice of the suggestion list when the user doesn't make any choice ? I believe I could adapt the solution provided for the "enter issue" described here (Google maps Places API V3 autocomplete - select first option on enter) with a blur event handling, however this doesn't work.
Any hint ?
I think this is kind of defeating the purpose of the auto complete.
You could just retrieve the autocomplete predictions pro grammatically like so:
function initialize()
{
var service = new google.maps.places.AutocompleteService();
service.getQueryPredictions({ input: 'some address' }, callback);
}
function callback(predictions, status)
{
if (status != google.maps.places.PlacesServiceStatus.OK)
{
alert(status);
return;
}
// Take the first result
var result = predictions[0]
// do as you wish with the result
}
Hope that helps