i have geojson data:
{
"type":"FeatureCollection",
"metadata":{
"generated":1417015873000,
11-26T14:33:40&endtime=2014-11-26T14:33:45",
"title":"USGS Earthquakes",
"status":200,
"api":"1.0.13",
"count":1
},
"features":
[{
"type":"Feature",
"properties":
{
"mag":6.8,
"place":"160km NW of Kota Ternate, Indonesia",
"time":1417012423350,"updated":1417015584000,
"tz":480,
"url":"http://comcat.cr.usgs.gov/earthquakes/eventpage/usb000t08w",
"detail":"http://comcat.cr.usgs.gov/fdsnws/event/1/query?eventid=usb000t08w&format=geojson",
"felt":1,
"cdi":5,
"mmi":4.98,
"alert":"green",
"status":"reviewed",
"tsunami":1,
"sig":712,
"net":"us",
"code":"b000t08w",
"ids":",at00nfnhsd,pt14330000,usb000t08w,",
"sources":",at,pt,us,",
"types":",cap,dyfi,general-link,geoserve,impact-link,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,",
"nst":null,
"dmin":1.45,
"rms":1.32,
"gap":37,
"magType":"mwb",
"type":"earthquake",
"title":"M 6.8 - 160km NW of Kota Ternate, Indonesia"
},
"geometry":{"type":"Point","coordinates":[126.5456,1.9752,41.06]},
"id":"usb000t08w"
}]
}
how to parse value "title" ?
var geojson = JSON.parse(geojson_data);
Turns the geojson string into an object, from there you can get whatever you values you want from it.
Edit: your json is invalid, where are you getting the data from? I cleaned it up, so you can call JSON.parse on it. However, it is not valid geojson, so I'd double check where you come up with the data. This geojson validator might help.
{
"metadata": {
"generated": 1417015873000,
"11-26T14: 33: 40&endtime=2014-11-26T14: 33": 45,
"title": "USGSEarthquakes",
"status": 200,
"api": "1.0.13",
"count": 1
},
"features": [
{
"type": "Feature",
"properties": {
"mag": 6.8,
"place": "160km NW of Kota Ternate, Indonesia",
"time": 1417012423350,
"updated": 1417015584000,
"tz": 480,
"url": "http://comcat.cr.usgs.gov/earthquakes/eventpage/usb000t08w",
"detail": "http://comcat.cr.usgs.gov/fdsnws/event/1/query?eventid=usb000t08w&format=geojson",
"felt": 1,
"cdi": 5,
"mmi": 4.98,
"alert": "green",
"status": "reviewed",
"tsunami": 1,
"sig": 712,
"net": "us",
"code": "b000t08w",
"ids": ",at00nfnhsd,pt14330000,usb000t08w,",
"sources": ",at,pt,us,",
"types": ",cap,dyfi,general-link,geoserve,impact-link,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,",
"nst": null,
"dmin": 1.45,
"rms": 1.32,
"gap": 37,
"magType": "mwb",
"type": "earthquake",
"title": "M 6.8 - 160km NW of Kota Ternate, Indonesia"
},
"geometry": {
"type": "Point",
"coordinates": [
126.5456,
1.9752,
41.06
]
},
"id": "usb000t08w"
}
]
}
Related
I get route between 2 Point :
{
"routes": [
{
"overview_polyline": {
"points": "m{f~D}_ygHp#wAJs#Is#eAsBGk#Hg#"
},
"legs": [
{
"summary": "میدان انقلاب - انقلاب",
"distance": {
"value": 209.0,
"text": "۲۲۵ متر"
},
"duration": {
"value": 13.0,
"text": "کمتر از ۱ دقیقه"
},
"steps": [
{
"name": "بزرگراه اهواز-حمیدیه",
"instruction": "در جهت شرق در بزرگراه اهواز-حمیدیه قرار بگیرید",
"bearing_after": 119,
"type": "depart",
"distance": {
"value": 25.0,
"text": "۲۵ متر"
},
"duration": {
"value": 1.0,
"text": "کمتر از ۱ دقیقه"
},
"polyline": "m{f~D}_ygHTm#",
"start_location": [
48.629912,
31.333827
]
},
{
"name": "انقلاب",
"instruction": "در میدان انقلاب، از خروجی دوم، خارج شوید",
"rotaryName": "میدان انقلاب",
"bearing_after": 126,
"type": "rotary",
"modifier": "straight",
"exit": 2,
"distance": {
"value": 101.0,
"text": "۱۲۵ متر"
},
"duration": {
"value": 5.0,
"text": "کمتر از ۱ دقیقه"
},
"polyline": "wzf~DkaygHNWJQJs#Is#Yk#",
"start_location": [
48.630143,
31.333717
]
},
{
"name": "",
"instruction": "به مسیر خود ادامه دهید",
"bearing_after": 53,
"type": "exit rotary",
"modifier": "straight",
"exit": 2,
"distance": {
"value": 83.0,
"text": "۱۰۰ متر"
},
"duration": {
"value": 8.0,
"text": "کمتر از ۱ دقیقه"
},
"polyline": "szf~DigygHk#gAGk#Hg#",
"start_location": [
48.631088,
31.333703
]
},
{
"name": "انقلاب",
"instruction": "در مقصد قرار دارید",
"bearing_after": 0,
"type": "arrive",
"distance": {
"value": 0.0,
"text": ""
},
"duration": {
"value": 0.0,
"text": ""
},
"polyline": "}{f~DelygH",
"start_location": [
48.631869,
31.333913
]
}
]
}
]
}
]
}
In Steps we have 4 points:
[31.333827,48.629912 ],
[31.333717,48.630143 ],
[31.333703,48.631088],
[31.333913,48.631869 ]
When I use polyline my output is like below picture. But real Path is another thing.
I use Leaflet and get my .png file for map from another server and get Json String from another server.
How can Manage this?
A Map Matching API should solve your problem.
Google Snap to Roads API
Mapbox Map Matching API
There also seems to be some open source alternatives like the Valhalla Map Matching API
What was the original directions API request? Curious to see why you're getting that result for that route
I am looking to sort a GeoJSON file on a property so I can then slice it keeping only the top 5 features. So for example I wish to take this GeoJSON and sort the file in descending order by the incidents property:
...
[
-75.1972382872565,
39.9294288475177
]
]
]
]
},
"properties": {
"area": "",
"location": "24th St. & Wolf St.",
"perimeter": "81903.64182498",
"dist_numc": "01",
"sum_area": "",
"area_sqmi": "216350124.153",
"district_i": "",
"objectid": "321",
"globalid": "c040618c-ac93-4b22-b174-0ea08e0f805d",
"district_": "1",
"_feature_id": "1",
"_feature_id_string": "Police_Districts.1",
"dist_num": "1",
"div_code": "SPD",
"phone": "686-3010",
"incidents": 11553
}
},
...
I'm looking to basically rearrange the order of the features array so that it's in descending order and the highest incident features are first.
How would I go about this? I am used to creating a compare function and then sorting an array with something like this:
//FUNCTION: SORT
export const compare = ( a, b ) => {
if ( a.incidents < b.incidents ){
return -1;
}
if ( a.incidents > b.incidents ){
return 1;
}
return 0;
}
But in this case I need to sort a JSON and only sort an array inside of it so I am unsure how to proceed.
I set up an example where i attempt to sort via a button click but doesn't seem to be working:
https://codesandbox.io/s/slicing-geojson-qg1hb?file=/src/App.js
Consider this file as JSON. To do that, I've copied the first three data from that geojson file and store into a variable called data. So we need to sort that array according to the incidents property. Now execute javascript's sort() function to data.features. Since your data is big and you're sorting the data according to the incidents property, make sure to print only incidents property to see whether your data is being sorted or not. As StackOverflow asks limited characters(30000) in this section, I'm going to keep only the first three coordinates from every geometry property. Have a look at the snippet below:
var data = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[
-75.0544420852857,
40.044532749252
],
[
-75.054816199384,
40.0441717116827
],
[
-75.0551367855513,
40.0438732632911
],
]
]
]
},
"properties": {
"area": "",
"location": "Harbison Ave. & Levick St.",
"perimeter": "63587.3693993",
"dist_numc": "02",
"sum_area": "",
"area_sqmi": "192346097.032",
"district_i": "",
"objectid": "322",
"globalid": "95200c4a-2617-47c2-93f1-07d6359a92e9",
"district_": "2",
"_feature_id": "2",
"_feature_id_string": "Police_Districts.2",
"dist_num": "2",
"div_code": "NEPD",
"phone": "686-3020",
"incidents": 32340
}
}
,
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[
-75.1972382872565,
39.9294288475177
],
[
-75.1969248893574,
39.9291749499585
],
[
-75.1966534158686,
39.9293232425744
],
]
]
]
},
"properties": {
"area": "",
"location": "24th St. & Wolf St.",
"perimeter": "81903.64182498",
"dist_numc": "01",
"sum_area": "",
"area_sqmi": "216350124.153",
"district_i": "",
"objectid": "321",
"globalid": "c040618c-ac93-4b22-b174-0ea08e0f805d",
"district_": "1",
"_feature_id": "1",
"_feature_id_string": "Police_Districts.1",
"dist_num": "1",
"div_code": "SPD",
"phone": "686-3010",
"incidents": 11553
}
},
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[
-75.1343640909741,
39.9529315410666
],
[
-75.1352375679666,
39.9506957263754
],
[
-75.1352409996735,
39.9506869425429
]
]
]
]
},
"properties": {
"area": "",
"location": "11th St. & Winter St.",
"perimeter": "34655.32085552",
"dist_numc": "06",
"sum_area": "",
"area_sqmi": "69279267.8986235",
"district_i": "",
"objectid": "325",
"globalid": "e0afa680-ecd3-470e-b0f8-59b70d4f72b5",
"district_": "6",
"_feature_id": "5",
"_feature_id_string": "Police_Districts.5",
"dist_num": "6",
"div_code": "CPD",
"phone": "686-3060",
"incidents": 23428
}
}
]
};
console.log("Before sorting");
console.log(data.features[0].properties.incidents);
console.log(data.features[1].properties.incidents);
console.log(data.features[2].properties.incidents);
data.features.sort(function (a, b) {
if (a.properties.incidents < b.properties.incidents)
return -1;
else if (a.properties.incidents > b.properties.incidents)
return 1;
});
console.log("After sorting");
console.log(data.features[0].properties.incidents);
console.log(data.features[1].properties.incidents);
console.log(data.features[2].properties.incidents);
I know this has been asked a lot, but I just can't help myself, because the my JSON has some weird format in my opinion.
Im calling the bing api you can see below and it reports a JSON like this:
{
"authenticationResultCode": "ValidCredentials",
"brandLogoUri": "http:dev.virtualearth.netBrandinglogo_powered_by.png",
"copyright": "Copyright © 2020 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
"resourceSets": [
{
"estimatedTotal": 44,
"resources": [
{
"__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
"point": {
"type": "Point",
"coordinates": [
48.12575,
11.50249
]
},
"description": "Bei München-Laim - Stockender Verkehr;; vorsichtig an das Stauende heranfahren.",
"end": "Date(1581665178000)",
"incidentId": 1717453254024927000,
"lastModified": "Date(1581643942010)",
"roadClosed": false,
"severity": 2,
"source": 9,
"start": "Date(1581061714000)",
"toPoint": {
"type": "Point",
"coordinates": [
48.12562,
11.5046
]
},
"type": 2,
"verified": true
},
{
"__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
"point": {
"type": "Point",
"coordinates": [
48.10819,
11.61907
]
},
"description": "Bei Woferlstraße - Bauarbeiten auf Abschnitt.",
"end": "Date(1581974827000)",
"incidentId": 4267251995514645000,
"lastModified": "Date(1581637098936)",
"roadClosed": false,
"severity": 2,
"source": 9,
"start": "Date(1581629269000)",
"toPoint": {
"type": "Point",
"coordinates": [
48.10819,
11.61907
]
},
"type": 9,
"verified": true
},
{
"__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
"point": {
"type": "Point",
"coordinates": [
48.14469,
11.55741
]
},
"description": "Zwischen Karlstraße und Hirtenstraße - Bauarbeiten auf Abschnitt.",
"end": "Date(1585778340000)",
"incidentId": 3021451548046648000,
"lastModified": "Date(1581637098936)",
"roadClosed": false,
"severity": 2,
"source": 9,
"start": "Date(1581629270000)",
"toPoint": {
"type": "Point",
"coordinates": [
48.14314,
11.55658
]
},
"type": 9,
"verified": true
},
{
"__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
"point": {
"type": "Point",
"coordinates": [
48.14314,
11.58826
]
},
"description": "Bei Franz-Josef-Strauß-Ring - Baustelle.",
"end": "Date(1609369140000)",
"incidentId": 337182766905069500,
"lastModified": "Date(1581637098936)",
"roadClosed": false,
"severity": 2,
"source": 9,
"start": "Date(1581629314000)",
"toPoint": {
"type": "Point",
"coordinates": [
48.14423,
11.58316
]
},
"type": 9,
"verified": true
},
{
"__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
"point": {
"type": "Point",
"coordinates": [
48.141,
11.5613
]
},
"description": "Bei Karlsplatz - Bauarbeiten auf Abschnitt. Fahrbahn von auf einen Fahrstreifen verengt.",
"end": "Date(1581974827000)",
"incidentId": 1310817648090719700,
"lastModified": "Date(1581637098936)",
"roadClosed": false,
"severity": 2,
"source": 9,
"start": "Date(1581629270000)",
"toPoint": {
"type": "Point",
"coordinates": [
48.14186,
11.56163
]
},
"type": 9,
"verified": true
}
]
}
]
}
I just can't help myself to get only the description part into a simple html table.
the following is what i tried by now.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script>
$.getJSON("http://dev.virtualearth.net/REST/v1/Traffic/Incidents/48.052165,11.722993,48.222626,11.391344?key=BINGKEY").then(function(data)
{console.log(data);
var tr = data
for (var i = 0; i < data.resourceSets.estimatedTotal; i++) {
var tr = $('<tr/>');
// Indexing into data.report for each td element
$(tr).append("<td>" + data.resourceSets.resources[i].description + "</td>");
$('.table1').append(tr);
}
});
</script>
<table class="table1">
<tr>
<th>description</th>
</tr>
</table>
</body>
</html>
maybe someone can help me with my problem.
Thanks
resourceSets is collection in json and you are trying to access it as normal property.
for(var s = 0; s < data.resourceSets.length; s++) {
for (var i = 0; i < data.resourceSets[s].resources.length; i++) {
var tr = $('<tr/>');
// Indexing into data.report for each td element
$(tr).append("<td>" + data.resourceSets[s].resources[i].description + "</td>");
$('.table1').append(tr);
}
}
Side but related note: estimatedTotal is 44, but in the json that is posted, has only 5 resources. Are you sure you want to iterate 44 times? if yes, you need to watch array index out of range exception.
I would declare an iterable list of fields and then dynamically loop-over the resources.
[ 'description', 'severity', 'point.coordinates[0]', 'point.coordinates[1]' ]
Note: You can append multiple items by mapping as seen below.
Update: You can resolve nested fields by implementing a recursive function as seen below.
Instead of this:
return $('<td>').text(resource[field]);
You can use this:
return $('<td>').text(resolveField(resource, field));
Warning: It's not fool-proof, because it fails at multiple nested arrays e.g. foo[0][0].
Demo
let fields = [ 'description', 'severity', 'point.coordinates[0]', 'point.coordinates[1]' ];
let data = getData();
$('.table-1 tbody').append(data.resourceSets.flatMap(resourceSet => {
return resourceSet.resources.map(resource => {
return $('<tr>').append(fields.map(field => {
return $('<td>').text(resolveField(resource, field));
}));
});
}));
// Adapted from: https://stackoverflow.com/a/19156197/1762224
function resolveField(obj, prop) {
return prop.match(/[^\]\[.]+/g)
.map(token => {
return Number.isInteger(token)
? parseInt(token, 10)
: token.replace(/^['"](.+(?=['"]$))['"]$/, '$1');
})
.reduce((ref, curr) => {
if (ref != null) {
if (Array.isArray(ref)) {
return ref[curr];
} else if (typeof ref === 'object') {
if (ref.hasOwnProperty(curr)) {
return ref[curr];
}
}
}
return null;
}, obj);
}
function getData() {
return {
"authenticationResultCode": "ValidCredentials",
"brandLogoUri": "http:dev.virtualearth.netBrandinglogo_powered_by.png",
"copyright": "Copyright © 2020 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
"resourceSets": [{
"estimatedTotal": 44,
"resources": [{
"__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
"point": {
"type": "Point",
"coordinates": [
48.12575,
11.50249
]
},
"description": "Bei München-Laim - Stockender Verkehr;; vorsichtig an das Stauende heranfahren.",
"end": "Date(1581665178000)",
"incidentId": 1717453254024927000,
"lastModified": "Date(1581643942010)",
"roadClosed": false,
"severity": 2,
"source": 9,
"start": "Date(1581061714000)",
"toPoint": {
"type": "Point",
"coordinates": [
48.12562,
11.5046
]
},
"type": 2,
"verified": true
},
{
"__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
"point": {
"type": "Point",
"coordinates": [
48.10819,
11.61907
]
},
"description": "Bei Woferlstraße - Bauarbeiten auf Abschnitt.",
"end": "Date(1581974827000)",
"incidentId": 4267251995514645000,
"lastModified": "Date(1581637098936)",
"roadClosed": false,
"severity": 2,
"source": 9,
"start": "Date(1581629269000)",
"toPoint": {
"type": "Point",
"coordinates": [
48.10819,
11.61907
]
},
"type": 9,
"verified": true
},
{
"__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
"point": {
"type": "Point",
"coordinates": [
48.14469,
11.55741
]
},
"description": "Zwischen Karlstraße und Hirtenstraße - Bauarbeiten auf Abschnitt.",
"end": "Date(1585778340000)",
"incidentId": 3021451548046648000,
"lastModified": "Date(1581637098936)",
"roadClosed": false,
"severity": 2,
"source": 9,
"start": "Date(1581629270000)",
"toPoint": {
"type": "Point",
"coordinates": [
48.14314,
11.55658
]
},
"type": 9,
"verified": true
},
{
"__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
"point": {
"type": "Point",
"coordinates": [
48.14314,
11.58826
]
},
"description": "Bei Franz-Josef-Strauß-Ring - Baustelle.",
"end": "Date(1609369140000)",
"incidentId": 337182766905069500,
"lastModified": "Date(1581637098936)",
"roadClosed": false,
"severity": 2,
"source": 9,
"start": "Date(1581629314000)",
"toPoint": {
"type": "Point",
"coordinates": [
48.14423,
11.58316
]
},
"type": 9,
"verified": true
},
{
"__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
"point": {
"type": "Point",
"coordinates": [
48.141,
11.5613
]
},
"description": "Bei Karlsplatz - Bauarbeiten auf Abschnitt. Fahrbahn von auf einen Fahrstreifen verengt.",
"end": "Date(1581974827000)",
"incidentId": 1310817648090719700,
"lastModified": "Date(1581637098936)",
"roadClosed": false,
"severity": 2,
"source": 9,
"start": "Date(1581629270000)",
"toPoint": {
"type": "Point",
"coordinates": [
48.14186,
11.56163
]
},
"type": 9,
"verified": true
}
]
}]
};
}
table { border-collapse: collapse; }
table, th, td { border: thin solid #AA5555; }
th, td { padding: 0.25em; }
thead tr { background: #EE8888; }
tbody tr:nth-child(even) { background: #EECCCC; }
tbody tr:nth-child(odd) { background: #FFEEEE; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table-1">
<thead>
<tr>
<th>Description</th>
<th>Severity</th>
<th>Lat</th>
<th>Lon</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Here is a test suite for the resolveField function:
let foo1 = { bar : 10 };
let foo2 = { bar : { baz : [ 1, 2 ] } };
let foo3 = { bar : [ { baz : 1 }, { baz : 2 } ] };
console.log(resolveField(foo1, 'bar') === 10);
console.log(resolveField(foo2, 'bar.baz[0]') === 1);
console.log(resolveField(foo3, 'bar[1].baz') === 2);
It is very hard to parse json in javascript and display that data in html.Handlebars is the option to your solution.The dynamic data produced from the API can be easily embedded using handlebars.Refer the site below for more information.Hope this helps.
Introduction to Handlebars.js
I have a mapbox source composed by a list of geojson point, each element of this source has a key icon referring to an icon URL:
var featureCollection = {
"type": "FeatureCollection",
"features": [
{
"geometry":{
"type": "Point",
"coordinates": [1,1]
},
"properties": {
"id": 1,
"name": "name1",
"address": "address1",
"icon": "icon1"
}
},
{
"geometry":{
"type": "Point",
"coordinates": [2,2]
},
"properties": {
"id": 2,
"name": "name2",
"address": "address2",
"icon": "icon2"
}
},
{
"geometry":{
"type": "Point",
"coordinates": [3,3]
},
"properties": {
"id": 3,
"name": "name3",
"address": "address3",
"icon": "icon3"
}
},
{
"geometry":{
"type": "Point",
"coordinates": [4,4]
},
"properties": {
"id": 4,
"name": "name4",
"address": "address4",
"icon": "icon1"
}
}
]
}
map.addSource("shops", {
type: "geojson",
data: featureCollection,
cluster: true,
clusterMaxZoom: 14,
clusterRadius: 50
});
I'd like to plot my features by representing them by their icon variable, a way to do so would be to add as many layers as I have different icons:
map.addLayer({
id: currentLayer,
type: "symbol",
source: "featureCollection",
filter: ["!has", "point_count"],
"layout": {
"icon-image": currentIcon,
"icon-size":1.5
}
});
The thing is I have more than 200 different icons (out of 800 observations), and I really doubt creating 200 different layers is the most effective way to plot my observations. Especially when I'm triggering a function when the user clicks on an layer, so I would also have to define such function as many times as I have different icons.
You can and should create just one layer. icon-image supports data driven styles so you can use "icon-image": "{icon}".
http://jsbin.com/yofiwizuca/1/edit?html,output
This of course assumes you have icons in your Style named icon1, icon2',icon3based on the values of theicon` properties in your GeoJSON.
You could also use https://www.mapbox.com/mapbox-gl-js/style-spec#expressions if you need to manipulate the values.
I'm parsing JSON response from the MapQuest API. I need all of the 'narratives' from the 'legs' node under 'maneuvers' (legs-> maneuvers -> get all narratives), but I cannot figure it out.
I can get most of the values like so:
$(function(){
var mq = jQuery.parseJSON(jsonResponse);
$("#fuel").html(mq.renderMatrixResults[0].route.fuelUsed);
$("#rtime").html(mq.renderMatrixResults[0].route.realTime);
});
Part of JSON response:
{
"renderMatrixResults": [
{
"route": {
"hasTollRoad": true,
"computedWaypoints": [
],
"fuelUsed": 2.24,
"hasUnpaved": false,
"hasHighway": true,
"realTime": 5556,
"boundingBox": {
"ul": {
"lng": -74.240074,
"lat": 40.662548
},
"lr": {
"lng": -74.132072,
"lat": 40.573451
}
},
"distance": 38.998,
"time": 5523,
"hasSeasonalClosure": false,
"locations": [
{
"latLng": {
"lng": -74.18862,
"lat": 40.609712
},
"adminArea4": "Brooklyn",
"adminArea5Type": "City",
"adminArea4Type": "County",
"adminArea5": "Brooklyn",
"street": "1234 Test Lane",
"adminArea1": "US",
"adminArea3": "NY",
"type": "s",
"displayLatLng": {
"lng": -74.188621,
"lat": 40.60971
},
"linkId": 33589148,
"postalCode": "10001-6992",
"sideOfStreet": "L",
"dragPoint": false,
"adminArea1Type": "Country",
"geocodeQuality": "POINT",
"geocodeQualityCode": "P1AAA",
"adminArea3Type": "State"
},
{
"latLng": {
"lng": -74.194858,
"lat": 40.601623
},
"adminArea4": "Brooklyn",
"adminArea5Type": "City",
"adminArea4Type": "County",
"adminArea5": "Brooklyn",
"street": "5678 Example Street",
"adminArea1": "US",
"adminArea3": "NY",
"type": "s",
"displayLatLng": {
"lng": -74.194854,
"lat": 40.601623
},
"linkId": 33361764,
"postalCode": "10001-5483",
"sideOfStreet": "R",
"dragPoint": false,
"adminArea1Type": "Country",
"geocodeQuality": "POINT",
"geocodeQualityCode": "P1AAA",
"adminArea3Type": "State"
}
],
"hasCountryCross": false,
"legs": [
{
"hasTollRoad": false,
"index": 0,
"roadGradeStrategy": [
[
]
],
"hasHighway": false,
"hasUnpaved": false,
"distance": 0.882,
"time": 145,
"origIndex": 1,
"hasSeasonalClosure": false,
"origNarrative": "Go west on some road",
"hasCountryCross": false,
"formattedTime": "00:02:25",
"destNarrative": "Proceed to 789 GIRAFFE STREET",
"destIndex": 1,
"maneuvers": [
{
"signs": [
],
"index": 0,
"maneuverNotes": [
],
"direction": 4,
"narrative": "Start out going south on Elephant Avenue.",
"iconUrl": "https://content.mapquest.com/mqsite/turnsigns/icon-dirs-start_sm.gif",
"distance": 0.57,
"time": 79,
"linkIds": [
],
"streets": [
"Elephant Avenue"
],
"attributes": 0,
"transportMode": "AUTO",
"formattedTime": "00:01:19",
"directionName": "South",
"mapUrl": "https://www.mapquestapi.com/staticmap/v4/getmap?key=Fmjtd|luur20uanq,b0=o5-9ayxdw&type=map&size=225,160&pois=purple-1,40.60971,-74.188621,0,0|purple-2,40.602351999999996,-74.189582,0,0|�er=40.606031,-74.18910149999999&zoom=10&rand=-1416511403&session=53c1fb45-030d-0004-02b7-16b5-00163e4c0d3f",
"startPoint": {
"lng": -74.188621,
"lat": 40.60971
},
"turnType": 2
},
{
"signs": [
],
"index": 1,
"maneuverNotes": [
],
"direction": 7,
"narrative": "Turn right onto Tiger Blvd.",
"iconUrl": "https://content.mapquest.com/mqsite/turnsigns/rs_right_sm.gif",
"distance": 0.269,
"time": 56,
"linkIds": [
],
"streets": [
"Tiger Blvd"
],
"attributes": 0,
"transportMode": "AUTO",
"formattedTime": "00:00:56",
"directionName": "West",
"mapUrl": "https://www.mapquestapi.com/staticmap/v4/getmap?key=Fmjtd|luur20uanq,b0=o5-9ayxdw&type=map&size=225,160&pois=purple-2,40.602351999999996,-74.189582,0,0|purple-3,40.601127,-74.194366,0,0|�er=40.601739499999994,-74.191974&zoom=12&rand=-1416511403&session=53c1fb45-030d-0004-02b7-16b5-00163e4c0d3f",
"startPoint": {
"lng": -74.189582,
"lat": 40.602352
},
"turnType": 2
}
Haven't tested it but here is the idea. You can use a function that will traverse object tree and collect items specified by a path.
function getPath(path, obj) {
var name, value;
path = path instanceof Array ? path: path.split('.'); //convert path to array
name = path.shift(); //get the first name
value = obj[name]; //extract value
if(!path.length || value == null) { //last name or value is null or undefined
return value;
}
if(value instanceof Array) { //if value is array - concat
return [].concat.apply([], value.map(function(item){
return getPath(path.slice(0), item);
}));
}
return getPath(path, value); //else go deeper
}
Usage:
var narratives
= getPath('renderMatrixResults.route.legs.maneuvers.narrative', mq);
I believe the path is correct.