Explanation for "need typeids" error - google-apps-script

I have found a script on github to pull prices from the EVE-Central API to include in a Google Spreadsheet. I have uploaded that script into the editor and saved it. When I try to run it I get an error about a file or function that is missing.
need typeids (line 38, file 'Code')
When I try to use the function inside the spreadsheet it tells me the function does not exist. After a lot of reading I found out Google changed something in their script editors.
Here is the script I am using. And a picture of the error code I got.
/*
Takes a bunch of typeids from a list (duplicates are fine. multidimensional is fine) and returns a bunch of rows
with relevant price data.
TypeID,Buy Volume,Buy average,Buy max,Buy min,Buy Std deviation,Buy median,Buy Percentile,
Sell Volume,Sell Average,Sell Max,Sell Min,Sell std Deviation,Sell Median,sell Percentile
I'd suggest loading price data into a new sheet, then using vlookup to get the bits you care about in your main sheet.
loadRegionPrices defaults to the Forge
loadSystemPrices defaults to Jita
=loadRegionPrices(A1:A28)
=loadRegionPrices(A1:A28,10000002)
=loadRegionPrices(A1:A28,10000002,47)
=loadSystemPrices(A1:A28)
An example below:
https://docs.google.com/spreadsheets/d/1f9-4cb4Tx64Do-xmHhELSwZGahZ2mTTkV7mKDBRPrrY/edit?usp=sharing
*/
function loadRegionPrices(priceIDs,regionID,cachebuster){
if (typeof regionID == 'undefined'){
regionID=10000002;
}
if (typeof priceIDs == 'undefined'){
throw 'need typeids';
}
if (typeof cachebuster == 'undefined'){
cachebuster=1;
}
var prices = new Array();
var dirtyTypeIds = new Array();
var cleanTypeIds = new Array();
var url="http://api.eve-central.com/api/marketstat?cachebuster="+cachebuster+"&regionlimit="+regionID+"&typeid=";
priceIDs.forEach (function (row) {
row.forEach ( function (cell) {
if (typeof(cell) === 'number' ) {
dirtyTypeIds.push(cell);
}
});
});
cleanTypeIds = dirtyTypeIds.filter(function(v,i,a) {
return a.indexOf(v)===i;
});
var parameters = {method : "get", payload : ""};
var o,j,temparray,chunk = 100;
for (o=0,j=cleanTypeIds.length; o < j; o+=chunk) {
temparray = cleanTypeIds.slice(o,o+chunk);
var xmlFeed = UrlFetchApp.fetch(url+temparray.join("&typeid="), parameters).getContentText();
var xml = XmlService.parse(xmlFeed);
if(xml) {
var rows=xml.getRootElement().getChild("marketstat").getChildren("type");
for(var i = 0; i < rows.length; i++) {
var price=[parseInt(rows[i].getAttribute("id").getValue()),
parseInt(rows[i].getChild("buy").getChild("volume").getValue()),
parseFloat(rows[i].getChild("buy").getChild("avg").getValue()),
parseFloat(rows[i].getChild("buy").getChild("max").getValue()),
parseFloat(rows[i].getChild("buy").getChild("min").getValue()),
parseFloat(rows[i].getChild("buy").getChild("stddev").getValue()),
parseFloat(rows[i].getChild("buy").getChild("median").getValue()),
parseFloat(rows[i].getChild("buy").getChild("percentile").getValue()),
parseInt(rows[i].getChild("sell").getChild("volume").getValue()),
parseFloat(rows[i].getChild("sell").getChild("avg").getValue()),
parseFloat(rows[i].getChild("sell").getChild("max").getValue()),
parseFloat(rows[i].getChild("sell").getChild("min").getValue()),
parseFloat(rows[i].getChild("sell").getChild("stddev").getValue()),
parseFloat(rows[i].getChild("sell").getChild("median").getValue()),
parseFloat(rows[i].getChild("sell").getChild("percentile").getValue())];
prices.push(price);
}
}
}
return prices;
}
function loadSystemPrices(priceIDs,systemID,cachebuster){
if (typeof systemID == 'undefined'){
systemID=30000142;
}
if (typeof priceIDs == 'undefined'){
throw 'need typeids';
}
if (typeof cachebuster == 'undefined'){
cachebuster=1;
}
var prices = new Array();
var dirtyTypeIds = new Array();
var cleanTypeIds = new Array();
var url="http://api.eve-central.com/api/marketstat?cachebuster="+cachebuster+"&usesystem="+systemID+"&typeid=";
priceIDs.forEach (function (row) {
row.forEach ( function (cell) {
if (typeof(cell) === 'number' ) {
dirtyTypeIds.push(cell);
}
});
});
cleanTypeIds = dirtyTypeIds.filter(function(v,i,a) {
return a.indexOf(v)===i;
});
var parameters = {method : "get", payload : ""};
var o,j,temparray,chunk = 100;
for (o=0,j=cleanTypeIds.length; o < j; o+=chunk) {
temparray = cleanTypeIds.slice(o,o+chunk);
var xmlFeed = UrlFetchApp.fetch(url+temparray.join("&typeid="), parameters).getContentText();
var xml = XmlService.parse(xmlFeed);
if(xml) {
var rows=xml.getRootElement().getChild("marketstat").getChildren("type");
for(var i = 0; i < rows.length; i++) {
var price=[parseInt(rows[i].getAttribute("id").getValue()),
parseInt(rows[i].getChild("buy").getChild("volume").getValue()),
parseFloat(rows[i].getChild("buy").getChild("avg").getValue()),
parseFloat(rows[i].getChild("buy").getChild("max").getValue()),
parseFloat(rows[i].getChild("buy").getChild("min").getValue()),
parseFloat(rows[i].getChild("buy").getChild("stddev").getValue()),
parseFloat(rows[i].getChild("buy").getChild("median").getValue()),
parseFloat(rows[i].getChild("buy").getChild("percentile").getValue()),
parseInt(rows[i].getChild("sell").getChild("volume").getValue()),
parseFloat(rows[i].getChild("sell").getChild("avg").getValue()),
parseFloat(rows[i].getChild("sell").getChild("max").getValue()),
parseFloat(rows[i].getChild("sell").getChild("min").getValue()),
parseFloat(rows[i].getChild("sell").getChild("stddev").getValue()),
parseFloat(rows[i].getChild("sell").getChild("median").getValue()),
parseFloat(rows[i].getChild("sell").getChild("percentile").getValue())];
prices.push(price);
}
}
}
return prices;
}

The error message is very explicit. Here's the relevant code:
function loadSystemPrices(priceIDs,systemID,cachebuster){
if (typeof systemID == 'undefined'){
systemID=30000142;
}
if (typeof priceIDs == 'undefined'){
throw 'need typeids'; //// <<<< Line 38
}
Function loadSystemPrices() has been invoked with no value for the priceIDs parameter. This condition is explicitly checked by the code, and results in a custom error message being thrown on line 38.
That's happening because you've invoked the function from the debugger, with no parameters. You can work around this by writing a test function to pass parameters, as described in Debugging a custom function in Google Apps Script.

Related

Get the first hyperlink and its text value

I hope everyone is in good health health and condition.
Recently, I have been working on Google Docs hyperlinks using app scripts and learning along the way. I was trying to get all hyperlink and edit them and for that I found an amazing code from this post. I have read the code multiple times and now I have a good understanding of how it works.
My confusion
My confusion is the recursive process happening in this code, although I am familiar with the concept of Recursive functions but when I try to modify to code to get only the first hyperlink from the document, I could not understand it how could I achieve that without breaking the recursive function.
Here is the code that I am trying ;
/**
* Get an array of all LinkUrls in the document. The function is
* recursive, and if no element is provided, it will default to
* the active document's Body element.
*
* #param {Element} element The document element to operate on.
* .
* #returns {Array} Array of objects, vis
* {element,
* startOffset,
* endOffsetInclusive,
* url}
*/
function getAllLinks(element) {
var links = [];
element = element || DocumentApp.getActiveDocument().getBody();
if (element.getType() === DocumentApp.ElementType.TEXT) {
var textObj = element.editAsText();
var text = element.getText();
var inUrl = false;
for (var ch=0; ch < text.length; ch++) {
var url = textObj.getLinkUrl(ch);
if (url != null) {
if (!inUrl) {
// We are now!
inUrl = true;
var curUrl = {};
curUrl.element = element;
curUrl.url = String( url ); // grab a copy
curUrl.startOffset = ch;
}
else {
curUrl.endOffsetInclusive = ch;
}
}
else {
if (inUrl) {
// Not any more, we're not.
inUrl = false;
links.push(curUrl); // add to links
curUrl = {};
}
}
}
if (inUrl) {
// in case the link ends on the same char that the element does
links.push(curUrl);
}
}
else {
var numChildren = element.getNumChildren();
for (var i=0; i<numChildren; i++) {
links = links.concat(getAllLinks(element.getChild(i)));
}
}
return links;
}
I tried adding
if (links.length > 0){
return links;
}
but it does not stop the function as it is recursive and it return back to its previous calls and continue running.
Here is the test document along with its script that I am working on.
https://docs.google.com/document/d/1eRvnR2NCdsO94C5nqly4nRXCttNziGhwgR99jElcJ_I/edit?usp=sharing
I hope you will understand what I am trying to convey, Thanks for giving a look at my post. Stay happy :D
I believe your goal as follows.
You want to retrieve the 1st link and the text of link from the shared Document using Google Apps Script.
You want to stop the recursive loop when the 1st element is retrieved.
Modification points:
I tried adding
if (links.length > 0){
return links;
}
but it does not stop the function as it is recursive and it return back to its previous calls and continue running.
About this, unfortunately, I couldn't understand where you put the script in your script. In this case, I think that it is required to stop the loop when links has the value. And also, it is required to also retrieve the text. So, how about modifying as follows? I modified 3 parts in your script.
Modified script:
function getAllLinks(element) {
var links = [];
element = element || DocumentApp.getActiveDocument().getBody();
if (element.getType() === DocumentApp.ElementType.TEXT) {
var textObj = element.editAsText();
var text = element.getText();
var inUrl = false;
for (var ch=0; ch < text.length; ch++) {
if (links.length > 0) break; // <--- Added
var url = textObj.getLinkUrl(ch);
if (url != null) {
if (!inUrl) {
// We are now!
inUrl = true;
var curUrl = {};
curUrl.element = element;
curUrl.url = String( url ); // grab a copy
curUrl.startOffset = ch;
}
else {
curUrl.endOffsetInclusive = ch;
}
}
else {
if (inUrl) {
// Not any more, we're not.
inUrl = false;
curUrl.text = text.slice(curUrl.startOffset, curUrl.endOffsetInclusive + 1); // <--- Added
links.push(curUrl); // add to links
curUrl = {};
}
}
}
if (inUrl) {
// in case the link ends on the same char that the element does
links.push(curUrl);
}
}
else {
var numChildren = element.getNumChildren();
for (var i=0; i<numChildren; i++) {
if (links.length > 0) { // <--- Added or if (links.length > 0) break;
return links;
}
links = links.concat(getAllLinks(element.getChild(i)));
}
}
return links;
}
In this case, I think that if (links.length > 0) {return links;} can be modified to if (links.length > 0) break;.
Note:
By the way, when Google Docs API is used, both the links and the text can be also retrieved by a simple script as follows. When you use this, please enable Google Docs API at Advanced Google services.
function myFunction() {
const doc = DocumentApp.getActiveDocument();
const res = Docs.Documents.get(doc.getId()).body.content.reduce((ar, {paragraph}) => {
if (paragraph && paragraph.elements) {
paragraph.elements.forEach(({textRun}) => {
if (textRun && textRun.textStyle && textRun.textStyle.link) {
ar.push({text: textRun.content, url: textRun.textStyle.link.url});
}
});
}
return ar;
}, []);
console.log(res) // You can retrieve 1st link and test by console.log(res[0]).
}

Node.js JSON Encode – Array Output Is Empty

I wroted this code to get a value from a database column to output with in JSON array. I succeeded to get it on the browser console, so I tried it with another value and used the same format to the code to passing it from my class file to the router app.post on the other file. I can see it on the terminal when I use console.log, but I can't see the output in the browser response, so what's wrong?
The code that successfully prints output:
auth.js, router part
app.post('/dispalymove', function (req, res, next) {
var lMove="";
if(req.body.MoveString !== null){
Move.setMoveUserId(req.user.id);
Move.setMoveString(req.body.MoveString);
lMove = a.getLastMove(req.user.GameId,function(move){
console.log("Return from display move:",move);
});
}
var output = {"msg":lMove, "loggedin":"true"};
res.send(JSON.stringify(output));
});
The function that I call on move.js file:
getLastMove(id,callback){
var MoveRequest = "SELECT * FROM users ORDER BY id";
var query = connection.query(MoveRequest, function(err,rows, result) {
if (rows.length == 0) {
return callback ("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
}
if (rows.length > 0) {
for (var i in rows) {
var move = rows[i].MoveString;
if (rows[i].GameId == id){
callback(move);
}
}
}
});
var move="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
return move;
}
The response on the browser console when the output is successful:
msg:"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
loggedin:"true"
the outputting code that have the problem
app.post('/getcolor', function (req, res, next) {
var lCol="";
if(req.body.MoveString !== null){
Move.setMoveUserId(req.user.id);
lCol = a.getColor(req.user.id,function(col){
console.log("Return from getcolor:",col)
//the the value that i get on terminal "Return from getcolor:white"
});
}
var output = {"msg":lCol, "loggedin":"true"};
res.send(JSON.stringify(output));
});
The function that I call from the other file:
getColor(id,callback){
var ColRequest = "SELECT * FROM users ORDER BY id";
var query = connection.query(ColRequest, function(err,rows, result) {
if (rows.length == 0) {
return callback ("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
}
if (rows.length > 0) {
for (var i in rows) {
var col = rows[i].GameColor;
if (rows[i].id == id){
callback(col);
}
}
}
});
var col="";
return callback(col);
}
The value that I get on my browser console response output just
loggedin:"true"
that should be like that
msg:"white"
loggedin:"true"
I tried to write this code with php
to post getcolor like that
session_start();
include "../classes/move.php";
$lCol="";
if(isset($_POST['MoveString'])){
$move = new move();
$move->setMoveUserId($_SESSION['UserId']);
$lCol=$move->getColor($_SESSION['UserId']);
}
$output = array("msg"=>"$lCol", "loggedin"=>"true");
echo json_encode($output);
and the function that i call
public function getColor($id){
include "../../connectToDB.php";
$ColRequest=$_db->query("SELECT * FROM users ORDER BY UserId");
$existCount = $ColRequest->rowCount();
if ($existCount == 0) { // evaluate the count
return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
}
if ($existCount > 0) {
while($row = $ColRequest->fetch(PDO::FETCH_ASSOC)){
$userID = $row["UserId"];
$col = $row["GameColor"];
if($userID == $id) {
return $col;
}
}
}
$col="";
return $col;
}
and the output was that on browser console responses
msg:"white"
loggedin:"true"
This is because of lCol = a.getColor(req.user.id,function(col):
lCol is undefined here because getColor returns nothing, it expects a callback and gives you a value in this callback (while getLastMove in the contrary does return something). Try with :
app.post('/getcolor', function (req, res, next) {
var lCol = "";
if (req.body.MoveString !== null) {
Move.setMoveUserId(req.user.id);
// lCol = <=== useless because a.getcolor returns nothing
a.getColor(req.user.id, function (col) {
console.log("Return from getcolor:", col)
//the the value that i get on terminal "Return from getcolor:white"
res.json({"msg": col, "loggedin": "true"}); // <=== here you have a defined lCol
});
} else {
var output = {"msg": lCol, "loggedin": "true"}; // <=== here lCol always equals ""
res.json(output);
}
// var output = {"msg": lCol, "loggedin": "true"}; // <=== here lCol always equals undefined (when req.body.MoveString !== null)
// res.send(JSON.stringify(output));
});
Edit: in the getColor and getLastMove function you sould not return anthing: just use the callback: because connection.query is asynchronous any return will be invalid; In getColor your are doing
var col="";
return callback(col); so you will always have a "" response. Beware: do not call a callback function several times when it ends to a server response (you can't send multiple responses for one request): your callback calls are in a loop, they should not, just call it once.

Protractor Convert a CSV file to Json and read key value

I am using the following functions on a library and then calling them like this. The issue with the code is that I am not able return the values from the code below:
Would be great if some one suggests a way to return the value back to my test. (I will post the full working code once this is solved). I have not worked with promises so if some one can suggest a solution that be great!
Resolved this!!! check my answer:
My Testcase
iit("Should Find the OrderID and update task and submit", function () {
var job_id_data= lib.getTestData('MYPROJ_TESTCASE_001'); //Problem area
console.log(job_id_data);
element(by.xpath('//input[#type=\'search\']')).sendKeys(job_id_data);
//Do other stuff
}
The below code in my function (lib) needs to return a promise, and I don't know how to do that :(
csvConverter.on("end_parsed",function(jsonObj){
//console.log(jsonObj); //here is your result json object
var foundTestData = getObjects(jsonObj, 'TC', jobreference);
console.log(returnKeyValue ); //I can see this value
returnKeyValue = getValues(foundTestData, 'JOBID'); // I cannot return this??
});
Full Not working code ...Code
var lib = require('./lib/library.js');
iit("should go to logout page", function () {
var id_data= lib.getTestData('Test.3');
//plan to use this value in my tests
});
//Library
function getTestData(jobreference) {
//Converter Class
var Converter=require("csvtojson").core.Converter;
var fs=require("fs");
var csvFileName="C:\\TestData.csv";
var fileStream=fs.createReadStream(csvFileName);
//new converter instance
var param={};
var csvConverter=new Converter(param);
var returnKeyValue="";
var result = {};
//This requires a code change:
csvConverter.on("end_parsed",function(jsonObj){
//console.log(jsonObj); //here is your result json object
var foundTestData = getObjects(jsonObj, 'TC', jobreference);
console.log(returnKeyValue ); //I can see this value
returnKeyValue = getValues(foundTestData, 'JOBID'); // I cannot return this??
});
//read from file
fileStream.pipe(csvConverter);
return returnKeyValue;
}
function getValues(obj, key) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getValues(obj[i], key));
} else if (i == key) {
objects.push(obj[i]);
}
}
return objects;
}
function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else
//if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
if (i == key && obj[i] == val || i == key && val == '') { //
objects.push(obj);
} else if (obj[i] == val && key == ''){
//only add if the object is not already in the array
if (objects.lastIndexOf(obj) == -1){
objects.push(obj);
}
}
}
return objects;
}
Managed to resolve this :) with some help from my colleague (thanks :))
This post here helped me get quickly to the point
http://know.cujojs.com/tutorials/promises/creating-promises
Solution is I updated the function to the following, which basically works with Protractor Promises. Which is great.
function getTestData(jobreference) {
var Converter=require("csvtojson").core.Converter;
var fs=require("fs");
var csvFileName="TESTJOB.csv";
var fileStream=fs.createReadStream(csvFileName);
var csvConverter=new Converter(param);
//new converter instance
var param={};
var csvConverter=new Converter(param);
var d = protractor.promise.defer();
csvConverter.on("end_parsed",function(jsonObj){
var foundTestData = getObjects(jsonObj, 'TCaseID', jobreference);
returnKeyValue = getValues(foundTestData, 'ID');
console.log(returnKeyValue.toString());
d.fulfill(returnKeyValue.toString());
});
//d.reject("fail!!!!");
fileStream.pipe(csvConverter);
return d.promise;
}

json stringify in IE 8 gives run time error Object property or method not supported

/* Problem description- I am using json stringify method to convert an javascript array to string in json notation.However I get an error message that 'Object property or method not supported' at line
hidden.value = JSON.stringify(jsonObj);
This should work as stringify is supported in IE8.Please advise
Full code below */
function getgridvalue() {
var exportLicenseId;
var bolGrossQuantity;
var bolNetQuantity;
var totalBolGrossQty =0 ;
var totalBolNetQty =0;
var jsonObj = []; //declare array
var netQtyTextBoxValue = Number(document.getElementById("<%= txtNetQty.ClientID %>").value);
var atLeastOneChecked = false;
var gridview = document.getElementById("<%= ExporterGrid.ClientID %>"); //Grab a reference to the Grid
for (i = 1; i < gridview.rows.length; i++) //Iterate through the rows
{
if (gridview.rows[i].cells[0].getElementsByTagName("input")[0] != null && gridview.rows[i].cells[0].getElementsByTagName("input")[0].type == "checkbox")
{
if (gridview.rows[i].cells[0].getElementsByTagName("input")[0].checked)
{
atLeastOneChecked = true;
exportLicenseId = gridview.rows[i].cells[8].getElementsByTagName("input")[0].value;
bolNetQuantity = gridview.rows[i].cells[5].getElementsByTagName("input")[0].value;
if (bolNetQuantity == "") {
alert('<%= NetQuantityMandatory %>');
return false;
}
if (!isNumber(bolNetQuantity)) {
alert('<%= NetQuantityNumber %>');
return false;
}
totalBolNetQty += Number(bolNetQuantity);
jsonObj.push({ ExportLicenseId: Number(exportLicenseId), BolNetQuantity: Number(bolNetQuantity) });
}
}
}
if (gridview.rows.length > 2 && !atLeastOneChecked)
{
alert('<%= SelectMsg %>');
return false;
}
if (totalBolNetQty != 0 && netQtyTextBoxValue != totalBolNetQty)
{
alert('<%= NetQuantitySum %>');
return false;
}
var hidden = document.getElementById('HTMLHiddenField');
// if (!this.JSON) {
// this.JSON = {};
// }
var JSON = JSON || {};
if (hidden != null) {
hidden.value = JSON.stringify(jsonObj);
}
}
Use the F12 Developer Tools to check the browser mode. The JSON object exists, but has no methods in IE7 mode. Use the json2 library as a fallback.
json2.js

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>