First, I want to thank you for the efforts in answering.
Second, I created a site that contains a plug-in of Google Earth, and I want to use a local KML file to show two coordinates.
HTML code:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"> </script>
<script type="text/javascript">
var ge;
google.load("earth", "1", {"other_params":"sensor=false"});
var fso, kmlString, fh;
function init() {
google.earth.createInstance('map3d', initCB, failureCB);
}
function initCB(instance) {
ge = instance;
ge.getWindow().setVisibility(true);
}
function failureCB(errorCode) {
}
google.setOnLoadCallback(init);
</script>
</head>
<body>
<div id="map3d" style="height: 300px; width: 400px;"></div>
</body>
</html>
KML code:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<name>Simple placemark</name>
<description>Attached to the ground. Intelligently places itself
at the height of the underlying terrain.</description>
<Point>
<coordinates>-122.0822035425683,37.42228990140251,0</coordinates>
</Point>
</Placemark>
</kml>
I searched Google for some answers, but nothing helped me to understand how to combine between the HTML and KML (Google Earth Plug-in). please help me.
Thank you very much,
Orian.
function initCallback(pluginInstance) {
ge = pluginInstance;
ge.getWindow().setVisibility(true);
// Earth is ready, we can add features to it
addKmlFromUrl('http://path/to/your.kml');
}
function addKmlFromUrl(kmlUrl) {
var link = ge.createLink('');
link.setHref(kmlUrl);
var networkLink = ge.createNetworkLink('');
networkLink.setLink(link);
networkLink.setFlyToView(true);
ge.getFeatures().appendChild(networkLink);
}
or
function addKmlFromUrl(kmlUrl) {
google.earth.fetchKml(ge, kmlUrl, kmlFinishedLoading);
}
function kmlFinishedLoading(kmlObject) {
if (kmlObject) {
ge.getFeatures().appendChild(kmlObject);
}
}
https://developers.google.com/earth/articles/earthapikml
"use a local KML file"
Using the file:// handler in the browser may satisfy your needs, using a web-browser to access local files has it's own gotchas though, from security restrictions onwards.
Related
Have been trying to follow the guide here to creating a pie chart and from there develop some dashboard features in Google Apps Script. I found out that when you implement the calling of a script function (in the example it would be the drawChart() function), that is considered "Active Content" as seen here.
I have seen other examples that don't use HTML, but those all seem to require the use of the UiApp class, which has been depreciated. So, is the only way to get a dashboard/graphing feature in Google Apps Script to have an HTTPS security certificate? It seems rather limiting if this is the case. I see a post or two mentioning a similar frustration getting only a white screen, and I believe that is due to the HTTPS limitation.
Originally I didn't post code because I felt the issue here was pretty clear. Here is the code I have. I also tried a simple HTML "Hello World" file that didn't have any functions/scripts, and that worked. Here is the script as it relates to my Google Sheet:
function OpenChart(){
var html = HtmlService.createHtmlOutputFromFile('DummyChart');
SpreadsheetApp.getUi().showModalDialog(html, "Statistics");
}
Here is the HTML file it calls:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
//Load charts package and visualization API
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(MakeChart);
//Here is the script I think could be causing a problem
function MakeChart()
{
var ss = SpreadsheetApp.getActive();
var s = ss.getSheets();
var s = sheets[1];
var UI = SpreadsheetApp.getUi();
var response = UI.prompt("Please enter the first cell in the category").getResponseText();
var ir = s.getRange(response);
var n= 0;
var stored = [];
stored.push(["Income Category", "Frequency"]);
while (ir.getValue()!= "") {
n = n +1;
ir = ir.offset(1, 0);
}
//Above we just set n, below we use n to fill our array
ir = ir.offset(-n,0)
for(i =0; i<n;i++) {
stored.push([ir.getValue(),ir.offset(n+2,0).getValue()]);
ir = ir.offset(1, 0);
}
var data = google.visualization.arrayToDataTable([
stored[]]);
/*I tried to also load data here directly as is seen on the pie chart example I used. This didn't have any affect*/
var options = { 'chartArea:backgroundColor': "Azure",
'is3D': true,
'title': 'Test Chart'};
//Now instantiate it
var chart = new google.visualization.PieChart(document.getElementById('chartDiv'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chartDiv" style="width: 450px; height: 300px;"> </div>
</body>
</html>
Any help appreciated.
Here is a quick example of how this can work. I stuck with the basic example and added the values from the pie chart example to the spreadsheet. The client side will need to call the server side to get the data. The is done with google.script.run. You would modify getData() to suite your needs.
code.gs:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu("charts").addItem("piechart", "openPieChart").addToUi()
}
function openPieChart(){
var html = HtmlService.createHtmlOutputFromFile("piechart");
var ui = SpreadsheetApp.getUi();
ui.showModalDialog(html, "piechart")
}
function getData(){
return SpreadsheetApp.getActiveSheet().getDataRange().getValues()
}
piechart.html
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(function(){google.script.run.withSuccessHandler(drawChart).getData()});
function drawChart(values) {
var data = google.visualization.arrayToDataTable(values);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
I'm trying to get the most basic XPCOM javascript object to be accessible to the javascript I load into my webpage. I'm using the example code from this tutorial:
https://developer.mozilla.org/en-US/docs/How_to_Build_an_XPCOM_Component_in_Javascript
Here is my set up:
install.rdf:
<?xml version="1.0"?>
<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:em="http://www.mozilla.org/2004/em-rdf#">
<Description about="urn:mozilla:install-manifest">
<em:id>helloworld#thellamatesting.com</em:id>
<em:name>Hello World</em:name>
<em:version>1.0</em:version>
<em:type>2</em:type>
<em:creator>The Llama</em:creator>
<em:description>Testing</em:description>
<em:targetApplication>
<Description>
<em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
<em:minVersion>2.0</em:minVersion>
<em:maxVersion>20.0</em:maxVersion>
</Description>
</em:targetApplication>
</Description>
</RDF>
chrome.manifest
content helloworld chrome/content/
content helloworld chrome/content/ contentaccessible=yes
overlay chrome://browser/content/browser.xul chrome://helloworld/content/browser.xul
component {4762b5c0-5b32-11e2-bcfd-0800200c9a66} components/HelloWorld.js
contract #thellamatesting.com/helloworld;1 {4762b5c0-5b32-11e2-bcfd-0800200c9a66}
locale helloworld en-US locale/en-US/
components/HelloWorld.js
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
function HelloWorld() {
// If you only need to access your component from Javascript, uncomment the following line:
this.wrappedJSObject = this;
}
HelloWorld.prototype = {
classDescription: "My Hello World Javascript XPCOM Component",
classID: Components.ID("{4762b5c0-5b32-11e2-bcfd-0800200c9a66}"),
//Also tried
//classID: Components.ID("4762b5c0-5b32-11e2-bcfd-0800200c9a66"),
contractID: "#thellamatesting.com/helloworld;1",
QueryInterface: XPCOMUtils.generateQI(),
// Also tried
//QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIHelloWorld]),
hello: function() {
return "Hello World!";
}
};
var components = [HelloWorld];
if ("generateNSGetFactory" in XPCOMUtils)
var NSGetFactory = XPCOMUtils.generateNSGetFactory(components); // Firefox 4.0 and higher
else
var NSGetModule = XPCOMUtils.generateNSGetModule(components); // Firefox 3.x
Testing HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="application/javascript">
function go() {
try {
var coms = Components;
alert(Components.classes);
var myComponent = Components.classes['#thellamatesting.com/helloworld;1'].getService().wrappedJSObject;
alert(myComponent.hello());
} catch (anError) {
dump("ERROR: " + anError);
}
};
</script>
</head>
<body>
<button onclick="javascript:go()">Click to go</button>
</body>
</html>
After all this, I end up with "Components.classes is undefined". Does anyone know what I'm doing wrong here?
Thanks so much!
In order to gain access to the Components object from a javascript context, you need to have extended capabilities, that is, run from a chrome:// URL. There used to be a way for a regular web page (served from http://) to request extended capabilities (called UniversalXPConnect) but it has been removed out of security concerns.
I think you should tell us a little more about what it is you're trying to achieve. If you're trying to export data from your addon into a webpage, the AddonSDK (see https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/) has a very good protocol for doing that called page-mod; it allows you to inject data into web pages.
Thanks to Jonathan's advice I was able to come up with a great solution to this problem. Here is the code I'm using:
main.js:
var data = require("self").data;
var pageMod = require("page-mod");
const {Cc,Ci} = require("chrome");
pageMod.PageMod({
include: "*",
contentScriptFile: data.url("copy-helper.js"),
onAttach: function(worker) {
worker.port.on("handleCopy", function(copyInfo) {
var gClipboardHelper = Cc["#mozilla.org/widget/clipboardhelper;1"].getService(Ci.nsIClipboardHelper);
gClipboardHelper.copyString(copyInfo.dataToCopy);
});
}
});
copy-helper.js:
window.addEventListener("copyEvent", function (event) {
self.port.emit('handleCopy', event.detail.copyInfo);
}, false);
in my apps javascript
var event = new CustomEvent("copyEvent", {
detail:{
copyInfo: {dataToCopy:"my string"}
}
});
window.dispatchEvent(event);
Hope this helps anyone else who's ran into this issue!
First let me thank you for the assistance, I am new to Javascript, and want to learn to parse a >.xml file into my javascript. The file I want to parse is contact.xml, located in my root folder.
Again, thank you.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1 /DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function loadXMLDoc(XMLname)
{
var xmlDoc;
if (window.XMLHttpRequest)
{
xmlDoc=new window.XMLHttpRequest();
xmlDoc.open("GET",XMLname,false);
xmlDoc.send("");
return xmlDoc.responseXML;
}
// IE 5 and IE 6
else if (ActiveXObject("Microsoft.XMLDOM"))
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load(XMLname);
return xmlDoc;
}
alert("Error loading document!");
return null;
}
<title>Contacts</title>
</script>
</head>
<body>
<script type="text/javascript">
xmlDoc = loadXMLDoc("contactinfo.xml") // Path to the XML file;
var M = xmlDoc.getElementsByTagName("item");
for (i=0;i<M.length;i++){
document.write("<div style='width:450px;'>")
document.write("<h2>"+xmlDoc.getElementsByTagName("item")[i].childNodes[0].nodeValue+"</h2>");
document.write("<p>" + xmlDoc.getElementsByTagName("servicephone")[i].childNodes[0].nodeValue+ "</p>");
document.write("<p><a href='" + xmlDoc.getElementsByTagName("email")[i].childNodes[0].nodeValue +"</p>);
document.write("</div>")
}
</script>
</body>
</html>
*Here is my .xml file*
<?xml version="1.0" encoding="utf-8" ?>
<Contacts>
<item servicephone="(800) 500-0066"
email="customerservice#fsig.com"
url="http://www.fsig.com"
address="5000 Barcilona Beach Rd. Wilmington, NC 28000">
</item>
</Contacts>
You need to go down the hierarchy, so, first find the Contacts node, then inside there you can get all the tagnames as you have.
You have a great deal of attributes so you may find this useful also:
node.attributes["url"].nodeValue
So just loop through all the items, then I would just copy itemelem[t] to node just to make it easier, then you get the attributes you need.
Depending on the browser you are using most of them come with some javascript debugger, so you can put in breakpoints and look at the values in the variables and see what the next step needs to be.
I'm using JavaScript interface for checking if Google's StreetView is available. My problem is that from android 3.0 code stopped working, and I am unnable to find why. Problem is that methods from "JavascriptCheck" interface are never called and Logcat doesn't show any errors.
Java code:
public void showStreetView(GeoPoint geoPoint) {
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JavascriptCheck(), "Android");
lat = geoPoint.getLatitudeE6()/1E6;
lon = geoPoint.getLongitudeE6()/1E6;
webView.loadDataWithBaseURL("", context.getString(R.string.html_streetview, lat, lon), "text/html", "UTF-8", "");
}
public class JavascriptCheck {
public void hasStreetview(boolean hasStreetview) {
if (hasStreetview) {
openStreetView();
} else {
Toast.makeText(context, context.getString(R.string.loc_no_street_view), Toast.LENGTH_SHORT).show();
}
}
}
WebView in layout file:
<WebView android:id="#+id/webView"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:visibility="gone">
</WebView>
JavaScript string:
<string name="html_streetview">
<html>
<head>
<script src=\"http://maps.google.com/maps?file=api&v=2& sensor=false\" type=\"text/javascript\"/>
</head>
<body>
<script type=\"text/javascript\">
var testPoint = new GLatLng(%1$s, %2$s);
var svClient = new GStreetviewClient();
svClient.getNearestPanoramaLatLng(testPoint, function (nearest) {
if ((nearest !== null) && (testPoint.distanceFrom(nearest) <= 100)) {
Android.hasStreetview(true);
} else {
Android.hasStreetview(false);
}
});
</script>
</body>
</html>
</string>
Solved my problem long ago, just wanted to share with others. Honeycomb and later Android versions require that you use full html <script> tags. Also it is better to keep script string in assets folder. My assets/index.html looks like this now:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript">
var sv = new google.maps.StreetViewService();
function hasStreet(lat, lon) {
var point = new google.maps.LatLng(lat, lon);
sv.getPanoramaByLocation(point, 50, isSVAvailable);
}
function isSVAvailable(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
Android.hasStreetview(true);
} else {
Android.hasStreetview(false);
}
}
</script>
</head>
<body></body>
</html>
I too was using this function and have seen it broken since I tried upgrading my app for ICS. It seems that the Javascript won't execute if you have an external src link. If you take out the javascript src link and add some logging you'll see that the script will run (and obviously return false all the time).
I know in the docs they recommend not using javascript that calls into your native code unless you control all elements in the javascript but perhaps now they explicitly stop code from running that references an external resource?
I'm currently working on a project for Adobe Air (1.5.3) and I need to unzip a file, copy some of its contents to another file.
Then I saw people talking about the Fzip (http://codeazur.com.br/lab/fzip) lib. The problem is that I don't know how to "import" or use this library with Javascript and Adobe Air, since Javascript doesn't have the import directive.
How can I manage to do that ?
I posted a demo of how to use FZip with Adobe Air and Javascript. I hope it hopes clear things up for you.
In short you need to pull the SWF file out of the compiled SWC (when applicable) and access the class.
The demo is pretty simple and really just a proof of concept but you should be able to extend it easily.
http://www.drybydesign.com/2010/05/12/adobe-air-fzip-without-flex/
-Ari
Ari's example is pretty good, and it got me started but he left out some pretty crucial stuff--like writing the uncompressed files back to the disk. And the zip file does not have to be hosted remotely--the thing about AIR is that it runs like a local Application...here is an example that build on the good start Ari gave us. (I am using HTML5 just to be cool and hip and modern! :)-
<!DOCTYPE HTML>
<html>
<head>
<title>Test Fzip</title>
<script type="application/x-shockwave-flash" src="scripts/fzip.swf"></script>
<script type="text/javascript" src="scripts/AIRAliases.js"></script>
<script type="text/javascript" src="scripts/AIRIntrospector.js"></script>
<script type="text/javascript" src="scripts/jquery-1.4.2.js"></script>
<script type="text/javascript">
var fzip;
if (window.runtime) {
if (!fzip)
fzip = {};
fzip.FZip = window.runtime.deng.fzip.FZip;
fzip.FZipFile = window.runtime.deng.fzip.FZipFile;
}
var file = air.File.documentsDirectory.resolvePath("test.zip");
//file.url
var zip = new fzip.FZip;
zip.addEventListener(air.Event.OPEN, onopen);
zip.addEventListener(air.Event.COMPLETE, oncomplete);
zip.load(new air.URLRequest(file.url.toString()));
function oncomplete(event) {
var count = zip.getFileCount();
alert(count);
for ( var idx = 0; idx < count; idx++)
{
var zfile = zip.getFileAt(idx);
// alert(zfile.filename);
var uzfile = air.File.applicationStorageDirectory.resolvePath(zfile.filename);
var stream = new air.FileStream();
stream.open( uzfile, air.FileMode.WRITE );
stream.writeBytes( zfile.content,0, zfile.content.length );
stream.close();
}
}
function onopen(event) {
alert("file is opened");
}
</script>
</head>
<body>
</body>
</html>