How to verify a google maps api key in html javascript? - javascript

I have a rather standard Google Maps page, using my own API key. The page only does some marker additions by JS and presenting it in a text-box. If the key is invalid or expired or whatever, the following page is displayed.
That is fine, but then I would like to at lest tell the user why it is wrong. The map is accessed by standard:
...
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?key=API_KEY"></script>
</head>
<body>
<div id="map"></div>
<p><input type="text" "readonly" id="status" size=40></p>
...
However, I would like to check that the API key is working and valid, and tell the user if the key is OK or not in that text box.
How can I do that?
PS. The problem with using a callback function in the src=, is that it returns regardless what is the API status, but not actually the status itself. Here is a kludge solution of this.
EDIT: I found an answer in the obscurely and poorly documented callback function, gm_authFailure(), and solved my question with:
function gm_authFailure() {
let apiError = "No or invalid API key!"
document.getElementById('status').value = apiError;
};
You don't even need to specify this callback in your URL, it will use it anyway!

Add this:
function gm_authFailure() { alert('yo'); };
In the global scope. Per this:
https://developers.google.com/maps/documentation/javascript/events#auth-errors

Related

JS variable is displayed as undefined when using HTML

I am working on a project on Google Apps Script. I have a JS function that returns a date (as a text). I also have an HTML document to display a form with several inputs. I would like to prefill one input with the date returned by the JS funtion. It almost works, except it displays "undefined" instead of the date, even though I know the js funtion is working fine.
Here are some code to better understand :
The input where I call the script (don't mind the onmousemove, i just didn"t find anotherway to call the script).
<input type="text" id="deliveryDate" name="deliveryDate" onmousemove="displayActiveDate()">
So it calls the folowing script.
<script>
function displayActiveDate(){
var activeDate = google.script.run.getActiveDate();
document.getElementById("deliveryDate").value = activeDate;
}
</script>
Which in turn calls getActiveDate() which is the separate JS function that returns the date.
If you have any idea on how to solve this, I will be very thankful.
google.script.run.serverSideFunction() returns undefined. In order to get the actual response value from your serverSideFunction() you need to use the withSuccessHandler() method with a callback like so:
google.script.run.withSuccessHandler(onSuccess).serverSideFunction();
function onSuccess(data) {
// do something with the data returned by the serverSideFunction()
}
Also note that you also have withFailureHandler(err) to handle any errors you server-side functions may return.
Here is the full reference
Instead of writing document.getElementById("deliveryDate").value = activeDate; type document.getElementById("deliveryDate").innerHTML= activeDate; in your script

Display message Google Sheets from Apps Script

I want to display a message on a google sheet. But I don't get it, and, after research here, in documentation, I don't get the answer.
I think that the problem is in "activate" the spreadsheet, where i need to display.
var SEGUIMIENTO = SpreadsheetApp.openById("MyTestediD");
var INF = SEGUIMIENTO.getSheetByName("NameOfSheet");
function TestMessage() {
INF.activate();
Browser.msgBox("Hello")
}
When i run.. nothing happen
I need the definition of Spreadsheet outside the function because I'm working in 2 Spreadsheet's by ID in more that one function.
i only need the correction in my code for display a simple message in the spreadsheet.
PD. i really cant find a simple example of that,
Update
This code it's part of a macro recorder of a Spreadsheet, the same "SpreadsheetApp.openById("MyTestediD");"
I don't know why you try to 'activate' a sheet. If you want display a message I assume you want to do it in the user's current sheet, so:
SpreadsheetApp.getUi().alert('Confirmation received.');
From https://developers.google.com/apps-script/reference/base/browser
The methods in this class are only available for use in the context of a Google Spreadsheet. Please use G Suite dialogs instead.
As you can see, Google is nicely asking you to use G Suite dialogs instead of Class Browser, so be nice too and follow their request.
When you say you want a message in a spreeadsheet, do you mean an alert message? If so, the answer is to use the code SpreadsheetApp.getUi().alert('Hello.'); when the TestMessage function is executed
var SEGUIMIENTO = SpreadsheetApp.openById("My TestediD");
var INF = SEGUIMIENTO.getSheetByName("NameOfSheet");
function TestMessage() {
INF.activate();
SpreadsheetApp.getUi().alert('Hello.');
}

chrome extension: switching from localstorage to chrome.storage.local

I finally got one of my first JS scripts running as planned in Firefox. Now I need to switch to chrome.storage because it will otherwise not run in my extension.
Basically I want to update a Value in a HTML file, which can be changed by input in a submission box.
You are very welcome to pick around in my code, and tell me what is totally abnormal. But I am quite new to JS, and am simply trying to get this to work. Since this worked with localstorage, I guess I have to get it to work with chrome storage too. Once I get it to work, cleaning this mess can begin. Thank you in advance! (I am trying to solve this since around 12 hours not. Can't grasp it.)
the error i get when examining the script:
Uncaught Error: Invocation of form get(string) doesn't match definition get(optional string or array or object keys, function callback)
at normalizeArgumentsAndValidate (extensions::schemaUtils:112:11)
at StorageArea.self.(anonymous function) [as get] (extensions::StorageArea:35:14)
at chrome-extension://fcbadpjebgjnohhcihmkopdbnbjjmnod/initialize_id.js:5:26
options.html this is the "settings" file where one inputs the id which shall be changeable.
</head>
<body>
<p>ENTER YOUR ID FROM tsindex.com BELOW</p>
<form>
<input id="ts_id_js_html" type="text" value="128856"></input>
<br>
<br>
<button onclick="store()">Save/Load</button>
</form>
<script src="initialize_id.js"></script>
<script src="options.js"></script>
<script src="load_id.js"></script>
</body>
</html>
options.js this stores the given ID from the input field in chrome.storage.local (before localstorage)
function store(){
var input_id = document.getElementById("ts_id_js_html").value;
chrome.storage.local.set("ts_id_js", input_id);
}
initialize.js if chrome.storage.local is undefined executes X once. else it gets the stored value and replaces the input in the filed.
var init_count;
if (chrome.storage.local.get("ts_id_js") === undefined && init_count == undefined) {
init_count++; //ignore this for now
} else {
document.getElementById("ts_id_js_html").value = chrome.storage.local.get("ts_id_js");
}
load_id_to_popup.js this gets loaded when the popup.html gets opened, and inputs the given ID in the necessary field.
document.getElementById('input_id').dataset.serverid =
chrome.storage.local.get("ts_id_js");
IGNORE ! load_id.js THIS IS CURRENTLY REDUNDANT, ignore this.
document.getElementById("ts_id_js_html").value =
chrome.storage.local.get("ts_id_js");
chrome.storage.local.get is asynchronous, it is mean, Chrome returns value to callback function:
chrome.storage.local.get("ts_id_js", function(obj) {
let value = obj["ts_id_js"];
});

How to retrieve data from spreadsheet for chart google script. (Using HTML Service)

Hey good morning/afternoon/evening depending where you guys are at!
Just have a quick question for you guys. I've been stuck on this for a bit, and I've tried looking around, but i can't seem to find the answer for this specific issue.
So I'm in the process of trying to create a column chart using google scripts with the html service (since they UIApp service is depreciated now). I'm trying to retrieve the data from a spreadsheet have already created. But when i use this code, the page comes up blank as if there is some error in the background.
var sheet = SpreadsheetApp.openById("1gdRB6FFV426bAj95C0xJlqSucnnX0Z5ATVQdC2");
So here are some specifics:
1) I put this line in my Index.html file within a function I have called
drawChart();
2) I do have them wrapped in this tag.
<script type="text/javascript">
3) I know that this line of code is the cause of the issue because as soon as i comment it out my temp graph with temp data pops up, and page runs fine. But as soon as uncommented it blanks out the whole page.
Any ideas?
I'm wondering if I have to actually place this line of code within the "Code.gs" file, then some how transfer the data from Code.gs to my Index.html file. If that's the case can anyone point me in the direction to where I can follow the direction on how to do it?
Thank you guys in advance.
Sincerely,
Sicariuxs
You must use a withSuccessHandler(functionNameToReceiveData).
<script>
function getData() {
google.script.run
.withSuccessHandler(functionNameToReceiveData)
getData();
};
function functionNameToReceiveData(theDateReceivedHere) {
Logger.log('theDateReceivedHere: ' + theDateReceivedHere;
};
</script>
You can't use: var data = google.script.run.getData(); You must use a withSuccessHandler(functionNameToReceiveData).
#Sandy Good
Hey man I want to thank you for all your help. you're answer was actually great. But there was an additional mistake on top of the ones that you corrected me on. In my actual spreadsheet I had it as a "Date" value. But the format was not matching the data type in my "dataTable". It's working now though. I made all the changes you told me, but in addition I changed the value type from "Date" to "Text". Then in my for loop I wrote a "new Date()" function using the text as the format, and that worked here is some screenshots to show my end result.
link
link

javascript / jquery - google custom search api - functions triggering twice

I'm using the code from the google search API along with my own jquery function to do a simple log to the console, and I noticed the jquery functions are being triggered twice. In addition, javascript errors are being thrown (this happens even on Google's example page).
Here's my code:
<script type="text/javascript">
google.load('search', '1', {language : 'en'});
google.setOnLoadCallback(function() {
var customSearchControl = new google.search.CustomSearchControl('000638822871137547098:_xxgiq7wt_k');
var linkTarget = "frame";
//customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
//customSearchControl.draw('cse');
// Use "mysite_" as a unique ID to override the default rendering.
google.search.Csedr.addOverride("mysite_");
customSearchControl.setLinkTarget(linkTarget)
// Draw the Custom Search Control in the div named "CSE"
customSearchControl.draw('cse');
$('.gsc-search-button').click(function(){
console.log('click');
})
// Execute an initial search
//customSearchControl.execute("ajax");
}, true);
</script>
and here's the javascript error that occurs:
Unsafe JavaScript attempt to access frame with URL about:blank from frame with URL http://www.google.com/cse?q=x&client=google-coop&hl=en&r=s&cx=000638822871137547098%3A_xxgiq7wt_k&oe=UTF-8&ie=UTF-8&format=n4&ad=n0&adsafe=high&nocache=1319551264502&fexp=20606&num=0&safe=off&output=uds_ads_only&source=gcsc&v=3&adext=as1%2Csr1&rurl=http%3A%2F%2Flocalhost%3A8888%2F#slave-1-1. Domains, protocols and ports must match.
Lastly, here's the example from google code:
http://code.google.com/apis/customsearch/docs/js/rendering.html#_intro_CSC
How do I resolve these errors and fix the double click issue?
Looks like I was going about this the wrong way - to do the things I want to do, it's better to use the JSON Custom Search API - with documentation available here:
http://code.google.com/apis/customsearch/v1/overview.html

Categories