How to get coordinates from a KML file? - google-maps

Is there any way to parse a kml file and get the coordinates from it with JavaScript?
I've tried doing it with "getElementsByTagName" (like here) but debugger says it's not a valid function.
Any ideas?

It's not easy but you can import the file xml and the parsing with jquery parseXML
// import the file --- se related function below
var content = getSelectedFileContent(importFilename);
// build an xmlObj for parsing
xmlDocObj = $($.parseXML(content));
function getSelectedFileContent(filename) {
// var importFilename = importAreaBaseURL + filename;
var request = new XMLHttpRequest();
request.open("GET", filename, false);
request.send(null);
return request.responseText;
};
at this point you can easy parse the xml obj for placemark and iterate over them for the tag/value you need via jquery
var placemarks = xmlDocObj.find("Placemark");
placemarks.each(function (index) {
if ($(this).find("Polygon").length > 0) {
tipoGeom = "Polygon";
tmpHtml = $(this).find("Polygon").find("outerBoundaryIs").find("coordinates").html();
gmlll_geom = kmlCoords2gmlll( tmpHtml);
inner = $(this).find("Polygon").find("innerBoundaryIs");
inner.each(function(index,el) {
$(el).find("coordinates").html(); // this are the coordinates for polygion
});
}
});
These are sample parts (an extract of functioning code .... not all you need) this code is just for a suggestion....

Related

Excel to JSON parsing

I am trying to parse Excel data to JSON to feed drop downs in HTML. I am having a hard time getting this to work. I have looked all over the web. I am new to javascript so i find it overwhelming.
There seems to be a lot of scripting and to make this work. If anyone can help and explain how to set this up i would be greatly appreciative.
Thanks All,
HAppleknocker
This article explained clearly how to make the JSON object from a Excel File. After getting the JSON object as a string you can use it to do anything.
In here used sheet js and sample javaScript code available on GitHub.
How to convert Excel data into JSON object using JavaScript
<script>
$(document).ready(function(){
$("#fileUploader").change(function(evt){
var selectedFile = evt.target.files[0]; //Get the ExcelFile
var reader = new FileReader();
reader.onload = function(event) {
var data = event.target.result;
var workbook = XLSX.read(data, {
type: 'binary'
});
workbook.SheetNames.forEach(function(sheetName) {
var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
var json_object = JSON.stringify(XL_row_object);
document.getElementById("jsonObject").innerHTML = json_object;
})
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsBinaryString(selectedFile);
});
});
</script>

Convert .txt file to JSON

I want to convert a fairly unorganized and unstructured text file to JSON format. I want to be able to use the city ID information. Is there anyway I can convert this to JSON?
UPDATE: I also found this solution after a while. Very simple way to get the JSON of any tab separated text file.
https://shancarter.github.io/mr-data-converter/
You can try to use tsv2json this tool can reads a tsv file from stdin and writes a json file to stdout.
It's distributed in source file, to compile it you need to download D compiler and then run dmd tsv2json.d.
If you have more complex task there is another tool named tsv-utils
TSV to JSON in nodejs
var file_name = 'city_list.txt';
var readline = require('readline');
var fs = require('fs');
var lineReader = readline.createInterface({
input: fs.createReadStream(file_name)
});
var isHeader = false;
var columnNames = [];
function parseLine(line) {
return line.trim().split('\t')
}
function createRowObject(values) {
var rowObject = {};
columnNames.forEach((value,index) => {
rowObject[value] = values[index];
});
return rowObject;
}
var json = {};
json[file_name] = [];
lineReader.on('line', function (line) {
if(!isHeader) {
columnNames = parseLine(line);
isHeader = true;
} else {
json[file_name].push(createRowObject(parseLine(line)));
}
});
lineReader.on('close', function () {
fs.writeFileSync(file_name + '.json', JSON.stringify(json,null,2));
});

Creating a zip file from a JSON object using adm-zip

I'm trying to create a .zip file from a JSON object in Node.js. I'm using adm-zip to do that however I'm unable to make it work with this code:
var admZip = require('adm-zip');
var zip = new admZip();
zip.addFile(Date.now() + '.json', new Buffer(JSON.stringify(jsonObject));
var willSendthis = zip.toBuffer();
fs.writeFileSync('./example.zip', willSendthis);
This code creates example.zip but I'm not able to extract it, I tried with a .zipextractor but also with this code:
var admZip = require('adm-zip');
var zip = new admZip("./example.zip");
var zipEntries = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function(zipEntry) {
console.log(zipEntry.data.toString('utf8'));
});
It returns Cannot read property 'toString' of undefined at the line with console.log.
I could use zip.writeZip() for this example but I'm sending the .zipfile to Amazon S3 thus I need to use the method .toBuffer() to do something like this after using adm-zip:
var params = {Key: 'example.zip', Body: zip.toBuffer()};
s3bucket.upload(params, function(err, data) {...});
I don't see what is wrong, am I using the package correctly?
Try use zipEntry.getData().toString('utf8') instead zipEntry.data.toString('utf8'):
var admZip = require('adm-zip');
var zip = new admZip("./example.zip");
var zipEntries = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function(zipEntry) {
console.log(zipEntry.getData().toString('utf8'));
});

Reference Google Spreadsheet (CSV) in Jekyll Data

I am managing a website displaying a lot of tabular data (language stuff) and running on Jekyll. I really like to display content based on a CSV file stored in the _data folder of Jekyll.
I would like to be able to edit / add / remove content from this CSV directly on Google and then reference it to Jekyll (like a shortcut or something that sync the CSV content from Google to my static folder).
Which way would be the simplest to reference an external file (either in the _data folder or directly in my templace). I can find the CSV file with this kind of link but downloading it every time is a hassle (https://docs.google.com/spreadsheets/d//export?format=csv).
How can Jekyll understand data from external stored file (maybe in javascript ?).
Thank you.
Getting datas from google docs is becoming harder ;-(
I've tried with jquery.ajax but I met the CORS limitation.
Then I found tabletop and it works !
go to your google spreadsheet and File > Publish to the web > Start publishing
note the publish url
download tabletop script and save it to eg: js/tabletop.js
put a link at the bottom of your _includes/header.html eg
<script src="`{{ site.baseurl }}`/js/tabletop.js"></script>
in a data.html page put
---
title: csv to json
layout: page
---
<div id="csvDatas"></div>
you can now get your datas with a js/script.js file that you've also included at the very end of you _includes/footer.html
var csvParse = function() {
// put you document url here
var sharedDocUrl = 'https://docs.google.com/spreadsheets/d/1Rk9RMD6mcH-jPA321lFTKmZsHebIkeHx0tTU0TWQYE8/pubhtml'
// can also be only the ID
// var sharedDocUrl = '1Rk9RMD6mcH-jPA321lFTKmZsHebIkeHx0tTU0TWQYE8'
var targetDiv = 'csvDatas';
// holds datas at a closure level
// this then can be accessed by closure's functions
var dataObj;
function showInfo(data, tabletop) {
dataObj = data;
var table = generateTable();
var target = document.getElementById(targetDiv);
target.appendChild(table);
}
function generateTable(){
var table = document.createElement("table");
var head = generateTableHeader();
table.appendChild(head);
var body = generateTableBody();
table.appendChild(body);
return table;
}
function generateTableHeader(){
var d = dataObj[0];
var tHead = document.createElement("thead");
var colHeader = [];
$.each(d, function( index, value){
console.log(index + ' : ' + value);
colHeader.push(index);
});
var row = generateRow(colHeader, 'th');
tHead.appendChild(row);
return tHead;
}
// this can be factorized with generateTableHeader
function generateTableBody(){
var tBody = document.createElement("tbody");
$.each(dataObj, function( index, value ){
var rowVals = [];
$.each(value, function(colnum, colval){
rowVals.push(colval);
});
var row = generateRow(rowVals);
tBody.appendChild(row);
});
return tBody;
}
function generateRow(headersArray, cellTag){
cellTag = typeof cellTag !== 'undefined' ? cellTag : 'td';
var row = document.createElement("tr");
$.each(headersArray, function( index, value){
if( value != "rowNumber"){
var cell = document.createElement(cellTag);
var cellText = document.createTextNode(value);
cell.appendChild(cellText);
row.appendChild(cell);
}
});
return row;
}
return {
init: function() {
if( $('#' + targetDiv).length ){
Tabletop.init( { key: sharedDocUrl ,
callback: showInfo,
simpleSheet: true } );
}else{
console.log('Not the good page to parse csv datas');
}
}
};
}();
$( document ).ready(function() {
csvParse.init();
});

Binding JSON string to ListView in Metro apps?

I have a metro application(HTML5 & WinJS) in which am trying to display service data . Actually here am retrieving JSON data from my service but am unable to bind this data into listview . Anyone give me some working example.
Thank you.
You can use the WinJS.xhr() for this. You can read more about it on this link https://msdn.microsoft.com/pt-br/library/windows/apps/br229787.aspx and here is an example:
var path = "data/file.json";
function getData(path) {
WinJS.xhr({ url: path }).then(
function (response) {
var json = JSON.parse(response.responseText);
// Since this is an asynchronous function, you can't
// return the data, so you can:
// 1) retrieve the data to a namespace once the app loads.
var list = new WinJS.Binding.List(json);
Somenomespace.data = list;
// 2) or do all the binding inside the function.
var listView = document.getElementById("listViewID");
listView.winControl.itemDataSource = list.dataSource;
});
}
If you use the built in JSON.parse(jsonString) function you can loop through the content using a normal for loop as it then is a normal object and add it as usuall. Just remember to process or render the data.
Her is an example from code i had in a search page using listview:
var response = JSON.parse(data) ;
var originalResults = new WinJS.Binding.List();
for (x in response) {
originalResults.push(response[x]);
}
this.populateFilterBar(element, originalResults);
this.applyFilter(this.filters[0], originalResults);