Displaying multiple Google Maps asynchronously - google-maps

I currently have a page which shows results of a search. When the user clicks on a result, details are fetched using ajax and loaded into the page. In these details, there is a Google map.
Previously, I had the Gmaps script with callback in the details page. But I ran into this problem that the Gmaps script was inserted multiples times if the user clicked on several results.
Now, I load the script in the results page and the details page calls the initialize function while passing all the necessary parameters. But I get an undefined is not a function error.
So my question is: how to structure the Gmaps script, callback, and asynchronous initializing of the maps between the two pages (results, and details)?
results page
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=[key]"></script>
function initialize(params) {
var directionsService, directionsDisplay, map;
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
// your typical gmaps stuff
}
details page
<div id="map_canvas"></div>
initialize(params);

You can just see if the Google Map's script has already loaded by checking for the "google" global variable that gets added to the DOM.
Full jsfiddle example here: http://jsfiddle.net/gavinfoley/yD8Qt/.
// dom ready
$(function () {
if (typeof google === "undefined") {
alert("Lazy loading Google maps");
lazyLoadGoogleMaps();
} else {
alert("Google Maps is already loaded");
googleMapsLoaded();
}
});
function lazyLoadGoogleMaps() {
// Note the callback function name
$.getScript("http://maps.google.com/maps/api/js?sensor=true&callback=googleMapsLoaded")
.done(function (script, textStatus) {
alert("Google maps loaded successfully");
})
.fail(function (jqxhr, settings, ex) {
alert("Could not load Google Maps: ", ex);
});
}
// This function name is passed in to the Google maps script load above
// and will be called once Google maps has loaded
function googleMapsLoaded() {
alert("Done!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

Related

Check if user has run it

I run a Google Apps script that uploads a file to the user's Google Drive file:
function doGet(e) {
var blob = UrlFetchApp.fetch(e.parameters.url).getBlob();
DriveApp.createFile(blob);
return HtmlService.createHtmlOutput("DONE!");
}
My site loads a popup window that runs a Google Apps Script with that code. Works fine.
Now, how do I communicate back to my site that they user has successfully uploaded the file? As in, how can I communicate back to my server that the user has run doGet()?`
Some type of response handling must exist?
Full working code (test it out on JSBin):
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.js"></script>
</head>
<body>
<div class="google-upload" data-url="https://calibre-ebook.com/downloads/demos/demo.docx">
<span style="background-color: #ddd">Upload</span>
</div>
<script>
$(function() {
$(".google-upload").click(function() {
var url = "https://script.google.com/macros/s/AKfycbwsuIcO5R86Xgv4E1k1ZtgtfKaENaKq2ZfsLGWZ4aqR0d9WBYc/exec"; // Please input the URL here.
var withQuery = url + "?url=";
window.open(withQuery + $('.google-upload').attr("data-url"), "_blank", "width=600,height=600,scrollbars=1");
});
});
</script>
</body>
</html>
So to clarify, I want a way to find out whether if the user has successfully uploaded the file. Something like:
request.execute(function(response) {
if (response.code == 'uploaded') {
// uploaded, do stuff
} else {
// you get the idea...
}
});
Adding a bounty for a complete solution to this.
Rather than returning a HtmlService object, you can pass data using jQuery's $.getJSON method and retrieve data from the doGet function with ContentService. Google Apps Script does not accept CORS, so using JSONP is the best way to get data to and from your script. See this post for more.
Working CodePen Example
I split your HTML and scripts for clarity. None of the HTML changed from your original example.
Code.gs
function doGet(e) {
var returnValue;
// Set the callback param. See https://stackoverflow.com/questions/29525860/
var callback = e.parameter.callback;
// Get the file and create it in Drive
try {
var blob = UrlFetchApp.fetch(e.parameters.url).getBlob();
DriveApp.createFile(blob);
// If successful, return okay
// Structure this JSON however you want. Parsing happens on the client side.
returnValue = {status: 'okay'};
} catch(e) {
Logger.log(e);
// If a failure, return error message to the client
returnValue = {status: e.message}
}
// Returning as JSONP allows for crossorigin requests
return ContentService.createTextOutput(callback +'(' + JSON.stringify(returnValue) + ')').setMimeType(ContentService.MimeType.JAVASCRIPT);
}
Client JS
$(function() {
$(".google-upload").click(function() {
var appUrl = "https://script.google.com/macros/s/AKfycbyUvgKdhubzlpYmO3Marv7iFOZwJNJZaZrFTXCksxtl2kqW7vg/exec";
var query = appUrl + "?url=";
var popupUrl = query + $('.google-upload').attr("data-url") + "&callback=?";
console.log(popupUrl)
// Open this to start authentication.
// If already authenticated, the window will close on its own.
var popup = window.open(popupUrl, "_blank", "width=600,height=600,scrollbars=1");
$.getJSON(popupUrl, function(returnValue) {
// Log the value from the script
console.log(returnValue.status);
if(returnValue.status == "okay") {
// Do stuff, like notify the user, close the window
popup.close();
$("#result").html("Document successfully uploaded");
} else {
$("#result").html(returnValue);
}
})
});
});
You can test the error message by passing an empty string in the data-url param. The message is returned in the console as well as the page for the user.
Edit 3.7.18
The above solution has problems with controlling the authorization flow. After researching and speaking with a Drive engineer (see thread here) I've reworked this into a self-hosted example based on the Apps Script API and running the project as an API executable rather than an Apps Script Web App. This will allow you to access the [run](https://developers.google.com/apps-script/api/reference/rest/v1/scripts/run) method outside an Apps Script web app.
Setup
Follow the Google Apps Script API instructions for JavaScript. The Apps Script project should be a standalone (not linked to a document) and published as API executable. You'll need to open the Cloud Console and create OAuth credentials and an API key.
The instructions have you use a Python server on your computer. I use the Node JS server, http-server, but you can also put it live online and test from there. You'll need to whitelist your source in the Cloud Console.
The client
Since this is self hosted, you'll need a plain HTML page which authorizes the user through the OAuth2 API via JavaScript. This is preferrable because it keeps the user signed in, allowing for multiple API calls to your script without reauthorization. The code below works for this application and uses the authorization flow from the Google quickstart guides.
index.html
<body>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button" style="display: none;">Authorize</button>
<button id="signout-button" style="display: none;">Sign Out</button>
<button onclick="uploadDoc()" style="margin: 10px;" id="google-upload" data-url="https://calibre-ebook.com/downloads/demos/demo.docx">Upload doc</button>
<pre id="content"></pre>
</body>
index.js
// Client ID and API key from the Developer Console
var CLIENT_ID = 'YOUR_CLIENT_ID';
var API_KEY = 'YOUR_API_KEY';
var SCRIPT_ID = 'YOUR_SCRIPT_ID';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://script.googleapis.com/$discovery/rest?version=v1"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = 'https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/script.external_request';
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
var uploadButton = document.getElementById('google-upload');
var docUrl = uploadButton.getAttribute('data-url').value;
// Set the global variable for user authentication
var isAuth = false;
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
// uploadButton.onclick = uploadDoc;
});
}
/**
* Called when the Upload button is clicked. Reset the
* global variable to `true` and upload the document.
* Thanks to #JackBrown for the logic.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn && !isAuth) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
uploadButton.style.display = 'block'
uploadButton.onclick = uploadDoc;
} else if (isSignedIn && isAuth) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
uploadButton.style.display = 'block';
uploadDoc();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
uploadButton.style.display = 'none';
isAuth = false;
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
isAuth = true; // Update the global variable
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
isAuth = false; // update the global variable
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Handle the login if signed out, return a Promise
* to call the upload Docs function after signin.
**/
function uploadDoc() {
console.log("clicked!")
var docUrl = document.getElementById('google-upload').getAttribute('data-url');
gapi.client.script.scripts.run({
'scriptId':SCRIPT_ID,
'function':'uploadDoc',
'parameters': [ docUrl ]
}).then(function(resp) {
var result = resp.result;
if(result.error && result.error.status) {
// Error before the script was Called
appendPre('Error calling API');
appendPre(JSON.parse(result, null, 2));
} else if(result.error) {
// The API executed, but the script returned an error.
// Extract the first (and only) set of error details.
// The values of this object are the script's 'errorMessage' and
// 'errorType', and an array of stack trace elements.
var error = result.error.details[0];
appendPre('Script error message: ' + error.errorMessage);
if (error.scriptStackTraceElements) {
// There may not be a stacktrace if the script didn't start
// executing.
appendPre('Script error stacktrace:');
for (var i = 0; i < error.scriptStackTraceElements.length; i++) {
var trace = error.scriptStackTraceElements[i];
appendPre('\t' + trace.function + ':' + trace.lineNumber);
}
}
} else {
// The structure of the result will depend upon what the Apps
// Script function returns. Here, the function returns an Apps
// Script Object with String keys and values, and so the result
// is treated as a JavaScript object (folderSet).
console.log(resp.result)
var msg = resp.result.response.result;
appendPre(msg);
// do more stuff with the response code
}
})
}
Apps Script
The Apps Script code does not need to be modified much. Instead of returning using ContentService, we can return plain JSON objects to be used by the client.
function uploadDoc(e) {
Logger.log(e);
var returnValue = {};
// Set the callback URL. See https://stackoverflow.com/questions/29525860/
Logger.log("Uploading the document...");
try {
// Get the file and create it in Drive
var blob = UrlFetchApp.fetch(e).getBlob();
DriveApp.createFile(blob);
// If successful, return okay
var msg = "The document was successfully uploaded!";
return msg;
} catch(e) {
Logger.log(e);
// If a failure, return error message to the client
return e.message
}
}
I had a hard time getting CodePen whitelisted, so I have an example hosted securely on my own site using the code above. Feel free to inspect the source and take a look at the live Apps Script project.
Note that the user will need to reauthorize as you add or change scopes in your Apps Script project.

What script to include for both Google Places and Geocoding

I'm struggling to get a Google Places lookup AND Geocoding to work together in the same page. I think there's a conflict in how I'm loading the two APIs.
I'm using this one to load the places API
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&key=*****************&callback=initAutocomplete&types=address" async defer></script>
Places lookup works fine with that.
For Geocoding, this is the first line of code I'm trying to get working
geocoder = new google.maps.Geocoder();
And it works (well, doesn't throw an error) if I include this in my page:
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
But that's pretty much the same URL I already have, and including it breaks the Places lookup. When I have both scripts included I also get a warning telling me I've included the Maps API multiple times which may cause problems.
Please could someone show me which script(s) to include for both to work together? I'm finding the docs pretty confusing at this point to be honest.
It should work fine with just your first include. It contains the base Google Maps API plus the Places library.
var initMap = function () {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
address: '10 Downing St, Westminster, London SW1A 2AA, UK',
}, function (results, status) {
if (status === 'OK') {
var result = results[0];
alert('latitude: ' + result.geometry.location.lat());
}
else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
};
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap" async defer></script>

How use google map API in hybrid app for mobile device

I want download java Script google map API V3 and load them in HTML file from local host instead use them from google API online link.
Because when I'm load API from google server and my device is offline my app has error in use of google API method for render to project. and I'm online after run app but map doesn't work and doesn't load image map.
If you start your app when offline, script tags will throw a net::ERRxxx. You can see this on browser console.
Later, when you come back online, those scripts have failed loading and that is it.
I have tackle this using setTimeout and google maps callback parameter. Basically, I remove and reinject the script tag on page every 5 seconds and set google maps callback to stop the cycle and execute a user callback.
So, as you stated, when you are back online, your script will load and your google maps API will be available inside the callback.
Try this:
loadAPI( function(map) {
console.log('back to business!');
//...
}
code:
var loadAPITimer = null;
function loadAPI(callback) {
var googleMapsScriptId = 'googleMapsScript';
if ( (typeof(loadAPITimer))==="undefined") {
throw('global vars are not defined');
}
if (window.google && window.google.maps) { // API already loaded
window.googleMapsLoadCallback(callback);
return;
}
if (loadAPITimer !== null) { //already running
return;
}
//inject script every 5 seconds
loadAPITimer = setInterval(function() { injectScript(); },5000);
//---- LOCAL FUNCTIONS --------------------------------------------
//---- google maps callback
window.googleMapsLoadCallback = function(cback) {
console.log('done! Inside googleMapsLoadCallback');
if (loadAPITimer) { //still running, cleanUp
clearInterval(loadAPITimer);
loadAPITimer = null;
} else {
console.log('google maps already loaded.');
}
cback && cback(window.google.maps);
}
//---- inject script tag for maps
function injectScript() {
if ( window.google && window.google.maps ) {
console.log('Google Maps Loaded!');
window.googleMapsLoadCallback(callback);
}
else if (window.google && window.google.load) {
console.log('google is defined: loading maps');
window.google.load('maps', version || 3, {'other_params': '&sensor=false' , 'callback' : 'googleMapsLoadCallback'});
}
else {
console.log('injecting Google Maps script');
var script = window.document.getElementById(googleMapsScriptId);
if (script) {
script.parentNode.removeChild(script);
}
window.setTimeout( function() {
script = window.document.createElement('script');
script.id = googleMapsScriptId;
script.type = 'text/javascript';
script.src = 'http://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=googleMapsLoadCallback';
window.document.body.appendChild(script);
}, 100 );
}
}
}

Ignore hidden features returned by identifyTask

I am building an app using javascript, google maps v2 and ESRI 10.1.
I have a DynamicMapServiceLayer and a single layer in my ESRI map service. I dynamically show or hide features on the layer using the ESRI setLayerDefinitions function based on filter values selected by the user at runtime.
When the user clicks on the map I use the ESRI IdentifyTask object to find what the user clicked on. I want to show an infowindow for the feature the user clicked on. My code is sort of working but it opens infowindows for features that are filtered out (not visible) on the layer.
How can I check to see if the user clicked on a visible feature and stop opening infowindows for hidden features? Or how can I get IdentifyTask to stop including hidden features in the response object it returns?
This is my identifyParameters task invoke set up
// set the identify parameters
var identifyParameters = new esri.arcgis.gmaps.IdentifyParameters();
identifyParameters.geometry = latLng; // where the user clicked on the map
identifyParameters.tolerance = 3;
identifyParameters.layerIds = [OUTAGES_LAYER];
identifyParameters.layerOption = 'all';
identifyParameters.bounds = map.getBounds();
var mapSize = map.getSize();
identifyParameters.width = mapSize.width;
identifyParameters.height = mapSize.height;
// execute the identify operation
identifyTask.execute(identifyParameters, function(response, error) {
if (hasErrorOccurred(error)) return;
addResultToMap(response, latLng);
});
UPDATE
I have upgraded to Google maps v3. Now the identify parameters support passing layerdef information as follows below. For example I can limit the identify operation to those features where FISCAL_YEAR = 2014. My problem is solved.
function identify(evt) {
dynamicMap.getMapService().identify({
'geometry': evt.latLng,
'tolerance': 3,
'layerIds': [12],
'layerOption': 'all',
'layerDefs': {12 : 'FISCAL_YEAR = 2014'},
'bounds': map.getBounds(),
'width': map.getDiv().offsetWidth,
'height': map.getDiv().offsetHeight
}, function(results, err) {
if (err) {
alert(err.message + err.details.join('\n'));
} else {
addResultToMap(results, evt.latLng);
}
});
}

Google Maps API Async Loading

I am loading the Google Maps API script Asynchronously in IE9 using the following code:
function initialize() {
...
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=TRUE_OR_FALSE&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
Now the thing is that when the script is fully loaded the initialize() function is called automatically. But when sometimes the user quota has been exceeded the initialize() function is not called and instead of map we see the plain white screen.
I want to detect this and fire my custom function which displays some alert like: "Error!".
Can anyone tell me to how to do this?
Thanks in advance...
As Andrew mentioned, there isn't a direct way to handle this. However, you can at least account for the possibility.
Set a timeout for a reasonable time frame (5 secondes?). In the timeout callback function, test for the existence of google and/or google.maps. If it doesn't exist, assume the script load failed.
setTimeout(function() {
if(!window.google || !window.google.maps) {
//handle script not loaded
}
}), 5000);
// Maps api asynchronous load code here.
I finally found the solution for this problem. Chad gave a nice solution but the only thing is that you can't put that piece of code in the callback() function because if the script fails to load the callback() function is never called!
So based on what Chad has mentioned I finally came up with the following solution:
function initialize() {
...
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=TRUE_OR_FALSE&callback=initialize";
setTimeout(function () {
try{
if (!google || !google.maps) {
//This will Throw the error if 'google' is not defined
}
}
catch (e) {
//You can write the code for error handling here
//Something like alert('Ah...Error Occurred!');
}
}, 5000);
document.body.appendChild(script);
}
window.onload = loadScript;
This seems to work fine for me! :)