How to convert JSON to GeoJSON - javascript

I am very new in my learnings of javascript and my rudimentary knowledge has hit a wall. I have setup a Leaflet map which I am wishing to plot divIcon based markers from cords on it from JSON. Through my countless research of trying to get it to work. I learned why my JSON file wasn't working even though I confirmed in the console it was being read. I learned Leaflet prefers it to be in GeoJSON. So I spent several more hours researching how to convert this. Most of my findings were outdated and did not work anymore or did not apply to me. This is what I did try through my rigorous research.
To start off I have set a variable for the path to my test JSON file as defined like this.
var jsonData = "./data/tracking.json";
In my attempt to convert the JSON to GeoJSON I tried this.
var outGeoJson = {}
outGeoJson['properties'] = jsonData
outGeoJson['type']= "Feature"
outGeoJson['geometry']= {"type": "Point", "coordinates":
[jsonData['lat'], jsonData['lon']]}
console.log(outGeoJson)
Checked the console and found the coordinates in the array from JSON file are undefined.
My search for a reason why this was coming up undefined fell short. My theory here is maybe because the JSON has a key of positions prior to the array and the fact it is an array. I continue to search for a valid solution that could possibly handle this issue. I tried this solution next.
var geojson = {
type: "FeatureCollection",
features: [],
};
for (i = 0; i < jsonData.positions.length; i++) {
if (window.CP.shouldStopExecution(1)) {
break;
}
geojson.features.push({
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [jsonData.positions[i].longitude, jsonData.positions[i].latitude]
},
"properties": {
"report_at": jsonData.positions[i].report_at,
"lat": jsonData.positions[i].lat,
"lon": jsonData.positions[i].lon,
"dir": jsonData.positions[i].dir,
"first": jsonData.positions[i].first,
"last": jsonData.positions[i].last
}
});
}
window.CP.exitedLoop(1);
console.log(geojson)
This solution gave me an error in the console of Uncaught TypeError: Cannot read property 'length' of undefined.
Attempted to troubleshoot that solution for several more hours and that has fallen short as well. Here is a sample of the test JSON file I am working with.
{
"positions": [
{
"report_at": "2015-01-21 21:00:08",
"lat": "38.9080658",
"lon": "-77.0030365",
"elev": "0",
"dir": "0",
"gps": "0",
"callsign": "WX2DX",
"email": "",
"phone": "",
"ham": "WX2DX",
"ham_show": "0",
"freq": "",
"note": "",
"im": "",
"twitter": null,
"web": "",
"unix": "1421874008",
"first": "William",
"last": "Smith",
"marker": "36181"
}
]
}
All I really need from it is the report_at, lat, lon, dir, first, last anyways. The rest I can do without. Is the above mentioned examples I tried a good or proper way to convert it? If not, then does anyone have a better suggestion than what I have been trying that I might be missing or overlooking which is a pretty good possibility due to be very green to this language? Thanks in advance!
EDIT: Since it has been brought to my attention I am not loading the JSON file this is what I have done to load it since the suggestions do not work as they apply to node.js and not a part of native javascript.
$.getJSON("./data/tracking.json", function(jsonData) {
var outGeoJson = {}
outGeoJson['properties'] = jsonData
outGeoJson['type']= "Feature"
outGeoJson['geometry']= {"type": "Point", "coordinates":
[jsonData['lat'], jsonData['lon']]}
console.log(outGeoJson)
});
This does load the file as it is displaying in the console as converted to GeoJSON. I will leave this as is for now unless there is a better solution.

If you do have jQuery in your project added, then you are almost there:
$.getJSON("./data/tracking.json", function(jsonData) {
/*
Here the anonymous function is called when the file has been downloaded.
Only then you can be sure that the JSON data is present and you can work with it's data.
You have to keep in mind if you are getting the file synchronously or asynchronously (default).
*/
});

var jsonData = "./data/tracking.json";
try replacing this with the next line.
var jsonData = require("./data/tracking.json");
or
import jsonData from "./data/tracking.json"; #es6 style
as #PatrickEvans mentioned you have to actually load the data rather than giving path as a string.

Related

Unable to retrieve contents of JSON post

I have a script in Sheets that is supposed to flatten a JSON post but am having some difficulty getting around the format of the incoming JSON.
Below, I have an example POST which I am trying to parse. Underneath that is my doPost function, with some of the ways I have tried getting the content. doPost uses another function to actually parse the content, but I can't seem to get around what looks like an array formatted JSON?
Here is an example of the POST object:
[
{
"id": "xyz123",
"payload": {
"reference_id": "id_6",
"unit_id": "000111222",
"origin": {
"name": "T-shirt Supply",
"city": "Jiujiang",
"state": "Jiangxi",
"country": "China",
},
"destination": {
"name": "Main Office",
"city": "Surabaya",
"state": "East Java",
"country": "Indonesia",
},
},
"status": "data_received",
"created_at": "2020-01-29T07:41:33.918Z",
"updated_at": "2020-01-29T07:41:33.918Z"
}
]
I have tried in several ways to access the contents, such as payload.reference_id, but for some reason can't find my way into the curled brackets of the JSON object. Here are some of the ways I have tried:
function doPost(e){
var data = e.postData.contents;
// returns JSON formatted [{ "id": "xyz", "payload" : {"reference" : "1", "updated" : true}}]
var data2 = JSON.parse(e.postData.contents);
// returns [object Object]
var data3 = data[0];
// returns [
var data4 = ContentService.createTextOutput(e.postData.contents).setMimeType(ContentService.MimeType.JSON);
// same result as 'data'
return dataX;
}
I have also attempted various workarounds, such as parsing twice, stringify, and more. Any help is greatly appreciated!!!
I think you don't need to parse e.postData.contents, probably it is already an object, not string.
Or if it is string and there is only one element, you can try this:
var data2 = JSON.parse(e.postData.contents.slice(1,-1));
I believe your goal is as follows.
You want to output the object of the 1st element in an array which is your sample value from doPost.
If my understanding is correct, how about the following modification?
Modified script:
function doPost(e){
var data2 = JSON.parse(e.postData.contents);
return ContentService.createTextOutput(JSON.stringify(data2[0])).setMimeType(ContentService.MimeType.JSON);
}
In this modification, it supposes that e.postData.contents is your sample value. Please be careful about this.
When the above-modified script is used, the 1st element of the array is returned.
Note:
When you modified the Google Apps Script, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful about this.
You can see the detail of this in the report of "Redeploying Web Apps without Changing URL of Web Apps for new IDE".
Reference:
createTextOutput()

Socrata map results in $http request, Javascript

I am trying to use this dataset to determine which district boundary an address (passed into the API call) falls within.
The endpoint returns an array of objects for each district or council. The polygon is found within the "the_geom" property, with 2 properties - type and coordinates. I have tried using $where, but I get errors.
[
{
"comments": "Inaugurated 2015-06-22",
"council": "1",
"councilper": "Scott Griggs",
"district": "1",
"objectid": "1",
"shape_area": "343352603.892",
"shape_leng": "88541.3042539",
"the_geom": {
"type": "MultiPolygon",
"coordinates": [
[
[
[
-96.80995700065864,
32.77138899977414
],
[
-96.80969800043205,
32.77121999997131
],
[ ...
I tried to use the query below, but it gave me an error:
https://www.dallasopendata.com/resource/h9ws-fqcn.json?$where=within_polygon(the_geom, 'MULTIPOLYGON (((-96.800270, 32.779091)))')
This is the page reference page - https://www.dallasopendata.com/Geography-Boundaries/Adopted-Council-Districts/6dcw-hhpj
And this is the endpoint- https://www.dallasopendata.com/resource/dgxr-hmze.json
any help would be greatly appreciated.
I suspect you're the developer who popped into our IRC channel, but I'll answer here too!
You're pretty close here! What you want to do here is use the intersects(...) SoQL function with a Well Known Text (WKT) POINT.
Here's an example that works for your use case:
https://www.dallasopendata.com/resource/h9ws-fqcn.json?$where=intersects(the_geom,%20%27POINT%20(-96.7994007%2032.775765)%27)

how to store data in local browser & retrieve back from it

i have json data below, i want to store those data in my browser & finally i want to get back those data from my browser if user request it from a textbox. How to do this stuffs?
Actually, i am a server side programmer, this is my second javascript/jquery demo example. I am basically trying to learn these stuffs with the help of creating demo. Please help me to learn.
i have jason data obtained by calling remote websites(eg. www.google.com/finance/....)
{
"list": {
"meta": {
"type": "resource-list",
"start": 0,
"count": 168
},
"resources": [{
"resource": {
"classname": "Quote",
"fields": {
"name": "USD/KRW",
"price": "1062.280029",
"symbol": "KRW=X",
"ts": "1396294510",
"type": "currency",
"utctime": "2014-03-31T19:35:10+0000",
"volume": "0"
}
}
}, {
"resource": {
"classname": "Quote",
"fields": {
"name": "SILVER 1 OZ 999 NY",
"price": "0.050674",
"symbol": "XAG=X",
"ts": "1396287757",
"type": "currency",
"utctime": "2014-03-31T17:42:37+0000",
"volume": "217"
}
}
}
]
}
}
Using jQuery and Localstorage you could do:
Set item:
localStorage.setItem('myJSON',yourJSONString);
Remove item:
localStorage.removeItem('myJSON');
Get item:
var JSONString = localStorage.getItem('myJSON');
There are several types of browser storage such as localStorage they are all built in and can be used directly.
Storage objects are a recent addition to the standard. As such they may not be present in all browsers.........The maximum size of data that can be saved is severely restricted by the use of cookies.
Code sample:
function storeMyContact(id) {
var fullname = document.getElementById('fullname').innerHTML;
var phone = document.getElementById('phone').innerHTML;
var email = document.getElementById('email').innerHTML;
localStorage.setItem('mcFull',fullname);
localStorage.setItem('mcPhone',phone);
localStorage.setItem('mcEmail',email);
}
On the other hand, localStorage might not be enough, therefore, external libraries come to hand which actually utilize the browsers built in storage and make the db works cross browsers.
1- SQL like DB sequelsphere (looks like suitable for heavy lifting!)
Code sample for query that will run directly from the browser:
SELECT empl_id, name, age
FROM empl
WHERE age < 30
2- JSON like DB taffydb (looks like suitable for every day activity!)
// Create DB and fill it with records
var friends = TAFFY([
{"id":1,"gender":"M","first":"John","last":"Smith","city":"Seattle, WA","status":"Active"},
{"id":2,"gender":"F","first":"Kelly","last":"Ruth","city":"Dallas, TX","status":"Active"},
{"id":3,"gender":"M","first":"Jeff","last":"Stevenson","city":"Washington, D.C.","status":"Active"},
{"id":4,"gender":"F","first":"Jennifer","last":"Gill","city":"Seattle, WA","status":"Active"}
]);
// Find all the friends in Seattle
friends({city:"Seattle, WA"});
3- jstorage is a cross-browser key-value store database to store data locally in the browser - jStorage supports all major browsers, both in desktop (yes - even Internet Explorer 6) and in mobile.
If you would like to have more options ->(client-side-browser-database)

result not coming with d3js?

After lot of help from stackoverflow folks,finally resolved my json and now its looking good.
luck.json--->
{
"PERFECT_JSON_object":
{
"51b59c1bbae1c":
[
{ "id": "parties", "float_1": "0.006" , "float_2": "0.9"},
{ "id": "royal-challenge", "float_1": "0.02" , "float_2": "0.333" },
{ "id": "star-speak","float_1": "0.02","float_2":"0.1" }
],
"51b59c1bbae3c":
[
{ "id": "parties","float_1": "0.006" , "float_2": "0.9"},
{ "id": "star-speak","float_1": "0.02", "float_2": "0.009" }
],
"51b59c1bbae5c":
[
{ "id": "parties","float_1": "0.006" , "float_2": "0.9"}
]
}
}
I have been trying to get my head around d3js with json,and I must say I have progressed quite a bit.But I am still not able to get the output with json data.
I went through these link`s but dint help.
https://github.com/mbostock/d3/wiki/Requests
d3.js & json - simple sample code?
Access / process (nested) objects, arrays or JSON
MyFIDDLE with json(no output,something wrong in here)
same fiddle with some static values( without Json)--
This is the result that I want.
I know that d3.json method requires json file to be on server.For temporary basis,as the json file is small can we include it directly in a variable in our d3 script??
I think I am messing up with json data in a wrong way.Can somebody help me with it
Yes, you can just add the JSON in a variable and run it this way. See here for the updated jsfiddle. You basically just add your JSON after var data =.

How to translate Solr JSON response into HTML while JSON is different every time

I am using Solr 4 for searching in a java web application.Solr produces a JSON response from which i have to extract search results and translate them into html so user can read that.
I know one solution but it seems dumb an I think there must be intelligent ideas.
{
"responseHeader": {
"status": 0,
"QTime": 0,
"params": {
"fl": "id,title",
"indent": "true",
"q": "solr",
"wt": "json"
}
},
"response": {
"numFound": 3,
"start": 0,
"docs": [
{
"id": "1",
"title": "Solr cookbook"
},
{
"id": "2",
"title": "Solr results"
},
{
"id": "3",
"title": "Solr perfect search"
}
]
}
}
After that i eval this text as:
var obj = eval ("(" + txt + ")");
To generate html page i can use either
<script>
document.getElementById("id").innerHTML = obj.response.docs[1].id
document.getElementById("title").innerHTML = obj.response.docs[1].title
</script>
or
document.write(obj.response.docs[1].id);
But limitation is that every time solr gives response with different object structure i.e. an object may have age feild but other can not have because it depends on query.
I want to use a sigle JSP page to display search results(like Google)
for all search queries
is it possible to write a single code segment which works for any possible search results with different schema.
Javascript stops working after encountering any error which is likely in my case. that's also problem.if I use for loop to traverse the object hierarchy it is highly error -prone.
Is it possible with a single view page Thanks.
You might want to consider using ajax-solr - A JavaScript framework for creating user interfaces to Solr
I suggest using Velocity templating which is readily supported in Solr - instead of extracting data from the JSON and rendering the HTML via JS.
Docs here

Categories

Resources