Looping through JSON Data for Google Maps - javascript

I'm trying to access data in this JSON (see below) file such as type, properties, etc. using:
data = new google.maps.Data();
var json = data.loadGeoJson('insert-url-here');
for (var i=0; i < json.length; i++) {
var obj = json[i];
console.log(obj.coordinates);
}
I get an error on the first line of the for loop Cannot read property 'length' of undefined. I want to zoom into the object by reading its coordinates value.
google.maps.addListener(data, 'click', function () {
obj.setZoom(10);
}
What am I doing wrong?
JSON sample:
"features": [{ "type": "Feature", "properties": { "id": 18, "geometry": { "type": "Point", "coordinates": [ -34.397, 150.644 ] }

To actually retrieve the coordinates property you need to do this:
var json = {"features": [{ "type": "Feature", "properties": { "id": 18, "geometry": { "type": "Point", "coordinates": [ -34.397, 150.644 ]}}}]}
document.write(json.features[0].properties.geometry.coordinates);
How is this JSON build
object
- property -> features (Array, length: 1)
[ Object
- property -> properties (Object)
- property -> geometry (Object)
- property -> coordinates (Array, length: 2)
]

var json = data.loadGeoJson('insert-url-here');
the json variable here is returning as a undefined object causing the error. Also better use another variable name
whenever you get the json returned, you can use something like eval() to return a javascript object. so that you can access coordinates using json.features[0].properties.coordinates
features here is an array so you need to go through them

Related

How to obtain a reference to a dynamically generated (unknown named) child element in json [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 months ago.
I have a json in the format:
"json": {
"schema": {
"type": "object",
"title": "My Table",
"properties": {
"table-1659555454697": {
"type": "array",
"items": {
"type": "object",
"properties": {
"inputTest": {
"type": "string"
},
"columnTwo": {
"type": "string"
}
},
"required": [
"inputTest",
"columnTwo"
]
}
}
},
},
I can obtain a reference to the "table-1659555454697" object with:
console.log(this.jsf.schema.properties);
What I'm struggling with is how to obtain a reference from that element's children to the "required" array's length. Assuming I cannot reference "table-1659555454697" by name since its dynamically generated.
I've tried:
console.log(this.jsf.schema.properties[0].items[0].required.length);
But I get undefined error
You probably want Object.keys, Object.values, or Object.entries. They provide an array of, respectively, the object's keys, the object's values, and the object's key-value pairs (as an array of [key, value] arrays).
const propertyNames = Object.keys(json.schema.properties) // ["table-1659555454697"]
const propertyValues = Object.values(json.schema.properties) // [{ type: "array", items: { ... }]
const propertyEntries = Object.entries(json.schema.properties)
// [ ["table-1659555454697", [{ type: "array", items: { ... }] ]
So we could do what you want like this:
const requiredLength = Object.values(json.schema.properties)[0].items.required.length
You can reference table-1659555454697 by doing
Object.keys(this.jsf.schema.properties)[0]

Google Maps - addGeoJson is not working for my file

addGeoJson is not working in google map for my file
please check below code that I am using in javascript
//create the map
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 6,
center: {lat:49.79, lng: -8.82}
});
// Load GeoJSON.
var promise = $.getJSON("Sensitive_Areas_Nitrates_Rivers.json"); //same as map.data.loadGeoJson();
promise.then(function(data){
cachedGeoJson = data; //save the geojson in case we want to update its values
console.log(cachedGeoJson);
map.data.addGeoJson(cachedGeoJson,{idPropertyName:"id"});
});
I have downloaded this file from here
you can check my JSON file
Sensitive_Areas_Nitrates_Rivers.json
also, you can check this link with polygon
I have used below JSON format so you can check it
{
"type": "FeatureCollection",
"crs": {
"type": "name",
"properties": {
"name": "EPSG:27700"
}
},
"features": [
{
"type": "Feature",
"id": 1,
"geometry": {
"type": "MultiLineString",
"coordinates": [
[
[
500051.6875,
224280.03130000085
],
[
500047.2812999999,
224277.6875
],
[
499977.5937999999,
224242.625
],
[
499976.6875,
224242.21880000085
]
]
]
},
"properties": {
"OBJECTID": 8,
"type_of_sa": "SA_N",
"datedesign": 1025136000000,
"name": "Rivers Itchen",
"length_km": 12,
"uwwtd_code": "UKENRI134",
"shape_Length": 12172.080443901654
}
}
]
}
[500051.6875, 224280.03130000085] - [X, Y] coordinates may be in EPSG: 27700 to EPSG:4326, Now we need to display these coordinates on google map, Is there any solution for this?
Since Google Maps expects GeoJSON to be in EPSG:4326, Sensitive_Areas_Nitrates_Rivers.json needs to be reprojected. QGIS, for instance, could be utilized for that matter (refer docs for a details)
Reprojected Sensitive_Areas_Nitrates_Rivers.json layer will be displayed like this:
You are getting coordinates in metres. For displaying in google map you need to convert it into [Lng, Lat].
For converting metres to [Lng, Lat] you need to change the projection from EPSG: 27700 to 4326
then only you are able to get this geojson in [Lng, Lat]
Tool you can use: QGIS Desktop 3.4.14
Link: https://qgis.org/en/site/forusers/download.html
After convert you need to export this file as feature.

Filter Json with javascript

I'm trying to create a function that takes a date as argument that will display the data only. This is to map it with leaflet.
The time series data looks like this:
(it's in JSON)
Time - DetectorID
0 - 5
1 - 3
2 - 4
and the geoJson that the data is mapped against is as follows:
var myGeojsonData =
{
"features": [
{
"geometry": {
"coordinates": [
144.829434,
-37.825233
],
"type": "Point"
},
"properties": {
"Area": "Combined Entry MVT on Grieve Pde, West Gate Fwy North Ramps, Grieve Pde Byp Start EB between Grieve ",
"IDnumber": "DetectorID"
},
"type": "Feature"
},...etc
I am trying to take the data from the time series with the following javascript code.
function selectdata(Time,timeseriesdata) {
output = timeseries.Time["(Time)"]
return output(time)
}
I used the pandas function to transform this to Json from a dataframe.

Iterating over an array of objects?

Here is some sample data that I get from an API:
{
"Document": {
"Placemark": [
{
"name": " V5-MJW",
"address": "Aviation Road, Windhoek, Namibia",
"description": [],
"TimeStamp": {
"when": "2016-05-21T06:12:00-04:00"
},
"styleUrl": "#asset7541",
"Point": {
"coordinates": "17.0829055,-22.598271,743"
}
},
{
"name": "GSatMicro80149",
"address": "Unnamed Road, Lesotho",
"description": [],
"TimeStamp": {
"when": "2016-05-11T04:52:00-04:00"
},
"styleUrl": "#asset7543",
"Point": {
"coordinates": "27.5594894,-29.456703,1659"
}
}
]
}
}
This is my current code that is creating an array:
var flightPlanCoordinates = [];
//data being the returned values from the API.
$.each(data.Document.Placemark, function () {
var location = this.Point.coordinates.split(',');
var loc = {lat: parseFloat(location[1]), lng: parseFloat(location[0])};
flightPlanCoordinates[this.name] == null ? flightPlanCoordinates[this.name] = [] : flightPlanCoordinates[this.name].push(loc);
});
I get a lot of placemarks with the same name, I want to split each placemark with a different name into a different array.
This all works fine until I try to itterate over flightPlanCoordinates, I tried the following:
$.each(flightPlanCoordinates, function(index) {
}
But this does not work, If I log the length of flightPlanCoordinates, it results in 0, yet in Firefox Dev tools I can see the correct values inside of flightPlanCoordinates.
How would I go about doing this? Is there a better way than what I am doing here?
Please change
var flightPlanCoordinates = [];
to
var flightPlanCoordinates = {};
it should be an object, because you set it with properties like flightPlanCoordinates[this.name], where this.name is a string, not an index.

Convert Javascript response to Array/Map

I have the following response from a Javascript ElasticSearch Query, and i need to map it to the below structure. Is there a more efficient way to do this than what I am currently doing?
Thanks
Structure I need to map to: (about 700 of these)
[{
"coordinates": ["48", "37"],
"name": "something",
"population": "501"
},
Current structure of my data being returned:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
0: Object
_id: "4"
_index: "locationIndex"
_score: 1
_source: Object
coordinates: Array[2]
0: -77.080597
1: 38.892899
length: 2
__proto__: Array[0]
name: "someName"
population: 57205
1: Object
...
What I'm trying but fails:
var results= [{
"key": 'coordinates',
resp.coordiantes[0],
resp.coordinates[1],
"key": 'name',
resp.name
})
}];
Assuming that your data is stored inside a myData variable, you can use the Array.prototype.map method to manipulate it and achieve what you want. Here's a solution:
result = myData.map(function(obj) {
return {
coordinates: obj._source.coordinates,
name: obj.name,
population: obj.population
}
});
Simple as this! The result will be something like this:
[
{
"coordinates": [-77.080597, 38.892899],
"name": "some name",
"population": 52701
},
{
"coordinates": [-54.930299, 30.992833],
"name": "some name 2",
"population": 84229
},
{
"coordinates": [-82.001438, -5.38131],
"name": "some name 3",
"population": 5991
} //, ...
]
It looks like you don't quite understand Object syntax in Javascript; in order for my answer to make the most sense, you may wish to read up a little on them.
Now that you understand Objects more, it should become quite clear that what you want looks something like:
var results = [];
for (var i = 0, len = data.length; i < len; i++)
{
var resp = data[i];
results.push({
'coordinates':resp['source']['coordinates'],
'name':resp.name,
'population':resp.population
});
}
For bonus points, you could include a JS framework like jQuery and just uase a map function.
I like Marcos map solution the most but also possible and quick is to use Array.from(data). This helped me in the past to convert the response API data that should be an array but wasn't yet.
I am the author of the open source project http://www.jinqJs.com.
You can easily do something like this to do what you want.
var result = jinqJs().from(data5).select(function(row){
return {coordinates: [row.coordinates[0]['0'], row.coordinates[0]['1']],
name: row.name,
population: row.population
}
});

Categories