Use currentLocation along with a business search in bing map API - bing-maps

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

Related

LootLocker - How to show local rank

In my game, I am able to show the GlobalRank, however, I would also like to show the position of a player in Ranking according to the global results.
So in the bottom line, there should be the local (on this device) results.
Basically, on the left bottom corner, I want to get the RANK from the LootLocker, but I am struggling to get the rank...
IEnumerator ShowScores()
{
yield return new WaitForSeconds(2);
LootLockerSDKManager.GetScoreList(ID, maxScores, (response) =>
{
if (response.success)
{
LootLockerLeaderboardMember[] scores = response.items;
for (int i = 0; i < scores.Length; i++)
{
playerNames[i].text = (scores[i].member_id +"");
playerScores[i].text = (scores[i].score +"");
playerRank[i].text = (scores[i].rank + "");
//Rank of the localPlayer
Rank.text = (scores["here_Should_Be_This_Player_ID"].rank + "");
LootLockerSDKManager.GetPlayerName
// Entries[i].text = (scores[i].rank + ". " + scores[i].score + ". " + scores[i].member_id);
}
if (scores.Length < maxScores)
{
for (int i = scores.Length; i < maxScores; i++)
{
// Entries[i].text = (i + 1).ToString() + ". none";
}
}
}
else
{
}
});
}
Fixed it with the LootLocker support team
Step 1 - load LootLocker and get the resonse
Step 2 - load the rank and get the resonse2
Step 3 - use the "Response2.rank from the LootLocker
Rank.text = (response2.rank + "");
string playerIdentifier = "PlayerNameRecordOnThisDevice";
LootLockerSDKManager.StartSession(playerIdentifier, (response) =>
{
if (response.success)
{
Debug.Log("session with LootLocker started");
}
else
{
Debug.Log("failed to start sessions" + response.Error);
}
LootLockerSDKManager.GetMemberRank(ID, playerIdentifier, (response2) =>
{
if (response2.statusCode == 200)
{
Debug.Log("GetMemberRank Successful");
}
else
{
Debug.Log("GetMemberRank failed: " + response2.Error);
}
Rank.text = (response2.rank + "");
});
}); ```

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

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.

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 />';
}

How to handle a drag-event within Google Earth plugin?

My javascript is very weak.
Is it possible to modify the same code below to do the following:
Make the objects loaded draggable
When the object is dropped, an ajax request to something like:
http://.../moveTo?lat=new_lat&long=new_long&id=some_way_to_uniquely_id_the_object
Any advice to offer?
Sample Code:
var ge;
// store the object loaded for the given file... initially none of the objects
// are loaded, so initialize these to null
var currentKmlObjects = {
'red': null,
'yellow': null,
'green': null
};
google.load("earth", "1");
function init() {
// Create checkboxes
var content = document.getElementById('content');
var inputHTML = 'Placemarks:<br/>';
inputHTML += '<input type="checkbox" id="kml-red-check" onclick="toggleKml(\'red\');"/>' +
'<label for="kml-red-check">Red</label>' +
'<input type="checkbox" id="kml-yellow-check" onclick="toggleKml(\'yellow\');"/>' +
'<label for="kml-yellow-check">Yellow</label>' +
'<input type="checkbox" id="kml-green-check" onclick="toggleKml(\'green\');"/>' +
'<label for="kml-green-check">Green</label>';
content.innerHTML = inputHTML;
google.earth.createInstance('content', initCB, failureCB);
}
function initCB(instance) {
ge = instance;
ge.getWindow().setVisibility(true);
// add a navigation control
ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
// add some layers
ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);
// fly to Santa Cruz
var la = ge.createLookAt('');
la.set(37, -122,
0, // altitude
ge.ALTITUDE_RELATIVE_TO_GROUND,
0, // heading
0, // straight-down tilt
5000 // range (inverse of zoom)
);
ge.getView().setAbstractView(la);
// if the page loaded with checkboxes checked, load the appropriate
// KML files
if (document.getElementById('kml-red-check').checked)
loadKml('red');
if (document.getElementById('kml-yellow-check').checked)
loadKml('yellow');
if (document.getElementById('kml-green-check').checked)
loadKml('green');
document.getElementById('installed-plugin-version').innerHTML =
ge.getPluginVersion().toString();
}
function failureCB(errorCode) {
}
function toggleKml(file) {
// remove the old KML object if it exists
if (currentKmlObjects[file]) {
ge.getFeatures().removeChild(currentKmlObjects[file]);
currentKmlObject = null;
}
// if the checkbox is checked, fetch the KML and show it on Earth
var kmlCheckbox = document.getElementById('kml-' + file + '-check');
if (kmlCheckbox.checked)
loadKml(file);
}
function loadKml(file) {
var kmlUrl = 'http://earth-api-samples.googlecode.com/svn/trunk/' +
'examples/static/' + file + '.kml';
// fetch the KML
google.earth.fetchKml(ge, kmlUrl, function(kmlObject) {
// NOTE: we still have access to the 'file' variable (via JS closures)
if (kmlObject) {
// show it on Earth
currentKmlObjects[file] = kmlObject;
ge.getFeatures().appendChild(kmlObject);
} else {
// bad KML
currentKmlObjects[file] = null;
alert('Bad KML');
// uncheck the box
document.getElementById('kml-' + file + '-check').checked = '';
}
});
}
google.setOnLoadCallback(init);
For bonus points, can I get the kml to be reloaded afterwards?
To make the objects draggable you need to set up some event listeners and handle the movement in the callback function. I presume the objects you wish to drag are place-marks (KmlPlacemark) if so you need something like this...(NB: This is untested and written here so there could be some typos.)
var dragging = false; // the object being dragged
var url = "http://.../moveTo?"; // path to your cgi script
function init() {
// Rest of your method body...
google.earth.addEventListener(ge.getGlobe(), "mousedown", function(e)
{
// if it is a place mark
if(e.getTarget().getType() == 'KmlPlacemark')
{
// set it as the dragging target
dragging = e.getTarget();
}
});
google.earth.addEventListener(ge.getGlobe(), "mouseup", function(e)
{
// drop on mouse up (if we have a target)
if(dragging) {
// build the query string
// ...you could use getName or getSnippet rather than getId
var query = "lat=" + dragging.getGeometry().getLatitude() +
"&long=" + dragging.getGeometry().getLongitude() +
"&id=" + dragging.getId();
// send the query to the url
httpPost(url, query);
// clear the dragging target
dragging = false;
}
});
google.earth.addEventListener(ge.getGlobe(), "mousemove", function(e)
{
// when the mouse moves (if we have a dragging target)
if(dragging) {
// stop any balloon opening
e.preventDefault();
// drag the object
// i.e. set the placemark location to cursor the location
dragging.getGeometry().setLatLng(e.getLatitude(), e.getLongitude());
}
});
}
// send a HTTP POST request
// could use jQuery, etc....
function httpPost(url, query) {
var httpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.httpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.httpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.httpReq .open('POST', url, true);
self.httpReq .setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.httpReq .onreadystatechange = function() {
if (self.httpReq .readyState == 4) {
// do something...
alert(self.httpReq.responseText);
}
}
self.httpReq.send(query);
}