Google Elevation API - splitting multiple elevation requests - google-maps

I'm trying to split a big request for elevation into multiple requests to avoid the 1sec/request and 512 coords limit in each request.
The problem I face is that the reply of my requests are not always received in the good order. Is using setInterval reliable enough?
Here is an example of response received in the wrong order that cause a problem (before using setInterval):
https://www.dropbox.com/s/x00jdnprj6w7lga/correctMap.png?dl=0
Here is my latest code:
function getCourseElevationData() {
var path = bikePathCoordinates; //Bunch of lat,long coords
// numberRequestToDo = Math.ceil(path.length/512); //TODO: split request in multiple 512 pack (google quotas)
numberRequestToDo = 2; //Temporary for testing
currentRequestNumber = -1; //will be at 0 on first call to get512Elevation
arrayOfRequest = [];
//1
var ptrStart= 0;
var pathSliced = path.slice(ptrStart, ptrStart+512);
arrayOfRequest.push(pathSliced);
//2
ptrStart += 512;
pathSliced = path.slice(ptrStart, ptrStart+512);
arrayOfRequest.push(pathSliced);
timerElevation = setInterval(request512Elevation, 1000); //1sec
}
//---------------------------------------------------------
function request512Elevation() {
alert("request512Elevation");
// Still has request to be done
if (currentRequestNumber+1 < numberRequestToDo) {
if (!lastRequestElevationFailed) {
currentRequestNumber++;
}
get512Elevation(arrayOfRequest[currentRequestNumber], currentRequestNumber);
}
// All request completed!
else {
clearInterval(timerElevation);
}
}
//------------------------------------------------------------------------------------------------
function get512Elevation(pathSliced, requestNumber) {
alert("get512PointsElevation" + requestNumber);
var locationElevationRequest = {
'locations': pathSliced
}
elevator.getElevationForLocations(locationElevationRequest, function (results, status) {
alert("ResponseReceived for request:" + requestNumber + ", status" + status + " result length:" + results.length);
if (status != google.maps.ElevationStatus.OK) {
lastRequestElevationFailed = true;
return;
}
lastRequestElevationFailed = false;
var elevations = results;
// Extract the elevation samples from the returned results
for (var i = 0; i < results.length; i++) {
elevationPath.push(elevations[i].location);
}
for (var i = 0; i < results.length; i++) {
dataElevation.addRow(['', elevations[i].elevation]);
}
//last reply received? if yes, we can display the elevation graph
if (currentRequestNumber+1 == numberRequestToDo) {
chart.draw(dataElevation, chartOptions);
}
//TODO: how to make sure response are received in correct order (1,2,3)? setInterval reliable enough?
});
}

Related

Unable to get this "tagging unanswered email" script to work

The following is a script that I found online to tag all the unanswered emails. It works for one of my gmail accounts, however when I shared it to another account and run it, it returns nothing every single time, even though there are unanswered emails within that time range. I then tried copy and paste the codes into a new project, however still wouldn't work.
Anyone has any ideas?
Thanks in advance!
/*
* This script goes through your Gmail Inbox and finds recent emails where you
* were the last respondent. It applies a nice label to them, so you can
* see them in Priority Inbox or do something else.
*
* To remove and ignore an email thread, just remove the unrespondedLabel and
* apply the ignoreLabel.
*
* This is most effective when paired with a time-based script trigger.
*
* For installation instructions, read this blog post:
* http://jonathan-kim.com/2013/Gmail-No-Response/
*/
// Edit these to your liking.
var unrespondedLabel = 'No Response',
ignoreLabel = 'Ignore No Response',
minDays = 0.125,
maxDays = 5;
function main() {
processUnresponded();
cleanUp();
}
function processUnresponded() {
var threads = GmailApp.search('is:sent from:me -in:chats older_than:' + minDays + 'd newer_than:' + maxDays + 'd'),
numUpdated = 0,
minDaysAgo = new Date();
minDaysAgo.setDate(minDaysAgo.getDate() - minDays);
// Filter threads where I was the last respondent.
for (var i = 0; i < threads.length; i++) {
var thread = threads[i],
messages = thread.getMessages(),
lastMessage = messages[messages.length - 1],
lastFrom = lastMessage.getFrom(),
lastMessageIsOld = lastMessage.getDate().getTime() < minDaysAgo.getTime();
if (isFromMe(lastFrom) && lastMessageIsOld && !threadHasLabel(thread, ignoreLabel)) {
markUnresponded(thread);
numUpdated++;
}
}
Logger.log('Updated ' + numUpdated + ' messages.');
}
function isFromMe(fromAddress) {
var addresses = getEmailAddresses();
for (i = 0; i < addresses.length; i++) {
var address = addresses[i],
r = RegExp(address, 'i');
if (r.test(fromAddress)) {
return true;
}
}
return false;
}
function getEmailAddresses() {
var me = Session.getActiveUser().getEmail(),
emails = GmailApp.getAliases();
emails.push(me);
return emails;
}
function threadHasLabel(thread, labelName) {
var labels = thread.getLabels();
for (i = 0; i < labels.length; i++) {
var label = labels[i];
if (label.getName() == labelName) {
return true;
}
}
return false;
}
function markUnresponded(thread) {
var label = getLabel(unrespondedLabel);
label.addToThread(thread);
}
function getLabel(labelName) {
var label = GmailApp.getUserLabelByName(labelName);
if (label) {
Logger.log('Label exists.');
} else {
Logger.log('Label does not exist. Creating it.');
label = GmailApp.createLabel(labelName);
}
return label;
}
function cleanUp() {
var label = getLabel(unrespondedLabel),
iLabel = getLabel(ignoreLabel),
threads = label.getThreads(),
numExpired = 0,
twoWeeksAgo = new Date();
twoWeeksAgo.setDate(twoWeeksAgo.getDate() - maxDays);
if (!threads.length) {
Logger.log('No threads with that label');
return;
} else {
Logger.log('Processing ' + threads.length + ' threads.');
}
for (i = 0; i < threads.length; i++) {
var thread = threads[i],
lastMessageDate = thread.getLastMessageDate();
// Remove all labels from expired threads.
if (lastMessageDate.getTime() < twoWeeksAgo.getTime()) {
numExpired++;
Logger.log('Thread expired');
label.removeFromThread(thread);
iLabel.removeFromThread(thread);
} else {
Logger.log('Thread not expired');
}
}
Logger.log(numExpired + ' unresponded messages expired.');
}
The Gmail search operator "older_than" does not support decimals, so you cannot use "0.125" in this case. Make sure you use an integer number/day. The script will not return errors, but the search will not work. More info about the Gmail search operators at https://support.google.com/mail/answer/7190?hl=en

Labeling Gmail message (not the whole thread) with Google Apps Script

Is it possible to search to messages with the label 'Apps script queue' and give just these specific messages (not the whole thread) a new label?
When I use GmailApp.search('label:Apps script queue') I get the requested messages but when I assign a new label to these messages, all the other messages of the thread (on other places in the mailbox) will get the same label. And that is not what I want.
This code does not return an error while adding a label to a specific message in a thread and if you use thread list method you'll see that it is only placed in the specific messageID(treated separately). But once your UI(Gmail site) is in conversation mode, it will be viewable in both labels.
function searchMail(){
var threads = GmailApp.search("SOME SEARCH");
Logger.log(threads.length);
listLabel('me');
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
Logger.log(messages.length);
for (var j = 0; j < messages.length; j++){
if (messages[j].isInInbox()){
Logger.log('me' + 'id msg: ' + messages[j].getId());
//Add label to the first reply
addLabel('me',messages[1].getId());
}
else{
Logger.log('me' + 'id msg: ' + messages[j].getId() +" not in inbox");
}
}
}
}
function addLabel(userId, messageId){
var resource = {addLabelIds: ["Label_6"]}
Gmail.Users.Messages.modify(resource, userId, messageId);
}
In Gmail, labels are applied to a thread and cannot be applied to a single email message of a thread.
You can however apply stars / colors to individual messages.
This is an old thread, but for anybody who might be reading it like me, maybe this will save you some time:
function getLabelMap() {
var allLabels = Gmail.Users.Labels.list('me');
var labelMap = [];
for (var label of allLabels.labels) {
labelMap[label.name] = label.id;
}
return labelMap;
}
var labelMap = getLabelMap();
function getLabel(labelName) {
return labelMap[labelName];
}
function labelMessage(messageID, labelName) {
var labelID = getLabel(labelName);
var labelRequest = {addLabelIds: [labelID]};
var subject = GmailApp.getMessageById(messageID).getSubject();
if (labelID != null) {
Logger.log("Labelling as %s: %s", labelName, subject);
Gmail.Users.Messages.modify(labelRequest, 'me', messageID);
} else {
Logger.log("Label not found: %s", labelName);
}
}
function unlabelMessage(messageID, labelName) {
var labelID = getLabel(labelName);
var labelRequest = {removeLabelIds: [labelID]};
var subject = GmailApp.getMessageById(messageID).getSubject();
if (labelID != null) {
Logger.log("Removing label %s: %s", labelName, subject);
Gmail.Users.Messages.modify(labelRequest, 'me', messageID);
} else {
Logger.log("Label not found: %s", labelName);
}
}
function reLabel () {
var messagesToRelabel = Gmail.Users.Messages.list('me', {'q':'label:Apps-script-queue'}).messages || [];
// Loop through each message (not by thread), using the Advanced Gmail Service (full GMail API in a Google Script).
messagesToRelabel.forEach(function (messageToRelabel){
unlabelMessage(messageToRelabel.id, "Apps script queue");
labelMessage(messageToRelabel.id, "New label");
});
}
Not asked for by the OP, but may be helpful for others who are trying to do "advanced filtering / labeling" using the GMail API:
function getMessageHeader(messageID, headerField) {
var messageInfo = Gmail.Users.Messages.get('me', messageID, {'format':'METADATA', 'metadataHeaders':[headerField]});
if (messageInfo.payload.headers) {
return messageInfo.payload.headers[0].value;
} else {
return null;
}
}
The above lets you filter on header info, e.g. I use it to check whether X-Uniform-Type-Identifier is equal to com.apple.mail-note to automatically flag old Apple Notes for deletion.

How to pass a whole dojox.grid.DataGrid store(items json data) to servlet?

I have a button on page - when clicked, it passes all the data to the servlet that could update each row data. My question is how to pass the whole store to the servlet as json data? Is there any easy way? Thanks
Here is some code I wrote to get the store to an object. Then it can be converted to JSON using dojo.toJson(obj);. I learned about this from the dojotoolkit website originally. (Give credit where credit is due). I realize this code is huge and nasty. When I looked for a better way about a year back I could not find one.
JsonHelper.storeToObject = function(store) {
var object = [];
var index = -1;
store.fetch({
onItem : function(item, request) {
object[++index] = JsonHelper.itemToObject(store, item);
}
});
return object;
};
JsonHelper.itemToObject = function(store, item) {
// store:
// The datastore the item came from.
// item:
// The item in question.
var obj = {};
if (item && store) {
// Determine the attributes we need to process.
var attributes = store.getAttributes(item);
if (attributes && attributes.length > 0) {
var i;
for (i = 0; i < attributes.length; i++) {
var values = store.getValues(item, attributes[i]);
if (values) {
// Handle multivalued and single-valued attributes.
if (values.length > 1) {
var j;
obj[attributes[i]] = [];
for (j = 0; j < values.length; j++) {
var value = values[j];
// Check that the value isn't another item. If
// it is, process it as an item.
if (store.isItem(value)) {
obj[attributes[i]].push(itemToObject(store,
value));
} else {
obj[attributes[i]].push(value);
}
}
} else {
if (store.isItem(values[0])) {
obj[attributes[i]] = itemToObject(store,
values[0]);
} else {
obj[attributes[i]] = values[0];
}
}
}
}
}
}
return obj;
};

GMap Api geocoder.getLatLng (address) function , Doesn't work good when call it within loop

I'm trying this recursion function to find LatLng of 2088 diffrent addresses and replay me with only about 180 results . although all addresses are valid on google maps website .
function test(i)
{
if(i >= jsArray.length){return;}
var geocoder = new GClientGeocoder();
geocoder.getLatLng(jsArray[i], function (current) {
return function(point) {
if (!point) {
data.push("null");
//nulls.push(myindex);
} else {
data.push(point);
//alert("done");
}
test(i+1,jsArray);
}
}(i));
}
test(0);
i have developed this recursive function but it's need about 30 mins till get good results ,
function test2(i)
{
geocoder.getLocations(jsArray[i], function (current) {
return function(response) {
if (!response || response.Status.code != 200) {
//alert(address + " not found");
//test(i,jsArray);
// data.push("null");
//nulls.push(myindex);
test2(i);
} else {
var len = response.Placemark[0];
point2 = new GLatLng(
len.Point.coordinates[1],
len.Point.coordinates[0]
);
data[i] = point2;
}
}
}(i));
}
for(i =0 ; i<=jsArray.length; i++)
{
if(i==jsArray.length){
alert(data.length);
/// $("#maintable").show(100) ;
/// $("#loading").hide(100) ;
}else{
test2(i);
}
}
i still need expert one to help me :) :D
The geocoder is asynchronous (which makes using it in loops problematic) and subject to a quota and rate limits. It is not intended for displaying lots of known addresses on a map, it is intended for user entered data.
You really should geocode your points off line, save the resulting coordinates and use those coordinates to display markers on your map.
If you are using it in a loop, you shouldn't use the getLatLng method, you should use the getLocations method, which contains a status code that will let you know why it is failing (G_GEO_TOO_MANY_QUERIES
= 620, would mean you could throttle your requests and potentially get a useful result)
// jsArray is array of addresses . the length of this array is 2087 element, all addresses got from google maps .
function MYFunction(i)
{
geocoder.getLocations(jsArray[i], function (current) {
return function(response) {
if (!response || response.Status.code != 200) {
test2(i); // recursive calling
} else {
var len = response.Placemark[0];
point2 = new GLatLng(
len.Point.coordinates[1],
len.Point.coordinates[0]
);
data[i] = point2;
}
}
}(i));
} /// end of y Function
//// loop for each address and pass it to MyFunction function and start recursive function .
for(i =0 ; i<=jsArray.length; i++)
{
MYFunction(i);
}

Retrieving Postal Code with Google Maps Javascript API V3 Reverse Geocode

I'm trying to submit a query using the postal code to my DB whenever the googlemaps viewport center changes. I know that this can be done with reverse geocoding with something like:
google.maps.event.addListener(map, 'center_changed', function(){
newCenter();
});
...
function newCenter(){
var newc = map.getCenter();
geocoder.geocode({'latLng': newc}, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
var newzip = results[0].address_components['postal_code'];
}
});
};
Of course, this code doesn't actually work. So I was wondering how I would need to change this in order to extract the postal code from the results array.
Thanks
What I've realized so far is that in most cases the ZIPCODE is always the last value inside each returned address, so, if you want to retrieve the very first zipcode (this is my case), you can use the following approach:
var address = results[0].address_components;
var zipcode = address[address.length - 1].long_name;
You can do this pretty easily using the underscore.js libraray: http://documentcloud.github.com/underscore/#find
_.find(results[0].address_components, function (ac) { return ac.types[0] == 'postal_code' }).short_name
Using JQuery?
var searchAddressComponents = results[0].address_components,
searchPostalCode="";
$.each(searchAddressComponents, function(){
if(this.types[0]=="postal_code"){
searchPostalCode=this.short_name;
}
});
short_name or long_name will work above
the "searchPostalCode" var will contain the postal (zip?) code IF
and only IF you get one from the Google Maps API.
Sometimes you DO NOT get a "postal_code" in return for your query.
Alright, so I got it. The solution is a little uglier than I'd like, and I probably don't need the last for loop, but here's the code for anyone else who needs to extract crap from address_components[]. This is inside the geocoder callback function
// make sure to initialize i
for(i=0; i < results.length; i++){
for(var j=0;j < results[i].address_components.length; j++){
for(var k=0; k < results[i].address_components[j].types.length; k++){
if(results[i].address_components[j].types[k] == "postal_code"){
zipcode = results[i].address_components[j].short_name;
}
}
}
}
$.each(results[0].address_components,function(index,value){
if(value.types[0] === "postal_code"){
$('#postal_code').val(value.long_name);
}
});
You can also use JavaScript .find method which is similar to underscore _.find method but it is native and require no extra dependency.
const zip_code = results[0].address_components.find(addr => addr.types[0] === "postal_code").short_name;
This takes only two for loops. The "results" array gets updated once we found the first "type" to be "postal_code".
It then updates the original array with the newly found array set and loops again.
var i, j,
result, types;
// Loop through the Geocoder result set. Note that the results
// array will change as this loop can self iterate.
for (i = 0; i < results.length; i++) {
result = results[i];
types = result.types;
for (j = 0; j < types.length; j++) {
if (types[j] === 'postal_code') {
// If we haven't found the "long_name" property,
// then we need to take this object and iterate through
// it again by setting it to our master loops array and
// setting the index to -1
if (result.long_name === undefined) {
results = result.address_components;
i = -1;
}
// We've found it!
else {
postcode = result.long_name;
}
break;
}
}
}
You can also use this code, this function will help to get zip on button click or onblur or keyup or keydown.
Just pass the address to this function.
use google api with valid key and sensor option removed as it doesn't required now.
function callZipAPI(addSearchZip)
{
var geocoder = new google.maps.Geocoder();
var zipCode = null;
geocoder.geocode({ 'address': addSearchZip }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//var latitude = results[0].geometry.location.lat();
//var longitude = results[0].geometry.location.lng();
var addressComponent = results[0].address_components;
for (var x = 0 ; x < addressComponent.length; x++) {
var chk = addressComponent[x];
if (chk.types[0] == 'postal_code') {
zipCode = chk.long_name;
}
}
if (zipCode) {
alert(zipCode);
}
else {
alert('No result found!!');
}
} else {
alert('Enter proper address!!');
}
});
}
I use this code to get "Postal code" and "locality", but you can use it to get any other field just changing the value of type:
JAVASCRIPT
var address = results[0].address_components;
var zipcode = '';
var locality = '';
for (var i = 0; i < address.length; i++) {
if (address[i].types.includes("postal_code")){ zipcode = address[i].short_name; }
if (address[i].types.includes("locality")){ locality = address[i].short_name; }
}
I think rather than depending on the index it better checks address type key inside the component. I solved this issue by using a switch case.
var address = '';
var pin = '';
var country = '';
var state = '';
var city = '';
var streetNumber = '';
var route ='';
var place = autocomplete.getPlace();
for (var i = 0; i < place.address_components.length; i++) {
var component = place.address_components[i];
var addressType = component.types[0];
switch (addressType) {
case 'street_number':
streetNumber = component.long_name;
break;
case 'route':
route = component.short_name;
break;
case 'locality':
city = component.long_name;
break;
case 'administrative_area_level_1':
state = component.long_name;
break;
case 'postal_code':
pin = component.long_name;
break;
case 'country':
country = component.long_name;
break;
}
}
places.getDetails( request_details, function(results_details, status){
// Check if the Service is OK
if (status == google.maps.places.PlacesServiceStatus.OK) {
places_postal = results_details.address_components
places_phone = results_details.formatted_phone_number
places_phone_int = results_details.international_phone_number
places_format_address = results_details.formatted_address
places_google_url = results_details.url
places_website = results_details.website
places_rating = results_details.rating
for (var i = 0; i < places_postal.length; i++ ) {
if (places_postal[i].types == "postal_code"){
console.log(places_postal[i].long_name)
}
}
}
});
This seems to work very well for me, this is with the new Google Maps API V3. If this helps anyone, write a comment, i'm writing my script as we speak... so it might change.
Using JSONPath, it's easily done with one line of code:
var zip = $.results[0].address_components[?(#.types=="postal_code")].long_name;
In PHP I use this code. Almost in every conditions it works.
$zip = $data["results"][3]["address_components"];
$zip = $index[0]["short_name"];
Romaine M. — thanks! If you just need to find the postal code in the first returned result from Google, you can do just 2 loops:
for(var j=0;j < results[0].address_components.length; j++){
for(var k=0; k < results[0].address_components[j].types.length; k++){
if(results[0].address_components[j].types[k] == "postal_code"){
zipcode = results[0].address_components[j].long_name;
}
}
}
In a word, that's a lot of effort. At least with the v2 API, I could retrieve those details thusly:
var place = response.Placemark[0];
var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
myAddress = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName
myCity = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName
myState = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName
myZipCode = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber
There has got to be a more elegant way to retrieve individual address_components without going through the looping jujitsu you just went through.
This simple code works for me
for (var i = 0; i < address.length; i++) {
alert(address[i].types);
if (address[i].types == "postal_code")
$('#postalCode').val(address[i].long_name);
if (address[i].types == "")
$('#country').val(address[i].short_name);
}
Using Jquery
You cant be sure in which location in the address_components array the postal code is stored. Sometimes in address_components.length - 1 > pincode may not be there. This is true in "Address to latlng" geocoding.
You can be sure that Postal code will contain a "postal_code" string. So best way is to check for that.
var postalObject = $.grep(results[0].address_components, function(n, i) {
if (n.types[0] == "postal_code") {
return n;
} else {
return null;
}
});
$scope.query.Pincode = postalObject[0].long_name;
return $http.get('//maps.googleapis.com/maps/api/geocode/json', {
params: {
address: val,
sensor: false
}
}).then(function (response) {
var model= response.data.results.map(function (item) {
// return item.address_components[0].short_name;
var short_name;
var st= $.each(item.address_components, function (value, key) {
if (key.types[0] == "postal_code") {
short_name= key.short_name;
}
});
return short_name;
});
return model;
});
//autocomplete is the text box where u will get the suggestions for an address.
autocomplete.addListener('place_changed', function () {
//Place will get the selected place geocode and returns with the address
//and marker information.
var place = autocomplete.getPlace();
//To select just the zip code of complete address from marker, below loop //will help to find. Instead of y.long_name you can also use y.short_name.
var zipCode = null;
for (var x = 0 ; x < place.address_components.length; x++) {
var y = place.address_components[x];
if (y.types[0] == 'postal_code') {
zipCode = y.long_name;
}
}
});
It seems that nowadays it's better to get it from the restful API, simply try:
https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_KEY_HERE
Using an AJAX GET call works perfect!
Something like:
var your_api_key = "***";
var f_center_lat = 40.714224;
var f_center_lon = -73.961452;
$.ajax({ url: "https://maps.googleapis.com/maps/api/geocode/json?latlng="+f_center_lat+","+f_center_lon+"&key="+your_api_key,
method: "GET"
})
.done(function( res ) { if (debug) console.log("Ajax result:"); console.log(res);
var zipCode = null;
var addressComponent = res.results[0].address_components;
for (var x = 0 ; x < addressComponent.length; x++) {
var chk = addressComponent[x];
if (chk.types[0] == 'postal_code') {
zipCode = chk.long_name;
}
}
if (zipCode) {
//alert(zipCode);
$(current_map_form + " #postalcode").val(zipCode);
}
else {
//alert('No result found!!');
if (debug) console.log("Zip/postal code not found for this map location.")
}
})
.fail(function( jqXHR, textStatus ) {
console.log( "Request failed (get postal code via geocoder rest api). Msg: " + textStatus );
});
As I got it zip is the last or the one that before last.
That why this is my solution
const getZip = function (arr) {
return (arr[arr.length - 1].types[0] === 'postal_code') ? arr[arr.length - 1].long_name : arr[arr.length - 2].long_name;
};
const zip = getZip(place.address_components);
i think this is the most accurate solution:
zipCode: result.address_components.find(item => item.types[0] === 'postal_code').long_name;
Just search for postal_code in all types, and return when found.
const address_components = [{"long_name": "2b","short_name": "2b","types": ["street_number"]}, { "long_name": "Louis Schuermanstraat","short_name": "Louis Schuermanstraat", "types": ["route"]},{"long_name": "Gent","short_name": "Gent","types": ["locality","political" ]},{"long_name": "Oost-Vlaanderen","short_name": "OV","types": ["administrative_area_level_2","political"]},{"long_name": "Vlaanderen","short_name": "Vlaanderen","types": ["administrative_area_level_1","political"]},{"long_name": "België","short_name": "BE","types": ["country","political"]},{"long_name": "9040","short_name": "9040","types": ["postal_code"]}];
// address_components = results[0]address_components
console.log({
'object': getByGeoType(address_components),
'short_name': getByGeoType(address_components).short_name,
'long_name': getByGeoType(address_components).long_name,
'route': getByGeoType(address_components, ['route']).long_name,
'place': getByGeoType(address_components, ['locality', 'political']).long_name
});
function getByGeoType(components, type = ['postal_code']) {
let result = null;
$.each(components,
function() {
if (this.types.some(r => type.indexOf(r) >= 0)) {
result = this;
return false;
}
});
return result;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>