Format HERE Map API JSON Response - json

I am experiencing an issue formatting the JSON response from the HERE Map API for an isoline. The full HERE API JSON response is shown below and contains Lat/Long coordinates for a line as shown below.
{
"response": {
"metaInfo": {
"timestamp": "2017-03-03T23:40:34Z",
"mapVersion": "8.30.68.151",
"moduleVersion": "7.2.201709-111134",
"interfaceVersion": "2.6.29"
},
"center": {
"latitude": 34.603565,
"longitude": -98.3959
},
"isoline": [
{
"range": 300,
"component": [
{
"id": 0,
"shape": [
"34.6096802,-98.4147549",
"34.6096802,-98.4141541",
"34.6098518,-98.4136391",
"34.6101952,-98.4132957",
"34.6103668,-98.4127808",
"34.6101952,-98.4122658",
"34.6098518,-98.4119225",
"34.6098518,-98.4115791",
"34.6101952,-98.4112358",
"34.5998955,-98.4115791",
"34.6002388,-98.4126091",
"34.6005821,-98.4129524",
"34.6009254,-98.4139824",
"34.6019554,-98.4143257",
"34.6022987,-98.4153557",
....
"34.6081352,-98.4129524",
"34.6083069,-98.4134674",
"34.6083069,-98.4148407",
"34.6084785,-98.4153557",
"34.6089935,-98.4155273",
"34.6095085,-98.4154415",
"34.6096802,-98.415184",
"34.6096802,-98.4147549"
]
}
]
}
],
"start": {
"linkId": "+888249498",
"mappedPosition": {
"latitude": 34.6034836,
"longitude": -98.3959009
},
"originalPosition": {
"latitude": 34.603565,
"longitude": -98.3959
}
}
}
}
I am mapping the isoline data in Leaflet as a polygon. I can do it manually like this, and all works well.
var polygon = L.polygon([
[34.6343994, -98.7664032],
[34.6357727, -98.76297],
[34.6385193, -98.7602234],
[34.6398926, -98.7561035],
[34.6385193, -98.7519836],
[34.6357727, -98.7492371],
[34.6357727, -98.7464905],
.....
[34.6302795, -98.7712097],
[34.6330261, -98.7718964],
[34.6343994, -98.7698364],
[34.6343994, -98.7664032]
]
).addTo(map);
Am now trying to automate it but cannot get the json output into a compatible format for Leaflet. I can make the API call, capture the JSON response, and extract the array of lat/long coordinates using the following code:
function getJson(url) {
return JSON.parse($.ajax({
type: 'GET',
data: '',
url: url,
dataType: 'json',
global: false,
async: false,
success: function (data) {
return data;
}
}).responseText);
}
var myJsonObj = getJson('https://isoline.route.cit.api.here.com/routing/7.2/calculateisoline.json?mode=fastest;car;traffic:disabled&jsonAttributes=1&rangetype=time&start=34.603565,-98.3959&app_id=id&app_code=codeg&range=1800');
var isoline = myJsonObj.response.isoline[0].component[0].shape;
The variable isoline looks like this (an array of lat/long coordinate pairs) but I cannot get them into an array of arrays as needed for Leaflet.
[
"34.6096802,-98.4147549",
"34.6096802,-98.4141541",
"34.6098518,-98.4136391",
"34.6101952,-98.4132957",
"34.6103668,-98.4127808",
"34.6101952,-98.4122658",
"34.6098518,-98.4119225",
"34.6098518,-98.4115791",
"34.6101952,-98.4112358",
"34.5998955,-98.4115791",
"34.6002388,-98.4126091",
"34.6005821,-98.4129524",
"34.6009254,-98.4139824",
"34.6019554,-98.4143257",
"34.6022987,-98.4153557",
....
"34.6081352,-98.4129524",
"34.6083069,-98.4134674",
"34.6083069,-98.4148407",
"34.6084785,-98.4153557",
"34.6089935,-98.4155273",
"34.6095085,-98.4154415",
"34.6096802,-98.415184",
"34.6096802,-98.4147549"
]
Would appreciate any help in reformatting the coordinates to look like this
[
[34.6343994, -98.7664032],
[34.6357727, -98.76297],
[34.6385193, -98.7602234],
[34.6398926, -98.7561035],
[34.6385193, -98.7519836],
[34.6357727, -98.7492371],
[34.6357727, -98.7464905],
.....
[34.6302795, -98.7712097],
[34.6330261, -98.7718964],
[34.6343994, -98.7698364],
[34.6343994, -98.7664032]
]
It may be that there is a better way of putting the data in Leaflet as well, but Polygon and Polyline are the only methods I can find and they require the coordinates in an array of arrays.

You need to iterate over each element and split, forming an array.
Like this, (ES6 way)
const newArray = array.map(a => a.split(',').map(Number));
or (Non ES6 way)
var newArray = [];
array.forEach(function (a){ newArray.push(a.split(',').map(Number)); });
So your final code should look like this,
function getJson(url) {
return JSON.parse($.ajax({
type: 'GET',
data: '',
url: url,
dataType: 'json',
global: false,
async: false,
success: function (data) {
return data;
}
}).responseText);
}
function parseJSONForPolygon(rawJsonArray) {
var newArray = [];
rawJsonArray.forEach(function (a) { newArray.push(a.split(',').map(Number)); });
return newArray;
};
var myJsonObj = getJson('https://isoline.route.cit.api.here.com/routing/7.2/calculateisoline.json?mode=fastest;car;traffic:disabled&jsonAttributes=1&rangetype=time&start=34.603565,-98.3959&app_id=id&app_code=codeg&range=1800');
var isoline = parseJSONForPolygon(myJsonObj.response.isoline[0].component[0].shape);
.map(Number) credit goes to
https://stackoverflow.com/a/15677905/923426

let polygonArray = [];
data.response.isoline.component.shape.forEach((elm) => {
polygonArray.push(elm.split(','));
})
now your polygonArray will be acceptable by leaflet

Related

How to convert Backbone fetched object to proper Handlebars JSON Object?

Currently I have an issue with getting back a proper JSON object I'm fetching with Backbone fetch() and putting it into a Handlebars template.
See below my code, I have made a ugly workaround for now to test my Backend API
When converting to JSON with *.toJSON(), it just adds an extra object in-between and I don't need this extra object
Object [0]
--> books
----> Object [0]
------> Array of book
--------> book
--------> cities
JSON
{
"books": [
{
"book": 00001,
"cities": [
"TEST"
]
},
{
"book": 00002,
"cities": [
"TEST"
]
},
{
"book": 00003,
"cities": [
"TEST"
]
}
],
"more": true
}
JavaScript
var Book = Backbone.Model.extend({
default: {
book: 0,
cities: ["TEST1", "TEST2", "TEST3"]
},
url: function () {
return ".list.json";
}
});
var Books = Backbone.Collection.extend({
model: Book,
url: ".list.json"
});
var BooksView = Backbone.View.extend({
initialize: function(){
_.bindAll(this, 'render');
this.collection = new Books();
this.collection.fetch();
this.source = $('.e-books-template').html();
// Use an extern template
this.template = Handlebars.compile(this.source);
var self = this;
this.collection.fetch({
success: function () {
self.render();
},
error: function () {
console.log("ERROR IN BooksView");
}
});
},
render: function() {
var collect = JSON.stringify(this.collection);
collect = collect.slice(1, -1);
var html = this.template($.parseJSON(collect));
this.$el.html(html);
}
});
var booksView = new BooksView({ });
$(document).ready(function(){
booksView.$el = $('.e-books-content');
});
A Backbone collection expects an array of models but your JSON provides an object with the array under a books key. Parse the server response to format the data :
var Books = Backbone.Collection.extend({
model: Book,
url: ".list.json",
parse: function(data) {
return data.books;
}
});
Pass your data to your template via http://backbonejs.org/#Collection-toJSON ,
// directly as an array in your template
var html = this.template(this.collection.toJSON());
// under a books key
var html = this.template({
books: this.collection.toJSON()
});
And a demo http://jsfiddle.net/nikoshr/8jdb13jg/

extjs error on filling store

I have a java map. I converted it to json string and I obtain something like this :
{"NEW ZEALAND":"111111111111111","CHAD":"1","MOROCCO":"111","LATVIA":"11"}
Now I want to use it in a store and then a chart like the following code but it's not working. I have no error just no display.
var obj = Ext.Ajax.request({
url: App.rootPath + '/controller/home/dashboard/test.json',
method:'GET',
success: function(response) {
return Ext.JSON.decode(response.responseText);
}
});
var store2 = Ext.create('Ext.data.Store', {
model: 'PopulationPoint',
data: obj
});
Ext.create('Ext.chart.Chart', {
renderTo: 'infos2',
width: 500,
height: 300,
store: store2,
series: [
{
type: 'pie',
field: 'population',
label: {
field: 'state',
display: 'rotate',
font: '12px Arial'
}
}
]
});
The AJAX request is asynchronous. As such, the obj variable used to initialize your data won't contain your data yet.
One option is to create the store2 variable and create the chart directly in the success callback of the AJAX request.
A cleaner option would be to configure the store with a proxy to load the url, and in the callback create the chart.
EDIT
The JSON response does not contain the fields that are declared in your model (sent in the comments). Update the JSON to return a properly formatted model and the chart should work as seen in this fiddle. The JSON should look something like
[
{
"state" : "New Zealand",
"population" : 111111111
},
{
"state" : "Chad",
"population" : 1
}
]

How to create JSON object using jQuery

I have a JSON object in below format:
temp:[
{
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
},
{
test:'test 2',
testData: [
{testName: 'do1',testId:''}
],
testRcd:'value'
}
],
How can i create JSON object in jquery for above format. I want to create a dynamic JSON object.
Just put your data into an Object like this:
var myObject = new Object();
myObject.name = "John";
myObject.age = 12;
myObject.pets = ["cat", "dog"];
Afterwards stringify it via:
var myString = JSON.stringify(myObject);
You don't need jQuery for this. It's pure JS.
A "JSON object" doesn't make sense : JSON is an exchange format based on the structure of Javascript object declaration.
If you want to convert your javascript object to a json string, use JSON.stringify(yourObject);
If you want to create a javascript object, simply do it like this :
var yourObject = {
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
};
I believe he is asking to write the new json to a directory. You will need some Javascript and PHP. So, to piggy back off the other answers:
script.js
var yourObject = {
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
};
var myString = 'newData='+JSON.stringify(yourObject); //converts json to string and prepends the POST variable name
$.ajax({
type: "POST",
url: "buildJson.php", //the name and location of your php file
data: myString, //add the converted json string to a document.
success: function() {alert('sucess');} //just to make sure it got to this point.
});
return false; //prevents the page from reloading. this helps if you want to bind this whole process to a click event.
buildJson.php
<?php
$file = "data.json"; //name and location of json file. if the file doesn't exist, it will be created with this name
$fh = fopen($file, 'a'); //'a' will append the data to the end of the file. there are other arguemnts for fopen that might help you a little more. google 'fopen php'.
$new_data = $_POST["newData"]; //put POST data from ajax request in a variable
fwrite($fh, $new_data); //write the data with fwrite
fclose($fh); //close the dile
?>
How to get append input field value as json like
temp:[
{
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
},
{
test:'test 2',
testData: [
{testName: 'do1',testId:''}
],
testRcd:'value'
}
],
Nested JSON object
var data = {
view:{
type: 'success', note:'Updated successfully',
},
};
You can parse this data.view.type and data.view.note
JSON Object and inside Array
var data = {
view: [
{type: 'success', note:'updated successfully'}
],
};
You can parse this data.view[0].type and data.view[0].note
var model = {"Id": "xx", "Name":"Ravi"};
$.ajax({ url: 'test/set',
type: "POST",
data: model,
success: function (res) {
if (res != null) {
alert("done.");
}
},
error: function (res) {
}
});

jqgrid - can I access server response with onSelectRow?

I get a JSON response from the server that I have full access to using loadComplete. Is it possible to be able to access the JSON response using
onSelectRow?
any other custom function defined outside of loadComplete?
You can define a variable which will hold the last state of the JSON response returned from the server:
var serverData;
$('#list').jqGrid({
datatype: 'json',
// ... other parameters
loadComplete: function (data) {
serverData = data; // or serverData = data.rows
// ...
},
onSelectRow: function (id) {
if (serverData) {
// here you can access serverData, but you need
// here probably find the item in the serverData
// which corresponds the id
}
}
});
If you have JSON data for example from the form
{
"total": "xxx",
"page": "yyy",
"records": "zzz",
"rows" : [
{"id" :"1", "cell": ["cell11", "cell12", "cell13"]},
{"id" :"2", "cell": ["cell21", "cell22", "cell23"]},
...
]
}
then you can save in serverData not the data directly. It could be interesting to save only cell part and save it as the value of the serverData[id]:
var serverData = [];
$('#list').jqGrid({
datatype: 'json',
// ... other parameters
loadComplete: function (data) {
var i, rows = data.rows, l = rows.length, item;
for (i = 0; i < l; i++) {
item = rows[i];
serverData[item.id] = item.cell;
}
// ...
},
onSelectRow: function (id) {
var item = serverData[id]; // the part of data which we need
}
});
If you use repeatitems: false setting in the jsonReader then you can save in the serverData only the part of the items (selected properties) which represented the row of the server data.
In any way you should save the part of the information from data parameter of loadComplete in some variable defined outside of the loadComplete.

Getting Json formatted objects

Ok, so I have a big JSON file that has arrays and objects setup for controls for a google map project I am working on...looks like this:
{
"settings":
{
"DEFAULT_MAP_SETTING": "DEFAULT_MAP_SETTINGS",
"DEFAULT_MAP_RES": "county",
"DEFAULT_MAP_CAT": "popden"
},
"map_settings":
{
"DEFAULT_MAP_SETTINGS":
{
"map_options":
{
"center": [39.828175, -94.5795],
"mapTypeId": "TERRAIN",
"streetViewControl": false,
"scrollwheel": false,
"overviewMapControl": false,
"mapTypeControl": false,
"zoom": 4
},
"map_bounds":
{
"upper-left": [98.70, -127.50],
"lower-right": [48.85, -55.90]
},
}
}
}
My question is how do I go about getting this data in json format as it has to be in json format to load up options and what not in google maps. For instance I have
var myMapOptions = {
"zoom": 4,
"minZoom" : 4,
"scrollWheel" : false,
"center": initialLoc,
"mapTypeId": google.maps.MapTypeId.ROADMAP,
};
var theMap = new google.maps.Map(document.getElementById("map_canvas"), myMapOptions);
Which loads up the google map. But I cant figure out how to set myMapOptions with my big Json file. Every method that I know of returns the json data in strings and gets rid of the formatting. Like $.ajax in jQuery will go get the json for me but it strips it of its formatting.
Can anyone help me out?
jQuery $.ajax() will automatically transform you JSON "file" into a javascript object if your request come back with a JSON header.
However you can override this by using dataType of $.ajax:
$.ajax({
url: "test.html",
dataType: "text",
success: function(data){
alert(data);
}
});
The previous script will alert you JSON file like you want.
[Update]
You can try to use eval():
$.ajax({
url: "test.html",
dataType: "text",
success: function(data){
var options = eval(data);
}
});
In this case your data need to be executable by javascript.
[Update 2]
JsonP style, your json file need to looks like that:
var options = {
"zoom": 4, "minZoom" : 4,
"scrollWheel" : false,
"center": new google.maps.LatLng(39.828175, -94.5795),
"mapTypeId": google.maps.MapTypeId.ROADMAP
};
Notice the "var options ="
Your ajax request need to look like that:
$.ajax({
url: "test.html",
dataType: "text",
success: function(data){
alert(data);// will show your data as text
eval(data); this will execute your "JSON file"
//after eval you can now use options as a variable
alert(options);
}
});