Bing Maps V8 Web Control and CommonJS - javascript

I am using Bing Maps V8 Web Control in a web application. I am also using Brunch to manage static assets, including JavaScript. By default, Brunch wraps all non-vendor JavaScript code in CommonJS modules.
Microsoft's documentation says to initialize the control with a callback parameter in the script import URL, like this:
<script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?branch=release&callback=loadMapScenario' async defer></script>
With the loadMapScenario defined like this:
Microsoft.Maps.loadModule('Microsoft.Maps.AutoSuggest', {
callback: onLoad,
errorCallback: onError,
credentials: 'Your Bing Maps Key'
});
function onLoad() {
var options = { maxResults: 5 };
var manager = new Microsoft.Maps.AutosuggestManager(options);
manager.attachAutosuggest('#searchBox', '#searchBoxContainer', selectedSuggestion);
}
function onError(message) {
document.getElementById('printoutPanel').innerHTML = message;
}
function selectedSuggestion(suggestionResult) {
document.getElementById('printoutPanel').innerHTML =
'Suggestion: ' + suggestionResult.formattedSuggestion +
'<br> Lat: ' + suggestionResult.location.latitude +
'<br> Lon: ' + suggestionResult.location.longitude;
}
The issue is that I get an error from the API saying that the callback function is invalid.
Is there a better way to do this? Is there a way for the web control to call a CommonJS-wrapped function in this manner?

See the issues with your code below:
<script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?branch=release&callback=loadMapScenario' async defer></script> In this line a callback function loadMapScenario is defined but its not exists.
Map functions call only after including bing map library js.
Solution
There is a sample code provided by bing maps. See http://www.bing.com/api/maps/sdk/mapcontrol/isdk#autoSuggestUiWithoutMap+HTML
If you are unable to see the above link then just see the below code. Just use your bing map api key to connect. Sample code provided here is Auto suggest without loading map. You can see different options in the above link.
<!DOCTYPE html>
<html>
<head>
<title>autoSuggestUiWithoutMapHTML</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
</head>
<body>
<div id='printoutPanel'></div>
<div id='searchBoxContainer'><input type= 'text' id= 'searchBox'/></div>
<div id='myMap' style='width: 100vw; height: 100vh;'></div>
<script type='text/javascript'>
function loadMapScenario() {
Microsoft.Maps.loadModule('Microsoft.Maps.AutoSuggest', {
callback: onLoad,
errorCallback: onError,
credentials: 'Your Bing Maps Key'
});
function onLoad() {
var options = { maxResults: 5 };
var manager = new Microsoft.Maps.AutosuggestManager(options);
manager.attachAutosuggest('#searchBox', '#searchBoxContainer', selectedSuggestion);
}
function onError(message) {
document.getElementById('printoutPanel').innerHTML = message;
}
function selectedSuggestion(suggestionResult) {
document.getElementById('printoutPanel').innerHTML =
'Suggestion: ' + suggestionResult.formattedSuggestion +
'<br> Lat: ' + suggestionResult.location.latitude +
'<br> Lon: ' + suggestionResult.location.longitude;
}
}
</script>
<script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?branch=release&callback=loadMapScenario' async defer></script>
</body>

Related

Unable to Consume Linkedin API through Localhost

I found similar threads but unfortunately didn't help resolve my issue so posting a new thread
I am trying to consume the linked API through localhost. The error I am getting is:
Uncaught Error: You must specify a valid JavaScript API Domain as part of this key's configuration.
Under Javascript Settings, Valid SDK Domains I added
http://127.0.0.1
http://127.0.0.1:8704
http://localhost
http://localhost:8704
http://localhost
I tried adding in https as well but still I am facing the same error.
I tried creating a ASP.NET project in Visual studio and tried running my html file with the associated port number which also I added in valid SDK domain, still the same issue.
My code is below:
<html>
<head>
<script type="text/javascript" src="https://platform.linkedin.com/in.js">
api_key: [MY KEY] //Client ID
onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load
authorize: true
</script>
</head>
<script type="text/javascript">
function OnLinkedInFrameworkLoad() {
console.log('OnLinkedInFrameworkLoad');
IN.Event.on(IN, "auth", OnLinkedInAuth);
}
function OnLinkedInAuth() {
console.log('OnLinkedInAuth');
IN.API.Profile("me").result(ShowProfileData);
}
function ShowProfileData(profiles) {
console.log('ShowProfileData' + profiles);
var member = profiles.values[0];
var id = member.id;
var firstName = member.firstName;
var lastName = member.lastName;
var photo = member.pictureUrl;
var headline = member.headline;
//use information captured above
var stringToBind = "<p>First Name: " + firstName + " <p/><p> Last Name: "
+ lastName + "<p/><p>User ID: " + id + " and Head Line Provided: " + headline
+ "<p/>"
document.getElementById('profiles').innerHTML = stringToBind;
}
</script>
<body>
<div id="profiles"></div>
</body>
</html>

YouTube API -- extracting title and videoId attributes to build hyperlink

The following is a JavaScript file that searches through YouTube video data using its API. Down at the bottom you'll see the onSearchResponse() function, which calls showResponse(), which in turn displays the search results.
As this code from Codecademy stands, a HUGE amount of information gets printed relating to my search term.
Instead of all that, can I simply display a hyperlink using the title and videoId attributes? How would I go about altering responseString in showResponse() to build that link? Thank you!
// Your use of the YouTube API must comply with the Terms of Service:
// https://developers.google.com/youtube/terms
// Helper function to display JavaScript value on HTML page.
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
// Called automatically when YouTube API interface is loaded (see line 9).
function onYouTubeApiLoad() {
// This API key is intended for use only in this lesson.
// See link to get a key for your own applications.
gapi.client.setApiKey('AIzaSyCR5In4DZaTP6IEZQ0r1JceuvluJRzQNLE');
search();
}
function search() {
// Use the JavaScript client library to create a search.list() API call.
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: 'clapton'
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}
// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
showResponse(response);
console.log(response);
}
Here is the corresponding HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="stylesheets/styles.css">
<meta charset="UTF-8">
<title>My YouTube API Demo</title>
</head>
<body>
<section>
<div id="response"></div>
</section>
<script src="javascripts/search-2.js"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</body>
</html>
Your advice is much appreciated!
I think it might be what you are exactly trying to do.
function showResponse(response) {
var html = response.items.map(itemToHtml);
document.getElementById('response').innerHTML += html;
}
function itemToHtml(item) {
var title = item.snippet.title;
var vid = item.id.videoId;
return generateHyperlink(title, vid);
}
function generateHyperlink(title, vid) {
return '' + title + '<br/>';
}
This code show up links named title having YouTube video link using videoId.

Error showing GSheet range using Google Visualization API in Google Apps Script Web App

I'm trying to display a Google Spreadsheet range using Google Table Visualization API via Google Apps Script Web App. I plan to deploy the Web App into a Google Site. When I copy the code to a Google Apps Script Web App Project and deploy the web app, the query response is "Bad Request [400]". How do I debug further?
Alternative Solutions:
Manual effort: Google Sites has a gadget to pull a Gspreadsheet range onto a webpage, but I want to do it programmatically for 70 different ranges and pages.
Pure Google Apps Script: I can programmatically create copies of a web page template containing Table Gadgets and edit table range. There is a known issue that breaks gadgets when you edit the HTML content (google-apps-script-issues #572).
Source Google Spreadsheet (fake public data)
https://docs.google.com/spreadsheets/d/1miOxJ3jPCLE66mWcZmd2q-1YAu6so-GbxjcmIDtXUV4
JS Fiddle code works. I can query the Google Spreadsheet and draw the Google Visualization Table.
https://jsfiddle.net/xcghpgmt/6/
Also works as a snippet.
function drawChart() {
var key = '1miOxJ3jPCLE66mWcZmd2q-1YAu6so-GbxjcmIDtXUV4';
var GID = 0;
var range = 'A3:h18';
var queryString = 'https://docs.google.com/spreadsheets/d/'+key+'/gviz/tq?gid='+GID+'&range='+range;
// Set Data Source
var query = new google.visualization.Query(queryString);
// Send the query with callback function
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
// Handle Query errors
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
// Draw Chart
var data = response.getDataTable();
var chart = new google.visualization.Table(document.getElementById('chart_div'));
chart.draw(data);
}
google.load('visualization', '1', {packages:['table'], callback: drawChart});
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>
Code.gs
function doGet() {
var html = HtmlService.createTemplateFromFile("Index").evaluate();
html.setTitle("Dynamic Webpage");
return html;
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.getContent();
}
Index.html
<!DOCTYPE html>
<html>
<header>
</header>
<body>
<div id="chart_div"></div>
</body>
<?!= include('JavaScript.html'); ?>
</html>
Javascript.html
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
function drawChart() {
var key = '1miOxJ3jPCLE66mWcZmd2q-1YAu6so-GbxjcmIDtXUV4';
var GID = 0;
var range = 'A3:h18';
var queryString = 'https://docs.google.com/spreadsheets/d/'+key+'/gviz/tq?gid='+GID+'&range='+range;
// Set Data Source
var query = new google.visualization.Query(queryString);
// Send the query with callback function
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
// Handle Query errors
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
// Draw Chart
var data = response.getDataTable();
var chart = new google.visualization.Table(document.getElementById('chart_div'));
chart.draw(data);
}
google.load('visualization', '1', {packages:['table'], callback: drawChart});
</script>
You haven't set the sandboxing for your application properly, so the caja sanitization is stripping out the jsapi.
Change:
function doGet() {
var html = HtmlService.createTemplateFromFile("Index").evaluate();
html.setTitle("Dynamic Webpage");
return html;
}
To:
function doGet() {
var html = HtmlService.createTemplateFromFile("Index").evaluate();
html.setTitle("Dynamic Webpage").setSandboxMode(HtmlService.SandboxMode.IFRAME);
return html;
}
You can remove the sandboxing statement altogether from the include() function, since it's the application you need to sandbox. Better yet delete include() and use this in Index.html instead:
<?!= HtmlService.createHtmlOutputFromFile('JavaScript').getContent(); ?>

How to Login with linkedin using javascript and display profile information

I want to integrate Linkedin login using javascript.
I searched for that and get relevant results. But lot of search results says that below code:
<script type="in/Login">
</script>
is used to create sign-in button. But i want to use my own custom button and call a function on "onClick" event in my HTML.
Help in correct direction.
My code :
function linkedinLogin(){
console.log('linkedinLogin called');
var src="http://platform.linkedin.com/in.js"
api_key: 'XXXXXXXXXXXXXXXX'
authorize: true
onLoad: OnLinkedInFrameworkLoad
}
function OnLinkedInFrameworkLoad()
{
IN.Event.on(IN, "auth", OnLinkedInAuth);
}
function OnLinkedInAuth() {
IN.API.Profile("me").result(ShowProfileData);
}
function ShowProfileData(profiles)
{
var member = profiles.values[0];
console.log(member);
var id=member.id;
var firstName=member.firstName;
var lastName=member.lastName;
var photo=member.pictureUrl;
var headline=member.headline;
//use information captured above
var str="<b>id</b> : "+id+"<br>";
str +="<b>firstName: </b>"+firstName+"<br>";
str +="<b>lastName: </b>"+lastName+"<br>";
str +="<b>photo: </b>"+photo+"<br>";
str +="<b>headline: </b>"+headline+"<br>";
str +="<input type='button' value='Logout' onclick='logout();'/>";
document.getElementById("status").innerHTML = str;
}
And this is my HTML snippet:
<li>
<a href="javascript:void(0);" onClick="linkedinLogin()">
<img src="images/icon_linkedIn.png" />
<span>LinkedIn</span>
</a>
</li>
<html>
<head>
<title>LinkedIn JavaScript API Hello World</title>
<!-- 1. Include the LinkedIn JavaScript API and define a onLoad callback function -->
<script type="text/javascript" src="https://platform.linkedin.com/in.js">
api_key: xxx
onLoad: onLinkedInLoad
authorize: true
</script>
<script type="text/javascript">
// 2. Runs when the JavaScript framework is loaded
function onLinkedInLoad() {
IN.Event.on(IN, "auth", onLinkedInAuth);
}
// 2. Runs when the viewer has authenticated
function onLinkedInAuth() {
IN.API.Profile("me").fields("id","first-name", "last-name", "email-address").result(displayProfiles);
}
// 2. Runs when the Profile() API call returns successfully
function displayProfiles(profiles) {
member = profiles.values[0];
document.getElementById("profiles").innerHTML =
"<p>"+member.id+"<br> " + member.firstName + "<br> " + member.lastName + "<br>"+member.emailAddress+"</p>";
}
</script>
</head>
<body>
<!-- 3. Displays a button to let the viewer authenticate -->
<script type="in/Login"></script>
<!-- 4. Placeholder for the greeting -->
<div id="profiles"></div>
</body>
</html>
Can you try this ?

Youtube Data Api - Uncaught TypeError: Cannot read property 'setApiKey' of undefined

I search music with youtube data api. I use javascript and jquery and i have a problem.
Here is my code
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="<?php echo SITE_PUBLIC; ?>/bootstrap-3.2.0/dist/js/bootstrap.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
<script>
function keyWordsearch(){
gapi.client.setApiKey('myapikey');
gapi.client.load('youtube', 'v3', function() {
data = jQuery.parseJSON( '{ "data": [{"name":"eminem"},{"name":"shakira"}] }' );
$.each(data["data"], function( index, value ) {
makeRequest(value["name"]);
});
});
}
function makeRequest(q) {
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet',
maxResults: 10
});
request.execute(function(response) {
$('#results').empty()
var srchItems = response.result.items;
$.each(srchItems, function(index, item) {
vidTitle = item.snippet.title;
vidThumburl = item.snippet.thumbnails.default.url;
vidThumbimg = '<pre><img id="thumb" src="'+vidThumburl+'" alt="No Image Available." style="width:204px;height:128px"></pre>';
$('#results').append('<pre>' + vidTitle + vidThumbimg + '</pre>');
})
})
}
keyWordsearch();
</script>
This code not working. Chrome console say "Uncaught TypeError: Cannot read property 'setApiKey' of undefined". But this code is working:
keyWordsearch() to
$(document).click(function(){
keyWordsearch()
})
I do not understand this issue. Thanks in advance
EDIT
My code run on jsFiddle.But not run my html file. My html file is here:
<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
<div id="container">
<h1>Search Results</h1>
<ul id="results"></ul>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
<script>
$(function(){
function keyWordsearch(){
gapi.client.setApiKey('AIzaSyCWzGO9Vo1eYOW4R4ooPdoFLmNk6zkc0Jw');
gapi.client.load('youtube', 'v3', function() {
data = jQuery.parseJSON( '{ "data": [{"name":"eminem"}] }' );
$.each(data["data"], function( index, value ) {
makeRequest(value["name"]);
});
});
}
function makeRequest(q) {
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet',
maxResults: 10
});
request.execute(function(response) {
$('#results').empty()
var srchItems = response.result.items;
$.each(srchItems, function(index, item) {
vidTitle = item.snippet.title;
vidThumburl = item.snippet.thumbnails.default.url;
vidThumbimg = '<pre><img id="thumb" src="'+vidThumburl+'" alt="No Image Available." style="width:204px;height:128px"></pre>';
$('#results').append('<pre>' + vidTitle + vidThumbimg + '</pre>');
})
})
}
keyWordsearch();
})
</script>
</body>
</html>
Looks like, you haven't load the javascript library. That's why it can't find the reference.
You can add it like:
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
You can specify an initial function while calling the API like this: client.js?onload=init (see my example below). Besides no need of a doucument.ready() wrapper. I'm not sure why it works with your API key on my local machine but I guess it's some kind of magic that checks if the site is availible to the public - if true the referrer entries in your google account will get important - correct me on that if somebody knows whats exactly happening here.
My code:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
<!--<link rel="stylesheet" type="text/css" media="screen" href="main.css" />-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<script type="text/javascript">
function makeRequest(q) {
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet',
maxResults: 3
});
request.execute(function(response) {
$('#results').empty();
var resultItems = response.result.items;
$.each(resultItems, function(index, item) {
vidTitle = item.snippet.title;
vidThumburl = item.snippet.thumbnails.default.url;
vidThumbimg = '<pre><img id="thumb" src="'+vidThumburl+'" alt="No Image Available." style="width:204px;height:128px"></pre>';
$('#results').append('<pre>' + vidTitle + vidThumbimg + '</pre>');
});
});
}
function init() {
gapi.client.setApiKey('AIzaSyCWzGO9Vo1eYOW4R4ooPdoFLmNk6zkc0Jw');
gapi.client.load('youtube', 'v3', function() {
data = jQuery.parseJSON( '{ "data": [{"name":"orsons"}] }' );
$.each(data["data"], function(index, value) {
makeRequest(value["name"]);
});
});
}
</script>
<script type="text/javascript" src="https://apis.google.com/js/client.js?onload=init"></script>
</head>
<body>
<h1>YouTube API 3.0 Test</h1>
<ul id="results"></ul>
</body>
</html>
In addition to all the answers which explain that you must specify and provide a callback function for the Google API client <script> loading line, I'd like to point out that it seems that the onload parameter will never run the specified function (at least in Chrome) when you load the Google API client.js from a local file (even though you are serving the HTML page via a webserver and not loading it from the file-system, which apparently seemed to be the only gotcha with the Google API JS client...).
e.g.:
<script src="/lib/js/client.js?onload=handleClientLoad"></script>
Although client.js will be loaded, this will never launch the handleClientLoad function when it's finished loading. I thought it would be useful to point this out, as this was a really frustrating thing to debug.
Hope this helps.
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
This MUST be called at the end, or at least after you define your method "handleClientLoad". This is its callback, and only after it was called - it means google api is ready. This is why you get gapi.client is null.
For the fun of it, you can use a timeout of a few seconds before using gapi.client and see it is not null anymore.

Categories

Resources