how to add dynamic kml to google earth? - javascript

We are trying to add dynamic kml to google earth.But we are failing in one situation.
CODE:
var currentKmlObject = null;
function loadkmlGE(){
if (currentKmlObject != null) {
ge.getFeatures().removeChild(currentKmlObject);
currentKmlObject = null;
}
var url = 'test.kml';
google.earth.fetchKml(ge, url, finished);
}
function finished(kmlObject) {
if (kmlObject) {
currentKmlObject = kmlObject;
ge.getFeatures().appendChild(currentKmlObject);
} else {
setTimeout(function() {
alert('Bad or null KML.');
}, 0);
}
}
When we click on button we are calling loadkmlGE() function.We are able to get the kml first time on google earth.If we click second time then we are not getting kml on google earth.But test.kml file is updating new values.So, how we can remove the kml from google earth?
Help would be appreciated.

fetchKml I beleive uses the browser to fetch the file. It will generally cache the file unless told otherwise.
You could arrange for the server to tell the browser it cant cache the file - using HTTP headers. depends on your server how to set that up.
... or just arrange the url to change each time.
var url = 'test.kml?rnd='+Math.random();
or similar. The server will likly ignore the bogus param. But as the URL has changed the browser wont have a cached version.

Related

Trying to pass parameters to HTML page in C# webView2

I am attempting to navigate to an HTML file using parameters for location (lat and long)
This is a WPF application that has a built in browser which shows data from the google maps api.
I want to instantiate my map given the location parameters in C#
I read this thread:
How to pass information from a WPF app to an HTML page
but I still get file not found. The url works fine without the parameters
String sURL = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\html\\mapview.html";
Uri uri = new Uri(sURL+"?lat="+lat+"&lng="+lng+"");
webBrowser1.Source = uri;
Any ideas as to why im getting these errors?
Not allowed to load local resource
and
ERR_FILE_NOT_FOUND
As mm8 pointed out, because I'm not using a web server it is not possible to pass parameters to my local file.
Reading various threads I had found a solution of installing a local webserver to the project, but since I didn't want to have to configure the web server and add unnecessary load to my projects, I worked around the issue by dynamically changing the coordinates in the HTML file before loading it in
private void LoadMap()
{
// Before loading map, change the trojan horse coordinates to the latest ones by editing the html file
string[] lines = File.ReadAllLines(sURL);
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].Contains("var lat"))
{
lines[i] = "<script>var lat = " + lat + "; var lng = " + lng + ";</script>";
break;
}
}
File.WriteAllLines(sURL, lines);
// We can now load in the desired coordinates
Uri uri = new Uri(sURL);
webBrowser1.Source = uri;
}
Note that this will require a new page load each time, but it is a good solution for changing things that need to be done on page load.
Another thing I tested was calling the script asynchronously. This also worked pretty well
// we need to wait for map initialization (page load) before running our calcRoute script
private async void NavMapLoading() //starts loading content asynchronously
{
await webBrowser1.EnsureCoreWebView2Async(null);
webBrowser1.CoreWebView2.DOMContentLoaded += OnWebViewDOMContentLoaded;
Uri uri = new Uri(AppDomain.CurrentDomain.BaseDirectory + "html\\map_route.html");
webBrowser1.Source = uri;
}
private async void OnWebViewDOMContentLoaded(object sender, CoreWebView2DOMContentLoadedEventArgs arg)
{
webBrowser1.CoreWebView2.DOMContentLoaded -= OnWebViewDOMContentLoaded;
webBrowser1.Focus();
// now we can load destination
await webBrowser1.ExecuteScriptAsync("calcRoute("+origin+","+dest+");");
}

Thumbnail image loading issue from google drive using javascript

please refer above link for reference.
I am using drive rest API for interacting with files from google drive.
my problem is when tries to load thumbnail images (which is got from google drive meta data) i got following error in response.
(Reload the page to get source for: https://lh6.googleusercontent.com/PIkXnvV5LN71K8UdvltrFIS7WpKOiXHnJCIvPRsq0ma_XU_gzEFKrfnc6hYFIojM_4_kNA
=w100-h100)
however it works fine sometimes and loads the image perfectly.
Also i checked the link in new tab which is also works perfectly.
here is my code for java script
--link used for meta data
var googleLink = 'https://www.googleapis.com/drive/v2/files?q="'+attachmentId+'" in parents and mimeType != "application/vnd.google-apps.folder"&access_token='+that.getAccessToken();
--code for render image links in browser
for(var i = 0; i < files.items.length; i++){
var div = $('<div class="row">');
var link = $('<a href="'+files.items[i]['downloadUrl']+"&access_token="+upload.getAccessToken()+'">');
if(files.items[i]['thumbnailLink'] != undefined){
var thumbnailUrl = files.items[i]['thumbnailLink'].split("=");
var linkUrl = thumbnailUrl[0]+"=w100-h100";
var image = $('<img src="'+files.items[i]['iconLink']+'" data-src="'+linkUrl+'" style="padding:2px; float:left; height:auto; width:auto;" onload="loadPreviewImage(this)">');
link.append(image);
}else{
div.append($('<img src="'+files.items[i]['iconLink']+'" style="padding:2px; float:left;">'));
}
link.append(files.items[i]['originalFilename']);
div.append(link);
td.append(div);
}
//function for loading thumbnail image
function loadPreviewImage(element){
var img = $(element);
img.src = img.dataset.src;
}
You error 403 may occur if you disable the Google Drive setting called Allow users to install Google Drive apps. This might be a good thing to check if you are certain that Google Drive is already enabled.
It is also suggested to clear your cache first. If that doesn't work, try running a malware scan using a malware/virus scanner.
You may check these related threads:
Getting a 403 - Forbidden for Google Service Account
403 Forbidden error when accessing Google Drive API downloadURL
The issue I was having was not seeing the Google Doc icon and instead seeing a broken image. But I was able to resolve it by realizing I was having the same request issue from a third-party so I went into the internet settings of the computer and resetting them to the default.
Start > Control Panel > Internet Options > Tabs (Security/Privacy/Advanced) = Default

KDE plasmoid ind autorefresh

I'm trying to write KDE4 plasmoid in JavaScript, but have not success.
So, I need to get some data via HTTP and display it in Label. That's working well, but I need regular refresh (once in 10 seconds), it's not working.
My code:
inLabel = new Label();
var timer= new QTimer();
var job=0;
var fileContent="";
function onData(job, data){
if(data.length > 0){
var content = new String(data.valueOf());
fileContent += content;
}
}
function onFinished(job) {
inLabel.text=fileContent;
}
plasmoid.sizeChanged=function()
{
plasmoid.update();
}
timer.timeout.connect(getData);
timer.singleShot=false;
getData();
timer.start(10000);
function getData()
{
fileContent="";
job = plasmoid.getUrl("http://192.168.0.10/script.cgi");
job.data.connect(onData);
job.finished.connect(onFinished);
plasmoid.update();
}
It gets script once and does not refresh it after 10 seconds. Where is my mistake?
It is working just fine in here at least (running a recent build from git master), getData() is being called as expected. Can you see any errors in the console?
EDIT: The problem was that getUrl() explicitly sets NoReload for KIO::get() which causes it load data from cache instead of forcing a reload from the server. Solution was to add a query parameter to the URL in order to make it force reload it.

Different external .js files with same variable names

I'm making a websites that displays noise measurement data from different locations. The data for each location is captured on a sound level meter device and it is then read with a windows-based application. The application then uploads data on a web server as a .js file with an array variable in it. This .js files are refreshed every 5 minutes.
I first created a javascript application that displays live data for a single measuring unit. But now I need to display data on a map for all the locations. The problem is that the windows application on each location makes a file with the same name and same variables only on another location. I'm having some trouble with reading the correct data.
This is what I did so far:
function removejscssfile(filename, filetype){
var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist from
var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
var allsuspects=document.getElementsByTagName(targetelement)
for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
}
}
function updateData(){
var numberOfNoiseSniffers = noiseSniffers.length-1;
var j = 0;
for (i=0;i<=numberOfNoiseSniffers;i++) {
file = '../'+ noiseSniffers[i] + "/" + "CurrentMeasurement.js";
$.include(file,function(){
laeq[j] = currentMeas[1][1];
lastUpdate[j] = currentMeas[0][1];
if (j==numberOfNoiseSniffers){
updateMarkers();
}
removejscssfile(file[0], "js");
j++;
});
}
t=setTimeout(function() { updateData() }, 300000);
}
$(function (){
map = new google.maps.Map(document.getElementById("gMap"), myOptions);
//noiseSniffers is an array where I have save all the folder names of different measurement locations
var numberOfNoiseSniffers = noiseSniffers.length-1;
var j = 0;
for (i=0;i<=numberOfNoiseSniffers;i++) {
var file = '../'+ noiseSniffers[i] + "/" + "CurrentMeasurement.js";
//I am using include plugin for jquery to include files because it has a callback for when a file is actually loaded
$.include(file,function(){
//a set of global arrays that keep the data from the loaded file and this data is then displayed in google maps markers
laeq[j] = currentMeas[1][1];
lastUpdate[j] = currentMeas[0][2];
latitude[j] = systemstats[12][5];
longitude[j] = systemstats[11][6];
//checking to see if I am in the process of including the last file
if (j==numberOfNoiseSniffers){
//a function that creates google maps markers
createMarkers();
}
//after that I remove the files that were just included and read
removejscssfile(file, "js");
j++;
});
}
setTimeout(function() { updateData() }, 300000);
});
I got the function for removing my .js file here: Dynamically removing an external JavaScript or CSS file.
And this is the jquery plugin for loading the .js file: Include File On Demand.
The initial load usually works (sometimes it happens that only one or no markers get loaded. But the update function mostly returns the same data for both locations.
So what I want to know is, how can I firstly make my code working and how to optimize it. I posted just the main parts of the javascript code, but I can provide all the code if it is needed. Thanks for any help.
I think you need some sort of JSONP-like solution.
Basically load data on the server side, then wrap it in a method call before returning it to client side. Your response should look something like this:
var location_data = [1,2,3,4]
updateLocation('location_id', location_data)
Now you define an updateLocation() function in your client side script. Now, every time you need new data, you create new 'script' tag with src pointing to your server side. When the response is loaded, your updateLocation() will be invoked with correct params.
I hope this is clear enough
You can maybe try some form of namespacing
i exactly dont understood your problem, but you may try this
//put your code inside an anonymous function and execute it immediately
(function(){
//your javascript codes
//create variable with same names here
//
})();

Google API Authentication

Using the Google Javascript API I am trying to authenticate myself (locally) to create a new event in my calendar. However, I get an error (see below) stating that my "next" parameter is bad or missing when I execute the log-in portion of the script. I am following the data api interactive samples for "Create a single event".
Update 1: From the address bar I see "next" set the following way:
next=file:///C:/calext/sending_data.html
Does Google not like local files? Workaround?
Update 2: I tried running the file on my web host. The page ran (threw a few errors) but the event ended up on my calendar. So the bug lies somewhere with not liking local files. Thoughts?
Error Message:
The page you have requested cannot be
displayed. Another site was requesting
access to your Google Account, but
sent a malformed request. Please
contact the site that you were trying
to use when you received this message
to inform them of the error. A
detailed error message follows:
The "next" parameter was bad or
missing.
My page's code:
<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
</head>
<body>
<img src="128.png">
<script type="text/javascript">
var myService;
var feedUrl = "https://www.google.com/calendar/feeds/default/private/full";
google.load("gdata", "1");
google.setOnLoadCallback(getMyFeed); // starts process
// Create a single event example
function doExample()
{
var calendarService = myService;
// The default "private/full" feed is used to insert event to the
// primary calendar of the authenticated user
var feedUri = 'http://www.google.com/calendar/feeds/default/private/full';
// Create an instance of CalendarEventEntry representing the new event
var entry = new google.gdata.calendar.CalendarEventEntry();
// Set the title of the event
entry.setTitle(google.gdata.Text.create('JS-Client: insert event'));
// Create a When object that will be attached to the event
var when = new google.gdata.When();
// Set the start and end time of the When object
var startTime = google.gdata.DateTime.fromIso8601("2010-10-24T09:00:00.000-05:00");
var endTime = google.gdata.DateTime.fromIso8601("2010-10-24T10:00:00.000-05:00");
when.setStartTime(startTime);
when.setEndTime(endTime);
// Add the When object to the event
entry.addTime(when);
// Submit the request using the calendar service object
calendarService.insertEntry(feedUri, entry, handleMyFeed, handleError, google.gdata.calendar.CalendarEventEntry);
}
function handleMyFeed(myResultsFeedRoot)
{
alert("This feed's title is: " + myResultsFeedRoot.feed.getTitle().getText());
}
function handleError(e)
{
alert("There was an error!");
alert(e.cause ? e.cause.statusText : e.message);
}
function getMyFeed()
{
// Set up my service
myService = new google.gdata.calendar.CalendarService('GoogleInc-jsguide-1.0');
// Log me in
var scope = "https://www.google.com/calendar/feeds/";
var token = google.accounts.user.login(scope);
// Create a single event example
doExample();
// Get my feed
myService.getEventsFeed(feedUrl, handleMyFeed, handleError);
}
</script>
</body>
</html>
I assume your opening a local file which requires a local file. By default, file:// URIs cannot read other file:// URIs. Try adding this command line parameter, it is specifically made to help developers test:
chrome --allow-file-access-from-files

Categories