Google Geocoder Missing Type Address Component - google-maps

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).

Related

Google Autocomplete "city" is missing but shown in autocomplete form input

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.

Google auto complete API sometime returning wrong geocode

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']

Google Map : Auto suggested address issue

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!

Distance calculate from autocomplete inputs: certain locations in API dropdown selection don't get assigned usuable location data

I have a simple distance calculator on a page I'm making, and the distance is calculated between 2 points from an input field using data from google maps (Places Autocomplete).
I load the info from google using this:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places">
I've also tried adding the adsense and geometery libraries seperated by comma, but from the documentation it doesn't seem like I really need those for this problem. Without them the places I want to see do appear, it's just that sometimes they aren't used.
The dropdown does function and I can see the results I want to use. Most of the time it will, but for certain vague places it does not. For example, the distance from X to "Tufts University, Medford, MA, United States" (autocompleted by google) will calculate just fine. However, from X to "Foxwoods Resort Casino, Ledyard, CT, United States" (also autocompleted by google) will not. These are both large campus-style layouts, and I understand that it's not an exact address, but in most cases the broadest name for a large multi-address destination will work fine. So why not on Foxwoods, for example? It appears in the autocomplete drop down menu provided by google, so why doesn't it have some kind of address value?
The options I'm using for the map are pretty standard, I have it restricted to the US but that's about it. Except:
travelMode: google.maps.DirectionsTravelMode.DRIVING
That's how it uses the points to get the mileage, unsure if it's related but that's the only other thing I can find that might change behavior.
If there's any more info I need to provide let me know, I'm wondering how to lick this and I just can't. I'm hoping that it's possible without going into a whole geolocation thing :P
Thanks!
edit: here's the distance calculation function using the "start" and "end" autocompleted inputs:
var fromText = document.getElementById('start');
var fromAuto = new google.maps.places.Autocomplete(fromText);
var toText = document.getElementById('end');
var toAuto = new google.maps.places.Autocomplete(toText);
function calcRoute() {
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
var distanceInput = document.getElementById("distance");
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
distanceinkm = response.routes[0].legs[0].distance.value / 1000;
distanceinmiles = (distanceinkm * 0.621371);
distanceinmiles = distanceinmiles.toFixed(2);
distanceInput.value = distanceinmiles;
}
});
"Foxwoods Resort Casino, Ledyard, CT, United States" is a place, it can't be found by the geocoder or the directions service. The autocomplete service returns the coordinates associated with the result. Use those to compute the route.
Example of getting coordinates from the documentation (as pointed out by Scott Selby in the comments)

google map autocomplete select first entry in list by default

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