TypeError: Cannot read property 'getChild' of null - Apps Script - github

I am a newbie and am trying to use a script to send our school website's feeds
to our Google Chat (Google Workspace for Edu).
I found a code here that works like a charm with the testing Url (https://cloudblog.withgoogle.com/products/gcp/rss/),
but returns me an error when I point to our school's website.
TypeError: Cannot read property 'getChild' of null
Here is the code and below the Debug error
// URL of the RSS feed to parse
var RSS_FEED_URL = "https://www.icriccardomassa.edu.it/agid/feed/";
// https://cloudblog.withgoogle.com/products/gcp/rss/"; <- this works!
// Webhook URL of the Hangouts Chat room
var WEBHOOK_URL = "https://chat.googleapis.com/v1/spaces/AAAAueQ0Yzk/messages?key=AI [..]";
// When DEBUG is set to true, the topic is not actually posted to the room
var DEBUG = false;
function fetchNews() {
var lastUpdate = new Date(PropertiesService.getScriptProperties().getProperty("lastUpdate"));
var lastUpdate = new Date(parseFloat(PropertiesService.getScriptProperties().getProperty("lastUpdate")) || 0);
Logger.log("Last update: " + lastUpdate);
Logger.log("Fetching '" + RSS_FEED_URL + "'...");
var xml = UrlFetchApp.fetch(RSS_FEED_URL).getContentText();
var document = XmlService.parse(xml);
// var items = document.getRootElement().getChild('channel').getChildren('item').reverse();
var items = document.getRootElement().getChild('channel').getChildren('item').reverse();
Logger.log(items.length + " entrie(s) found");
var count = 0;
for (var i = 0; i < items.length; i++) {
var pubDate = new Date(items[i].getChild('pubDate').getText());
var og = items[i].getChild('og');
var title = og.getChild("title").getText();
var description = og.getChild("description").getText();
var link = og.getChild("url").getText();
if(DEBUG){
Logger.log("------ " + (i+1) + "/" + items.length + " ------");
Logger.log(pubDate);
Logger.log(title);
Logger.log(link);
// Logger.log(description);
Logger.log("--------------------");
}
if(pubDate.getTime() > lastUpdate.getTime()) {
Logger.log("Posting topic '"+ title +"'...");
if(!DEBUG){
postTopic_(title, description, link);
}
PropertiesService.getScriptProperties().setProperty("lastUpdate", pubDate.getTime());
count++;
}
}
Logger.log("> " + count + " new(s) posted");
}
function postTopic_(title, description, link) {
var text = "*" + title + "*" + "\n";
if (description){
text += description + "\n";
}
text += link;
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify({
"text": text
})
};
UrlFetchApp.fetch(WEBHOOK_URL, options);
}
Thank you in advance for your help!
Debugger errors

Related

Enterprise Architect - How to set column key to Autonum?

I have a bunch of tables with Id int primary keys. However, I forgot to set AutoNum to True in the UI. Since changing all hundreds of tables is tedious, how can I set this property for all Id columns?
I have built a script that runs through each table and detects the Id column:
var package as EA.Package;
package = Repository.GetTreeSelectedPackage();
var tablesEnumerator = new Enumerator(package.Elements);
while (!tablesEnumerator.atEnd()) {
var table as EA.Element;
table = tablesEnumerator.item();
var methodsEnumerator = new Enumerator(table.Methods);
while (!methodsEnumerator.atEnd()) {
var method as EA.Method;
method = methodsEnumerator.item();
if (method.Name !== "Id") { continue; }
Session.Output(method.Name);
// Now what?!
}
}
I have searched for AutoNum in EnterpriseArchitect docs and APIs, but was unable to find suitable references.
According to Autonum in Column Properties inaccessible you can actually change the AutoNum behaviour via API with the means of TaggedValues. So there is no need of direct SQL updates to the database.
Setting the tagged values property and AutoNum on the Id attribute (not the method of the table seems to do the magic. It tried it via the builtin script engine and it works:
Before running the script
After running the script
The update script
!INC Local Scripts.EAConstants-JScript
function main()
{
var package = Repository.GetTreeSelectedPackage();
var elements as EA.Collection;
elements = package.Elements;
Session.Output("Elements Count " + elements.Count);
for ( var ec = 0 ; ec < elements.Count ; ec++ )
{
var element as EA.Element;
element = elements.GetAt(ec);
if("Table" != element.MetaType) continue;
Session.Output("Element: Name '" + element.Name + "' [" + element.ElementGUID + "] '" + element.MetaType + "'.");
var attributes as EA.Collection;
attributes = element.Attributes;
for ( var ac = 0; ac < attributes.Count ; ac++)
{
var attribute as EA.Attribute;
attribute = attributes.GetAt(ac);
if("Id" != attribute.Name) continue;
Session.Output("Attribute: Name '" + attribute.Name + "' [" + attribute.AttributeGUID + "] in element '"+ element.Name + "' [" + element.MetaType + "].");
var hasTvProperty = false;
var hasTvAutonum = false;
var taggedValues as EA.Collection;
taggedValues = attribute.TaggedValues;
Session.Output("TaggedValues: Count " + taggedValues.Count);
for ( var tc = 0; tc < taggedValues.Count; tc++)
{
var taggedValue as EA.TaggedValue;
taggedValue = taggedValues.GetAt(tc);
if("property" != taggedValue.Name && "AutoNum" != taggedValue.Name) continue;
Session.Output("TaggedValue: Name '" + taggedValue.Name + "'. Value '" + taggedValue.Value + "'");
if("property" != taggedValue.Name)
{
taggedValue.Value = "AutoNum=1;StartNum=1;Increment=1;";
taggedValue.Update();
element.Update();
hasTvProperty = true;
}
if("AutoNum" != taggedValue.Name)
{
taggedValue.Value = "True";
taggedValue.Update();
element.Update();
hasTvAutonum = true;
}
}
if(!hasTvProperty)
{
var tv = taggedValues.AddNew("property", "AutoNum=1;StartNum=1;Increment=1;");
tv.Update();
element.Update();
}
if(!hasTvAutonum)
{
var tv = taggedValues.AddNew("AutoNum", "True");
tv.Update();
element.Update();
}
break;
}
}
}
main();
Content of the t_attributetags table

How to get the data without breaking the call in the Facebook Graph API?

What I need to do to circumvent this issue, because when I request data for 2 months I already receive this error, when there is a break per day, I have the following call. With Little data works perfect, but when I increase the period the server brings me
User request limit reached","type":"OAuthException","is_transient":true,"code":17,"error_subcode":2446079,"fbtrace_id":"...
function solicitacaoAssicrona(){
var service = getService()
var batch = [{"method": "GET", "relative_url":"v3.2/act_1125789557444919/insights/impressions,reach,frequency,spend,campaign_name,account_name,clicks,cost_per_10_sec_video_view,cpm,cpp?level=campaign&since=2016-03-03&until=2019-03-04&time_increment=1&limit=100"}]
// var batchUrl = encodeURIComponent(JSON.stringify(batch));
// Logger.log(batchUrl);
var url = "https://graph.facebook.com?include_headers=false&batch=" + encodeURIComponent(JSON.stringify(batch))
var response = UrlFetchApp.fetch(url, {
method: 'POST',
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(response.getContentText());
Logger.log(result)
// response.forEach(function(resp){
// var resp = JSON.parse(resp.body);
// //Logger.log(JSON.stringify(resp, null, 2));
//
//// resp.data[0].values.forEach(function(response){
////
////
//// })
////
// })
}
I'Ve looked at the documentation, but to the moment without success!
https://developers.facebook.com/docs/marketing-api/insights/best-practices/
That's the call I have
var metricas = [
'impressions',
'reach',
'unique_clicks',
'account_currency',
'account_id',
'account_name',
'ad_id',
'ad_name',
'adset_id',
'adset_name',
'buying_type',
'campaign_id',
'campaign_name',
'clicks',
'cost_per_inline_link_click',
'cost_per_inline_post_engagement',
'cost_per_unique_click',
'cost_per_unique_inline_link_click',
'cpc',
'cpm',
'cpp',
'ctr',
'date_start',
//'date_stop',
'frequency',
'inline_link_click_ctr',
'inline_link_clicks',
'inline_post_engagement',
'objective',
'relevance_score',
'social_spend',
'spend',
'unique_ctr',
'unique_inline_link_click_ctr',
'unique_inline_link_clicks',
'unique_link_clicks_ctr',
//'website_ctr',
'video_10_sec_watched_actions',
'cost_per_10_sec_video_view',
'video_30_sec_watched_actions',
'video_avg_percent_watched_actions',
'video_avg_time_watched_actions',
'video_p100_watched_actions',
'video_p25_watched_actions',
'video_p50_watched_actions',
'video_p75_watched_actions',
'video_play_actions',
'video_thruplay_watched_actions',
'video_p95_watched_actions',
]
var parameters = metricas.join(',');
var url = 'https://graph.facebook.com/v3.2/act_xxxxxxxxxx/insights?fields= + parameters + '&level=ad&time_range[since]=2019-02-05&time_range[until]=2019-04-05&time_increment=1&limit=200'
It's to do with how much data you can retrieve with batch requests. For longer periods, you should divide it into smaller chunks, sequential to each other, thus retrieving the data needed in multiple requests. Have a look at this example:
Code.gs
From line 88 of the file, you can see how it can be divided in multiple requests.
https://github.com/halsandr/Facebook_Connector/blob/master/Code.gs
function dateDelta(dObj, num) {
if (isNaN(num)) {
var dateStart = new Date(dObj);
} else {
var dateStart = new Date(dObj);
var dateStart = new Date(dateStart.setDate(dateStart.getDate() + num));
}
var dd = dateStart.getDate();
var mm = dateStart.getMonth()+1; //January is 0!
var yyyy = dateStart.getFullYear();
if(dd<10){
dd='0'+dd;
}
if(mm<10){
mm='0'+mm;
}
var dateStart = yyyy + "-" + mm + "-" + dd;
return dateStart;
}
var gStartDate = new Date(request.dateRange.startDate);
var gStartDate = new Date(dateDelta(gStartDate, -1));
var gEndDate = new Date(request.dateRange.endDate);
var gEndDate = new Date(dateDelta(gEndDate, +1));
var gRange = Math.ceil(Math.abs(gEndDate - gStartDate) / (1000 * 3600 * 24));
var gBatches = Math.ceil(gRange / 92);
if (gBatches < 2) {
var batch = [{"method": "GET", "relative_url": request.configParams.pageID + "/insights/page_fans,page_impressions,page_post_engagements?since=" + dateDelta(gStartDate) + "&until=" + dateDelta(gEndDate)}];
//console.log(batch);
} else {
batch = [];
var iterRanges = gRange / gBatches;
for (i = 0; i < gBatches; i++) {
var iterStart = dateDelta(gStartDate, (iterRanges * i));
if (i == (gBatches - 1)) {
var iterEnd = dateDelta(gEndDate);
} else {
var iterEnd = dateDelta(gStartDate, (iterRanges * (i + 1)) + 1);
}
batch.push({"method": "GET", "relative_url": request.configParams.pageID + "/insights/page_fans,page_impressions,page_post_engagements?since=" + iterStart + "&until=" + iterEnd})
}
//console.log(batch);
}
// Fetch the data with UrlFetchApp
var url = "https://graph.facebook.com?include_headers=false&batch=" + encodeURIComponent(JSON.stringify(batch))

Add a user to a group programatically

Is it possible to add a user to a group via REST/sdk?
Scenario: We want to add all our users to a mandatory group on a regularly basis.
Thanks!Max
you can get group ids from share point list like this
function GetMandatoryGroups() {
var context;
var factory;
var appContextSite;
var oList;
var collListItem;
context = new SP.ClientContext(appweburl);
factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, hostweburl);
this.web = appContextSite.get_web();
oList = this.web.get_lists().getByTitle('MandatoryGroups');
context.load(oList);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><RowLimit>100</RowLimit></View>');
collListItem = oList.getItems(camlQuery);
context.load(collListItem, 'Include(Title,Id)');
context.executeQueryAsync(
Function.createDelegate(this, successHandler),
Function.createDelegate(this, errorHandler)
);
function successHandler() {
MandatoryGroups = new Array();
var listItemInfo = '';
var listitemenumerator = collListItem.getEnumerator();
while (listitemenumerator.moveNext()) {
var olistitem = listitemenumerator.get_current();
//listItemInfo += '<li>ID:' + olistitem.get_id().toString() + ' GroupID: ' + olistitem.get_item('Title') + '</li>';
MandatoryGroups.push(olistitem.get_item('Title'));
}
AutoJoinGroups();
// document.getElementById("message").innerHTML = 'Lists found' + oList.get_title() + ':<ul>' + listItemInfo + '</ul>';
}
function errorHandler(sender, args) {
document.getElementById("message").innerText =
"Could not complete cross-domain call: " + args.get_message();
}
}
you can join users to the mendatory groups like this (after user logs in )
function AutoJoinGroups() {
yam.platform.request({
// yam.request({
url: "groups.json?mine=1",
method: "GET",
data: {},
success: function (group) {
//for ($i = 0; $i < MandatoryGroups.length; $i++) {
// if (!ArrayContains(MandatoryGroups[$i].toString(), group)) {
// joinGroupAsync(MandatoryGroups[$i].toString());
// setTimeout('', 10000);
// // setTimeout(joinGroupAsync(MandatoryGroups[$i].toString()),5000);
// }
//}
var i = 0;
function AsyncAutoJoinLoop() {
if (i < MandatoryGroups.length) {
if (!ArrayContains(MandatoryGroups[i].toString(), group)) {
setTimeout(function () {
joinGroupAsync(MandatoryGroups[i].toString());
i++;
if (i < MandatoryGroups.length) {
AsyncAutoJoinLoop();
}
}, 3000)
}
}
}
AsyncAutoJoinLoop();
// getMyGroups();
},
error: function (group) {
console.error("There was an error with the request.");
}
});
}
function joinGroupAsync(id) {
yam.platform.request({
// yam.request({
url: "group_memberships.json?group_id=" + id,
method: "POST",
data: {},
success: function (group) {
},
error: function (group) {
console.error("There was an error with the request.");
}
});
}
you can add group to the sharepoint list like this.
function InsertMandatoryItem() {
var context;
var factory;
var appContextSite;
var oListItem;
context = new SP.ClientContext(appweburl);
factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, hostweburl);
this.web = appContextSite.get_web();
var oList = this.web.get_lists().getByTitle('MandatoryGroups');
var itemCreateInfo = new SP.ListItemCreationInformation();
oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('Title', InsertGroupId);
oListItem.update();
context.load(oListItem);
context.executeQueryAsync(
Function.createDelegate(this, onQuerySucceeded),
Function.createDelegate(this, onQueryFailed)
);
function onQuerySucceeded() {
//alert('Item created: ' + oListItem.get_id());
// getMyGroups();
// AutoJoinGroups();
$.getScript(scriptbase + 'SP.RequestExecutor.js', GetMandatoryGroups);
}
function onQueryFailed(sender, args) {
$.getScript(scriptbase + 'SP.RequestExecutor.js', GetMandatoryGroups);
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
}
You can remove remove group from sharepoint list like this
function RemoveMandatoryGroup() {
var context;
var factory;
var appContextSite;
var collListItem;
var itemId;
context = new SP.ClientContext(appweburl);
factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, hostweburl);
this.web = appContextSite.get_web();
var oList = this.web.get_lists().getByTitle('MandatoryGroups');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + RemoveGroupId.toString() + "</Value></Eq></Where></Query></View>");
collListItem = oList.getItems(camlQuery);
context.load(collListItem, 'Include(Title,Id)');
// this.oListItem.deleteObject();
context.executeQueryAsync(
Function.createDelegate(this, onQuerySucceeded),
Function.createDelegate(this, onQueryFailed)
);
function onQuerySucceeded() {
var oListItem;
var listitemenumerator = collListItem.getEnumerator();
while (listitemenumerator.moveNext()) {
var itemtoDelete = listitemenumerator.get_current();
////listItemInfo += '<li>ID:' + olistitem.get_id().toString() + ' GroupID: ' + olistitem.get_item('Title') + '</li>';
//MandatoryGroups.push(olistitem.get_item('Title'));
itemId = itemtoDelete.get_id();
}
oListItem = oList.getItemById(itemId);
oListItem.deleteObject();
context.executeQueryAsync(Function.createDelegate(this, onQueryDeleteSucceeded), Function.createDelegate(this, onQueryDeleteFailed));
//alert('Item created: ' + oListItem.get_id());
function onQueryDeleteSucceeded() {
//alert('Request failed. ' + args.get_message() +
// '\n' + args.get_stackTrace());
getMyGroups();
$.getScript(scriptbase + 'SP.RequestExecutor.js', GetMandatoryGroups);
}
function onQueryDeleteFailed() {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
}
No, there isn't. This is by design. Yammer likes to entice with the carrot, not by the stick. What we've done is create communications to ask people to join a specific group.
The api does allow the ability for the currently logged to be joined to a specific group. E.g. Put a link on a SharePoint site that says "Join the Yammer group", and have the action join that user to the group. You can see the details for how to do that here:
https://developer.yammer.com/restapi/#rest-groups
ya, in costume app yo can autojoin that user when he logs in..Same thing i ma doing.

import private google fusion table to google docs spreadsheet

I want to build a chart to google fusion table. I know there is an option to do it with fusion table but I need to do that using google spreadsheet.
How do I import a private fusion table to a spreadsheet?
function getdata(authToken) {
query = encodeURIComponent("SELECT * FROM tableid");
var URL = "http://www.google.com/fusiontables/api/query?sql=" + query;
var response = UrlFetchApp.fetch(URL, {
method: "get",
headers: {
"Authorization": "GoogleLogin auth=" + authToken,
}
});
return response.getContentText();
}
The code above gives me the table headers only.
Don't set each cell individually as in the example below unless you need to process each bit of data. Using this is about 10x faster:
var rows = o.length;
var columns = o[0].length;
cell.offset(<startrow>, <startcolumn>, rows, columns).setValues(o);
After a deep research, finally i figured it out after a deep search and reading here.
This is how it looks for the code google docs spreadsheet app script:
function onOpen()
{
var tableID = '00000' // Add the table ID of the fusion table here
var email = UserProperties.getProperty('email');
var password = UserProperties.getProperty('password');
if (email === null || password === null) {
email = Browser.inputBox('Enter email');
password = Browser.inputBox('Enter password');
UserProperties.setProperty('email',email);
UserProperties.setProperty('password', password);
} else {
email = UserProperties.getProperty('email');
password = UserProperties.getProperty('password');
}
var authToken = getGAauthenticationToken(email,password);
query = encodeURIComponent("SELECT * FROM tableID");
var URL = "http://www.google.com/fusiontables/api/query?sql=" + query;
var response = UrlFetchApp.fetch(URL, {
method: "get",
headers: {
"Authorization": "GoogleLogin auth=" + authToken,
}
});
var tableData = response.getContentText();
var o = Utilities.parseCsv(response.getContentText());
var doc = SpreadsheetApp.getActiveSpreadsheet();
var cell = doc.getRange('a1');
var index = 0;
for (var i in o) {
var row = o[i];
var col = 0;
for (var j in row) {
cell.offset(index, col).setValue(row[j]);
col++;
}
index++;
}
}
function getGAauthenticationToken(email, password) {
password = encodeURIComponent(password);
var response = UrlFetchApp.fetch("https://www.google.com/accounts/ClientLogin", {
method: "post",
payload: "accountType=GOOGLE&Email=" + email + "&Passwd=" + password + "&service=fusiontables&Source=testing"
});
var responseStr = response.getContentText();
responseStr = responseStr.slice(responseStr.search("Auth=") + 5, responseStr.length);
responseStr = responseStr.replace(/\n/g, "");
return responseStr;
}
After that you can do whatever you want in the spreadsheet.
BTW, I still think there is a simple way to import a private table into a spreadsheet automaticly.

Use currentLocation along with a business search in bing map API

I was currently at this site which shows how to implement business search using the bing map api. But what I am trying to implement is, first the map should get your current location and search for type of business nearby, let's say Restaurant or Check Cashing place.
My current page has the current location working but now how I implement the FindNearBy function with my page?
P.s. I want the search to already take place for the user without having to enter a search text, so the map should load up with current location and right next to it should list all or maybe the closest 5 restaurant nearby.
Not with Bing Maps...you need the Bing Phonebook API to do this.
I can get you part of the way there. The below example combines the use of both the Bing Maps API and the Bing Phonebook API) I just submitted a similar question about how to find the type of business, however...I'm not sure there's a wayto do this :/ (Below example searches for all Starbucks in the area ...of course, some HTML integration is required.
var _map;
var _appId;
$(document).ready(function () {
if (Modernizr.geolocation) {
$(".geofallback").hide();
}
else {
$(".geofallback").show();
}
$.post("Home/GetBingMapsKey", { "func": "GetBingMapsKey" }, function (data) {
// Create a Bing map
_map = new Microsoft.Maps.Map(document.getElementById("map"),
{ credentials: data }); //, mapTypeId: Microsoft.Maps.MapTypeId.ordnanceSurvey
});
// Get the current position from the browser
if (!navigator.geolocation) {
$("#results").html("This browser doesn't support geolocation, please enter an address");
}
else {
$.post("Home/GetBingKey", { "func": "GetBingKey" }, function (data) {
_appId = data;
});
navigator.geolocation.getCurrentPosition(onPositionReady, onError);
navigator.geolocation.getCurrentPosition(Search, onError);
}
});
function onPositionReady(position) {
// Apply the position to the map
var location = new Microsoft.Maps.Location(position.coords.latitude,
position.coords.longitude);
_map.setView({ zoom: 18, center: location });
// Add a pushpin to the map representing the current location
var pin = new Microsoft.Maps.Pushpin(location);
_map.entities.push(pin);
}
function onError(err) {
switch (err.code) {
case 0:
alert("Unknown error :(");
break;
case 1:
alert("Location services are unavailable per your request.");
break;
case 2:
alert("Location data is unavailable.");
break;
case 3:
alert("The location request has timed out. Please contact support if you continue to experience issues.");
break;
}
}
function Search(position) {
// note a bunch of this code uses the example code from
// Microsoft for the Phonebook API
var requestStr = "http://api.bing.net/json.aspx?"
// Common request fields (required)
+ "AppId=" + _appId
+ "&Query=starbucks"
+ "&Sources=Phonebook"
// Common request fields (optional)
+ "&Version=2.2"
+ "&Market=en-us"
+ "&UILanguage=en"
+ "&Latitude=" + position.coords.latitude
+ "&Longitude=" + position.coords.longitude
+ "&Radius=100.0"
+ "&Options=EnableHighlighting"
// Phonebook-specific request fields (optional)
// Phonebook.Count max val is 25
+ "&Phonebook.Count=25"
+ "&Phonebook.Offset=0"
// YP = Commercial Entity, WP = Residential
+ "&Phonebook.FileType=YP"
+ "&Phonebook.SortBy=Distance"
// JSON-specific request fields (optional)
+ "&JsonType=callback"
+ "&JsonCallback=?";
$.getJSON(requestStr, function (data) {
SearchCompleted(data);
});
}
function FormatBingQuery(appId, latitude ) {
}
function SearchCompleted(response) {
var errors = response.SearchResponse.Errors;
if (errors != null) {
// There are errors in the response. Display error details.
DisplayErrors(errors);
}
else {
// There were no errors in the response. Display the
// Phonebook results.
DisplayResults(response);
}
}
function DisplayResults(response) {
var output = document.getElementById("output");
var resultsHeader = document.createElement("h4");
var resultsList = document.createElement("ul");
output.appendChild(resultsHeader);
output.appendChild(resultsList);
var results = response.SearchResponse.Phonebook.Results;
// Display the results header.
resultsHeader.innerHTML = "Bing API Version "
+ response.SearchResponse.Version
+ "<br />Phonebook results for "
+ response.SearchResponse.Query.SearchTerms
+ "<br />Displaying "
+ (response.SearchResponse.Phonebook.Offset + 1)
+ " to "
+ (response.SearchResponse.Phonebook.Offset + results.length)
+ " of "
+ response.SearchResponse.Phonebook.Total
+ " results<br />";
// Display the Phonebook results.
var resultsListItem = null;
var resultStr = "";
for (var i = 0; i < results.length; ++i) {
resultsListItem = document.createElement("li");
resultsList.appendChild(resultsListItem);
//loc is specific to my C# object
var loc = new Array();
loc[0] = results[i].Longitude;
loc[1] = results[i].Latitude;
var address = {
AddressLine1: results[i].Address,
City: results[i].City,
State: results[i].StateOrProvince,
PostalCode: results[i].PostalCode,
Latitude: results[i].Latitude,
Longitude: results[i].Longitude,
Country: results[i].CountryOrRegion,
ID: results[i].UniqueId
};
//this part is specific to my project to return the
//address results so I can store them (since my
//implementation is a demonstration of how to
//use the MongoDB geoNear() functionality
$.ajax({
url: "/Home/AddAddressToCollection",
type: 'post',
data: JSON.stringify(address),
contentType: 'application/json',
dataType: 'json'
});
resultStr = results[i].Business
+ "<br />"
+ results[i].Address
+ "<br />"
+ results[i].City
+ ", "
+ results[i].StateOrProvince
+ "<br />"
+ results[i].PhoneNumber
+ "<br />Average Rating: "
+ results[i].UserRating
+ "<br /><br />";
// Replace highlighting characters with strong tags.
resultsListItem.innerHTML = ReplaceHighlightingCharacters(
resultStr,
"<strong>",
"</strong>");
}
}
function ReplaceHighlightingCharacters(text, beginStr, endStr) {
// Replace all occurrences of U+E000 (begin highlighting) with
// beginStr. Replace all occurrences of U+E001 (end highlighting)
// with endStr.
var regexBegin = new RegExp("\uE000", "g");
var regexEnd = new RegExp("\uE001", "g");
return text.replace(regexBegin, beginStr).replace(regexEnd, endStr);
}
function DisplayErrors(errors) {
var output = document.getElementById("output");
var errorsHeader = document.createElement("h4");
var errorsList = document.createElement("ul");
output.appendChild(errorsHeader);
output.appendChild(errorsList);
// Iterate over the list of errors and display error details.
errorsHeader.innerHTML = "Errors:";
var errorsListItem = null;
for (var i = 0; i < errors.length; ++i) {
errorsListItem = document.createElement("li");
errorsList.appendChild(errorsListItem);
errorsListItem.innerHTML = "";
for (var errorDetail in errors[i]) {
errorsListItem.innerHTML += errorDetail
+ ": "
+ errors[i][errorDetail]
+ "<br />";
}
errorsListItem.innerHTML += "<br />";
}
}
// Bonus: In case you want to provide directions
// for how to get to a selected entity
// _map.getCredentials(function (credentials) {
// $.getJSON('http://dev.virtualearth.net/REST/V1/Routes/driving?' + 'wp.0=' + lat1 + ',' + lon1 + '&wp.1=' + lat2 + ',' + lon2 + '&distanceUnit=mi&optmz=distance&key=' + credentials + '&jsonp=?&s=1',
// function (result) {
// if (result.resourceSets[0].estimatedTotal > 0) {
// var distance = result.resourceSets[0].resources[0].travelDistance;
// }
// else {
// $("#results").html("Oops! It appears one or more of the addresses you entered are incorrect. :( ");
// }
// });
// });
//Tie into a function that shows an input field
//for use as a fallback in case cannot use HTML5 geoLocation
//$(document).ready(function () {
// $("#btnFindLocation").click(function () {
// //check user has entered something first
// if ($("#txtAddress").val().length > 0) {
// //send location query to bing maps REST api
// _map.getCredentials(function (credentials) {
// $.getJSON('http://dev.virtualearth.net/REST/v1/Locations?query=' + $("#txtAddress").val() + '&key=' + credentials + '&jsonp=?&s=1',
// function (result) {
// if (result.resourceSets[0].estimatedTotal > 0) {
// var loc = result.resourceSets[0].resources[0].point.coordinates;
// $("#lat").val(loc[0]);
// $("#lon").val(loc[1]);
// var location = new Microsoft.Maps.Location(loc[0],
// loc[1]);
// _map.setView({ zoom: 18, center: location });
// // Add a pushpin to the map representing the current location
// var pin = new Microsoft.Maps.Pushpin(location);
// _map.entities.push(pin);
// }
// else {
// $("#results").html("sorry that address cannot be found");
// }
// });
// });
// }
// else {
// $("#results").html("please enter an address");
// }
// });
//});