Application requests KML data through AJAX from server. This data is stored in javascript variables, and displayed in Google Earth plugin.
In javascript, how do I
Frankly, I don't think this is possible. It was never intended that this could be done in javascript.
Probably it would be usefull (JSP variant):
private void printSaveStringButton(String fileName, String content) throws Exception {
//add new invisible container with write / save functions
out.println("<iframe id=\"xmlContentId\" style=\"display:none;\"></iframe>");
//save string in js variable
String jScript = "\n" +
"var SaveHelper = {\n" +
" content : null,\n" +
" saveContent : function(filename, text) {\n" +
" text=(SaveHelper.content!=null)?SaveHelper.content:text;\n" +
" var doc = document.getElementById('xmlContentId').contentWindow.document;\n" +
" doc.write(text);\n" +
" doc.execCommand(\"saveAs\",true,filename);\n" +
" doc.close();\n" +
" }\n" +
"};\n" +
"SaveHelper.content = '" + org.apache.commons.lang.StringEscapeUtils.escapeJavaScript(content) + "';\n";
out.println("<script type=\"text/javascript\">" + jScript + "</script>");
//add button that writes content into iframe container and show save dialog.
out.println("<button type=\"button\" onclick=\"SaveHelper.saveContent('"+fileName+"' )\">Save as...</button>");
}
You could probably use the parseKml function to parse the kml data in the javascript variable rather than trying to store it in a file and modifying it from javascript (which I dont think is possible due to security reasons)
https://developers.google.com/earth/documentation/kml
Check out http://regany.com/blog/2014/05/30/convert-a-string-to-a-download-file-in-javascript/
Enable popups and use the following code:
var str = "the string you wan't to download";
window.open('data:text/plain,' + encodeURIComponent(str));
You might want to check this out: it's called Downloadify. It uses a mix of Javascript and Flash, and can save a string in pretty much any format. Try out the demo and see for yourself!
This will work! It works for me.
enter link description here
`function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
// Start file download.
download('hello.txt','This is the content of my file ');
`