Add a user to a group programatically - rest

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.

Related

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

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

after effects - selecting render queue items via script

i'm looking for a way to select items in the render queue via script.
i'm creating a listBox that contains all the RQ items ( i need to list them in a simpler way then the RQ window, and i'm keeping the index number of each item), and i want to select from that list items and select them in the RQ.
ideas?
thanks
Dror
try{
function createUserInterface (thisObj,userInterfaceString,scriptName){
var pal = (thisObj instanceof Panel) ? thisObj : new Window("palette", scriptName,
undefined,{resizeable: true});
if (pal == null) return pal;
var UI=pal.add(userInterfaceString);
pal.layout.layout(true);
pal.layout.resize();
pal.onResizing = pal.onResize = function () {
this.layout.resize();
}
if ((pal != null) && (pal instanceof Window)) {
pal.show();
}
return UI;
};
{var res ="group {orientation:'column',\
alignment:['fill','fill'],\
alignChildren:['fill','top'],\
folderPathListbox:ListBox{\
alignment:['fill','fill'],\
properties:{\
multiline:true,\
multiselect:true,\
numberOfColumns:6,\
showHeaders:true,\
columnTitles: ['#','OM','Date','Time', 'Comp Name', 'Render Path']}\
},\
buttonGroup:Group{orientation:'row',\
alignment:['fill','bottom']\
alignChildren:['fill','bottom'],\
buttonPanel: Panel{\
text:'Actions',\
orientation: 'row',\
alignment:['fill','bottom']\
refButton: Button{text:'Refresh'}\
dupButton: Button{text:'Duplicate'}\
selButton: Button{text:'Select in RQ'}\
expButton: Button{text:'Export'}\
}\
searchPanel: Panel{\
text:'Search',\
orientation: 'row',\
searchBox: EditText{text:'search by fileName'},\
searchButton: Button{text:'Search'}, \
}\
}\
}";
}
function listRQ (rqList){
try{
var folderPathListbox = rqList;
var proj = app.project;
var totalRenderQ = proj.renderQueue.numItems;
for(var i= 1; i<=totalRenderQ; i++){
var totalOM= proj.renderQueue.item(i).numOutputModules;
for (var om= 1; om<=totalOM; om++){
var dateList, timeList, curItem;
if (proj.renderQueue.item(i).startTime != null){
var min = proj.renderQueue.item(i).startTime.getMinutes() <10 ? "0"+ proj.renderQueue.item(i).startTime.getMinutes() : proj.renderQueue.item(i).startTime.getMinutes();
var year = proj.renderQueue.item(i).startTime.getFullYear().toString().substr (-2,2);
timeList = (proj.renderQueue.item(i).startTime.getHours()-1)+":" + min;
dateList =proj.renderQueue.item(i).startTime.getDate()+"/"+(proj.renderQueue.item(i).startTime.getMonth()+1)+"/"+year ;
}else{
dateList = "not ";
timeList = "rendered";
}
curItem = folderPathListbox.add ('item', i ); // Column 1
curItem.subItems[0].text = om; // Column 2
curItem.subItems[1].text = dateList.toString(); // Column 3
curItem.subItems[2].text = timeList.toString(); // Column 4
curItem.subItems[3].text = proj.renderQueue.item(i).comp.name; // Column 5
curItem.subItems[4].text = proj.renderQueue.item(i).outputModule(om).file.toString().replace(new RegExp(",","g"), "\r").replace(new RegExp("%20","g"), " ").replace(new RegExp("%5B","g"), "[").replace(new RegExp("%5D","g"), "]"); // Column 6
}
}
}catch(err){alert(err)}
return folderPathListbox;
}
var UI = createUserInterface(this,res,"Better RQ");
var myList = UI.folderPathListbox;
var lsRq = listRQ(myList);
//~ alert(lsRq.toString());
{ // buttons action
UI.buttonGroup.buttonPanel.refButton.onClick = function () {
lsRq.removeAll();
listRQ(myList);
writeLn("all done");
}
UI.buttonGroup.buttonPanel.dupButton.onClick = function () {
var lstSlct = new Array ;
lstSlct = myList.selection;
if ( lstSlct != null){
var totalDup = lstSlct.length;
for (var i= 0; i<totalDup; i++){
var lsId = lstSlct[i].toString();
var dup = parseInt(lsId);
app.project.renderQueue.item(dup).duplicate();
writeLn("duplicated #"+dup);
}
}else{
alert ("select Something");
}
}
UI.buttonGroup.buttonPanel.selButton.onClick = function () {
app.project.renderQueue.showWindow(true) ; //shows the RQ
alert ("selButton");
}
UI.buttonGroup.buttonPanel.expButton.onClick = function () {
// var compName = myList.
alert ("expButton");
}
}
}
catch(err){
alert ("Error at line # " + err.line.toString() + "\r" + err.toString());
}

jquery.jeditable.ajaxupload.js how to send file?

maybe somebody can to explain me why I can't send file, maybe needed additional script or something els?
/*
* Ajaxupload for Jeditable
*
* Copyright (c) 2008-2009 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Depends on Ajax fileupload jQuery plugin by PHPLetter guys:
* http://www.phpletter.com/Our-Projects/AjaxFileUpload/
*
* Project home:
* http://www.appelsiini.net/projects/jeditable
*
* Revision: $Id$
*
*/
$.editable.addInputType('ajaxupload', {
/* create input element */
element : function(settings) {
settings.onblur = 'ignore';
var input = $('<input type="file" id="upload" name="upload" />');
$(this).append(input);
return(input);
},
content : function(string, settings, original) {
/* do nothing */
},
plugin : function(settings, original) {
var form = this;
form.attr("enctype", "multipart/form-data");
$("button:submit", form).bind('click', function() {
//$(".message").show();
// Modification to include original id and submitdata in target's querystring
var queryString;
if ($.isFunction(settings.submitdata)) {
queryString = jQuery.param(settings.submitdata.apply(self, [self.revert, settings]));
} else {
queryString = jQuery.param(settings.submitdata);
}
if (settings.target.indexOf('?') < 0) {
queryString = '?' + settings.id + '=' + $(original).attr('id') + '&' + queryString;
} else {
queryString = '&' + settings.id + '=' + $(original).attr('id') + '&' + queryString;
}
settings.target += queryString;
// End modification
$.ajaxFileUpload({
url: settings.target,
secureuri:false,
// Add the following line
data : settings.submitdata,
fileElementId: 'upload',
dataType: 'html',
success: function (data, status) {
$(original).html(data);
original.editing = false;
},
error: function (data, status, e) {
alert(e);
}
});
return(false);
});
}
});
$(\".ajaxupload\").editable('/?action=upload_profile_photo', {
indicator : '<i class=\"fa fa-spinner fa-pulse\"></i>',
type : 'ajaxupload',
submit : 'Upload',
cancel : 'Cancel',
tooltip : \"Click to upload...\"
});
<p class=\"ajaxupload\" id=\"profile_photo\"><img class=\"img-thumbnail img-responsive\" src=\"http://www.in-elite.com/?action=no_image_text\" alt=\"\"></p>
how result its passed only
print_r($._GET)Array ( [action] => upload_profile_photo [id] =>
profile_photo ) print_r($._POST)Array ( [value] => 20150501_153530.jpg
[id] => profile_photo )
And question so, How to send file?
Ux I found the problem ;-)
I'm forgot to add one js file called jquery.ajaxfileupload.js
<script type=\"text/javascript\" src=\"/includes/JS/jquery.ajaxfileupload.js\" charset=\"utf-8\"></script>
And content of this jquery.ajaxfileupload.js file is
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
if(window.ActiveXObject) {
var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
if(typeof uri== 'boolean'){
io.src = 'javascript:false';
}
else if(typeof uri== 'string'){
io.src = uri;
}
}
else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px';
document.body.appendChild(io);
return io
},
createUploadForm: function(id, fileElementId)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = $('#' + fileElementId);
var newElement = $(oldElement).clone();
$(oldElement).attr('id', fileId);
$(oldElement).before(newElement);
$(oldElement).appendTo(form);
//set attributes
$(form).css('position', 'absolute');
$(form).css('top', '-1200px');
$(form).css('left', '-1200px');
$(form).appendTo('body');
return form;
},
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function()
{ try
{
$(io).remove();
$(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
// var io = $('#' + frameId);
var form = $('#' + formId);
$(form).attr('action', s.url);
$(form).attr('method', 'POST');
$(form).attr('target', frameId);
if(form.encoding)
{
form.encoding = 'multipart/form-data';
}
else
{
form.enctype = 'multipart/form-data';
}
$(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload', uploadCallback);
}
else{
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
}
return {abort: function () {}};
},
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data);
//jQuery("<div>").html(data).evalScripts();
//alert($('param', data).each(function(){alert($(this).attr('value'));}));
return data;
}
})
Now everything ok and file are uploaded successfully.... Just needed to modified php script for which type of the data you need to upload

Google maps api v2 get polygon coordinate

I am a bit of a beginner at google maps api. I managed to let the user to draw a polygon on the map and then I want to get the coordinates on the drew polygon.
I have used the following segment of code but it gave me the following error Uncaught TypeError: Object [object Object] has no method 'getPath'
this is the code that I used
function startShape() {
initialize();
document.getElementById('lat').disabled = true;
document.getElementById('lng').disabled = true;
var polygon = new GPolygon([],"ff0000", 2, 0.7,"ff0000",0.2);
startDrawing(polygon, "Shape " + (++shapeCounter_), function() {
var cell = this;
var area = polygon.getArea();
cell.innerHTML = (Math.round(area / 10000) / 100) + "km<sup>2</sup>";
});
showcoor(polygon);
}
function startDrawing(poly, name, onUpdate) {
map.addOverlay(poly);
poly.enableDrawing(options);
poly.enableEditing({onEvent: "mouseover"});
poly.disableEditing({onEvent: "mouseout"});
GEvent.addListener(poly, "endline", function() {
//var cells = addFeatureEntry(name, color);
//GEvent.bind(poly, "lineupdated", cells.desc, onUpdate);
GEvent.addListener(poly, "click", function(latlng, index) {
if (typeof index == "number") {
poly.deleteVertex(index);
}
});
});
}
function showcoor (poly) {
GEvent.addListener(poly, "endline", function() {
GEvent.addListener(poly, "click", function() {
var str;
var vertices = this.getPath();
for (var i =0; i < vertices.length; i++) {
var xy = vertices.getAt(i);
str += xy.lat() +"," + xy.lng()+"<br />";
}
alert (str);
});
});
}
There is no getPath method on the GPolygon object. See the GPolygon reference.
Instead, you'll need to use getVertexCount() and getVertex(i).
for (var i = 0, I = this.getVertexCount(); i < I; ++i) {
var xy = this.getVertex(i);
str += xy.lat() + ', ' + xy.lng() + '<br />';
}

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");
// }
// });
//});