Google autocomplete suggestion without country name - google-maps-api-3

I am looking for a possibility to get suggestions without country name.
I have the following js code:
var options = {
types: ['(cities)'],
componentRestrictions: {country: "us"}
};
autocomplete = new google.maps.places.Autocomplete((document.getElementById('autocomplete')), options);
The result is e.g. Austin TX, USA
Now I want to have for that example only
Expect result is e.g. Austin TX
See more info following image link
click here
Do you have an idea? Thanks. Dhiraj Gangal

I investigated more on this and I have more Info here:
The Service to use:
https://developers.google.com/maps/documentation/javascript/places-autocomplete?hl=de#place_autocomplete_service
The AutocompletePrediction defines what the service returns https://developers.google.com/maps/documentation/javascript/reference?hl=de#AutocompletePrediction
and a PredictionTerm here https://developers.google.com/maps/documentation/javascript/reference?hl=de#PredictionTerm is one part of the "description" that gets intially displayed as result.
The interesting part is actually the PredictionTerm which is a part of the whole place suggestion.
If you look into this example: https://developers.google.com/maps/documentation/javascript/examples/places-queryprediction
You could easily grab each PredictionTerm of the suggestion results like in the following snippet:
predictions.forEach(function(prediction) {
var li = document.createElement('li');
var city = prediction.terms[2];
var content = "Results: "+city;
li.appendChild(document.createTextNode(prediction.description));
document.getElementById('results').appendChild(li);
});
I made an example: https://jsfiddle.net/yfkpvf72/1/

Related

How to export a table as google sheet in Google app maker using a button

I've looked extensively and tried to modify multiple sample sets of codes found on different posts in Stack Overflow as well as template documents in Google App Maker, but cannot for the life of me get an export and en email function to work.
UserRecords table:
This is the area where the data is collected and reviewed, the populated table:
These are the data fields I am working with:
This is what the exported Sheet looks like when I go through the motions and do an export through the Deployment tab:
Lastly, this is the email page that I've built based on tutorials and examples I've seen:
What I've learned so far (based on the circles I'm going round in):
Emails seem mostly straight forward, but I don't need to send a message, just an attachment with a subject, similar to using the code:
function sendEmail_(to, subject, body) {
var emailObj = {
to: to,
subject: subject,
htmlBody: body,
noReply: true
};
MailApp.sendEmail(emailObj);
}
Not sure how to change the "body" to the exported document
To straight up export and view the Sheet from a button click, the closest I've found to a solution is in Document Sample but the references in the code speak to components on the page only. I'm not sure how to modify this to use the table, and also what to change to get it as a sheet instead of a doc.
This may seem trivial to some but I'm a beginner and am struggling to wrap my head around what I'm doing wrong. I've been looking at this for nearly a week. Any help will be greatly appreciated.
In it's simplest form you can do a Google sheet export with the following server script (this is based on a model called employees):
function exportEmployeeTable() {
//if only certain roles or individuals can perform this action include proper validation here
var query = app.models.Employees.newQuery();
var results = query.run();
var fields = app.metadata.models.Employees.fields;
var data = [];
var header = [];
for (var i in fields) {
header.push(fields[i].displayName);
}
data.push(header);
for (var j in results) {
var rows = [];
for (var k in fields) {
rows.push(results[j][fields[k].name]);
}
data.push(rows);
}
if (data.length > 1) {
var ss = SpreadsheetApp.create('Employee Export');
var sheet = ss.getActiveSheet();
sheet.getRange(1,1,data.length,header.length).setValues(data);
//here you could return the URL for your spreadsheet back to your client by setting up a successhandler and failure handler
return ss.getUrl();
} else {
throw new app.ManagedError('No Data to export!');
}
}

Google Places Autocomplete - How to show only country names

I want the users to see only the country names when they type on the search box. Is it possible?
I've tried this (doesn't work):
var options = {
types: [('regions')]
};
var searchBox = new google.maps.places.SearchBox(input, options);
Google lets you to use some properties for getting the data like you want.You can set to it language and anything else.
Here is a link,which will help you.
http://www.w3docs.com/learn-javascript/places-autocomplete.html

Google map places API getPlace() only return name attribute for some addresses

I have an address search box using the google map autocomplete library:
var autocompleter = new google.maps.places.Autocomplete(item);
There is an odd occasion that an address only returns a name attribute:
Object {name: "138 Manukau Road, Pukekohe, New Zealand"}
But other addresses are giving more data, such as:
Object {address_components: Array[7], adr_address: "<span class="street-address">430 Queen St</span>, …n>, <span class="country-name">New Zealand</span>", formatted_address: "430 Queen St, Auckland, Auckland 1010, New Zealand", geometry: Object, icon: "http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png"…}address_components: Array[7]adr_address: "<span class="street-address">430 Queen St</span>, <span class="extended-address">Auckland</span>, <span class="locality">Auckland</span> <span class="postal-code">1010</span>, <span class="country-name">New Zealand</span>"formatted_address: "430 Queen St, Auckland, Auckland 1010, New Zealand"geometry: Objecthtml_attributions: Array[0]icon: "http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png"id: "00fce9b1c43ac960068949cbf32eecb587b0b020"name: "430 Queen St"place_id: "ChIJQfHW8OVHDW0RyHgQRLy8fKc"reference: "CqQBlgAAAIDnkWNQ4cmU624FV6l_bAxmI27czZoytmzrrEWVaXgR5LcZuFqt1cL3WIMzoWhmZNhftRzhLUVwpFjqmw3qwKIqugj02HrvU5x6PtUvepPNPV-08pin_PvRU-__mMMH3N2vILIOLM_AnYFMqNG5MArF4ChZXJxZj6vk7PI3ORJe1W6QjIXoPgesL379E4WUCjrZ0fjv3KgqzB-G4f-8A5MSEN5S47-QZqkY5sl37cIQFWQaFLg4InSVLpYGg8n1gGO958TcA4UK"scope: "GOOGLE"types: Array[1]url: "https://maps.google.com/maps/place?q=430+Queen+St,+Auckland,+Auckland+1010,+New+Zealand&ftid=0x6d0d47e5f0d6f141:0xa77cbcbc441078c8"vicinity: "Auckland"__proto__: Object
I have found a similar issue which raised by someone in 2012, and looks like it has not been attended.
This problem was happening intermittently for me and usually out of the blue.
Turns out that if you get a result from Autocomplete with only a name property, you can use the google.maps.places.AutocompleteService to finish the job.
For example, call this if you only get a name back (sending the input element in el)
function getPlace(result, el, callback) {
var autocompleteService = new google.maps.places.AutocompleteService();
if (result.name.length > 0) {
var d = { input: result.name, offset: result.name.length };
autocompleteService.getPlacePredictions(d, function (list, status) {
if (list == null || list.length == 0) callback(null);
var placesService = new google.maps.places.PlacesService(el);
var ref = { 'reference': list[0].reference }
placesService.getDetails(ref, function (detailsResult, placesServiceStatus) {
if (placesServiceStatus == google.maps.GeocoderStatus.OK) {
callback(detailsResult);
}
else {
callback(null);
}
});
});
}
}
This helped me a lot
http://plnkr.co/edit/GF3nM3XfYX9El2w11pGo?p=preview
Surprisingly the very same address now returning correct data, google must be watching these errors and fix them as soon as possible.
Maybe the google service is not able to geocode your address and only return to you the name of the address found. The reason could be that the service has no aditional data to give you for those adress.
You can just not show those incomplete address to the user or try to geocode that address by another service like OSM Geocoder
http://wiki.openstreetmap.org/wiki/Nominatim
From Google Maps Autocomplete Reference:
Returns the details of the Place selected by user if the details were
successfully retrieved. Otherwise returns a stub Place object, with
the name property set to the current value of the input field.
So the answer is that the getPlace method is just failing for specific places. Not sure how to solve this, but gets us one step closer to the answer.
EDIT: FIXED IT!
For my app, I'm loading multiple libraries for google maps (geometry and places). Switching the order that the libraries were loaded fixed the issue, and I don't know why.
Change:
maps.googleapis.com/maps/api/js?v=3&key=[KEY]&libraries=geometry,places
to
maps.googleapis.com/maps/api/js?v=3&key=[KEY]&libraries=places,geometry

google.maps.FusionTablesLayer: styles not applied

I got a code snippet below to display the boundary of an area from google map FusionTablesLayer. The polygon got displayed but the expected style never applied. What's wrong with my code? Please help me. Thank you alot.
var FT_TableID=420419;
var ftoptions = {
suppressInfoWindows:true,
styles: [
{polygonOptions: {fillColor:'#0040FF',fillOpacity:0.1,strokeColor:'#FF0000',strokeWeight:2,strokeOpacity:0.6}}
]
};
var layer = new google.maps.FusionTablesLayer(FT_TableID,ftoptions);
layer.setQuery('SELECT \'kml_4326\' FROM 420419 WHERE \'name_0\' = \'Vietnam\';');
layer.setMap(theMap);
Thank you for the suggestion. Let me clarify my case further, why I had to write the code that way: I stored ftquery for each area in the database (in the raw format: SELECT ... FROM ...) and loaded it out to draw the area boundary.
var ftoptions = {...};
var layer = new google.maps.FusionTablesLayer(tableid);
//to load custom styles, but not work, same for setOptions or set('styles',styles);
layer.setValues(ftoptions);
var ftquery = '';//this is loaded from database
layer.setQuery(ftquery);
layer.setMap(theMap);
I tried your suggestion but the polygon did not show. I must be wrong somewhere. Thank you all for any further help.
You are using the "old" style syntax. If you want to style the FusionTablesLayer, you need to use the documented syntax
var ftoptions = {
query: {
from: tableid,
select: 'kml_4326',
where: "name_0 = 'Vietnam'"
},
suppressInfoWindows:true,
styles: [
{polygonOptions: {fillColor:'#0040FF',fillOpacity:0.1,strokeColor:'#FF0000',strokeWeight:2,strokeOpacity:0.6 }}
]
};
var layer = new google.maps.FusionTablesLayer(ftoptions);
layer.setMap(theMap);

Google maps Autocomplete: output only address without country and city

I use Places library to autocomplete address input. Search is limited to only one city, and I get output like this:
"Rossiya, Moskva, Leninskiy prospekt 28"
How to hide "Rossiya, Moskva"? ...
My query:
function() {
// Search bounds
var p1 = new google.maps.LatLng(54.686534, 35.463867);
var p2 = new google.maps.LatLng(56.926993, 39.506836);
self.options = {
bounds : new google.maps.LatLngBounds(p1, p2),
componentRestrictions: {country: 'ru'},
};
var elements = document.querySelectorAll('.address');
for ( var i = 0; i < elements.length; i++) {
var autocomplete = new google.maps.places.Autocomplete(elements[i],
self.options);
}
You can but you have to replace the value of the input field in two places.
Example:
var autocomplete = new google.maps.places.Autocomplete(input, placesOptions);
var input = document.getElementById('searchTextField');
inside the 'place_changed' event you need to do the following:
placeResult = autocomplete.getPlace();
//This will get only the address
input.value = placeResult.name;
This will change the value in the searchtextfield to the street address.
The second place is a bit tricky:
input.addEventListener('blur', function(){
// timeoutfunction allows to force the autocomplete field to only display the street name.
if(placeResult){ setTimeout(function(){ input.value = placeResult.name; }, 1); } });
The reason why we have to do this is because if you only add the event listener for blur, google places will populate the input field with the full address, so you have to 'wait' for google to update and then force your change by waiting some miliseconds.
Try it without the setTimeout function and you will see what I mean.
EDIT
You can't. I had it the other way around, that you were just looking for a city. There is no way to only print out the street name (I'm assuming that's a street name) from the address component.
OPPOSITE OF WHAT WAS ASKED
From the docs:
the (cities) type collection instructs the Place service to return results that match either locality or administrative_area3.
var input = document.getElementById('searchTextField');
var options = {
bounds: defaultBounds,
types: ['(cities)']
};
autocomplete = new google.maps.places.Autocomplete(input, options);
in result u have hash and from it u can get part what u want:
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
now from "place" u can get it
place.geometry.location.lat()
and for address
place.address_components[0] or place.address_components[1] ...
depends on what u want to get
I had a very similar problem which indeed was solvable. This in an Angular 2 project but it should be applicable elsewhere as well. I filter my results for establishments, and wanted to show only the name and hide the address part of the result. This did the trick for me, a function executing once you select a suggestion:
getAddress(place: Object) {
this.zone.run(() => {
this.establishment = place['name'];
});
where zone is an NgZone component injected in the constructor and this.establishment is the variable tied to [(NgModel)] in the input field.
Inside place_changed set a timeout function:
var streetString = place.address_components[0] or place.address_components[1];
window.setTimeout(function() {
$('input').val(streetString);
}, 200);
This solution worked for me.

Resources