I need to convert a JSON response from Mapquest elevation API into a GeoJSON layer in my Leaflet map.
var ele = $.getJSON('http://open.mapquestapi.com/elevation/v1/profile?key=<API_KEY>&shapeFormat=raw&latLngCollection='+profile);
this is a sample of JSON reponse:
{
"shapePoints":[
39.74012,
-104.9849,
39.7995,
-105.7237,
39.6404,
-106.3736
],
"elevationProfile":[
{
"distance":0,
"height":1616
},
{
"distance":63.5583,
"height":3910
},
{
"distance":121.9561,
"height":2501
}
],
"info":{
"copyright":{
"text":"© 2018 MapQuest, Inc.",
"imageUrl":"http://api.mqcdn.com/res/mqlogo.gif",
"imageAltText":"© 2018 MapQuest, Inc."
},
"statuscode":0,
"messages":[
]
}
}
Marc Pfister
4,14718 silver badges11 bronze badges
asked Mar 3, 2019 at 15:56
1 Answer 1
If you've loaded the response you can convert the shapePoints
and elevationProfile
arrays to an array of coordinate points that can be inserted in a blank GeoJSON feature object and loaded
// You can do it with a functional approach:
// Use Array.filter() to sort the alternating points to lats and lngs,
// then use Array.map() to extract the elevations
// and 'zip' the three arrays in one array of lng/lat/elev (x/y/z!) arrays
var lats = shapePoints.filter(function(e, i) {return i % 2 === 0;});
var lngs = shapePoints.filter(function(e, i) {return i % 2 != 0;});
var elevs = elevationProfile.map(function(e, i) {return e.height;});
var lnglats = lngs.map(function(e, i) {return [e, lats[i], elevs[i]];});
// or the more traditional way:
var lnglats = [];
for (var i=0; i<shapePoints.length; i=i+2) {
lnglats.push([shapePoints[i+1], shapePoints[i], elevationProfile[i/2].height]);
}
geojson = {
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": lnglats
}
};
L.geoJSON(geojson).addTo(map);
answered Mar 4, 2019 at 0:34
-
Thanks, i just need to add "height" value as well to geometry.coordinates in the polyline.Eslam Farag– Eslam Farag2019年03月04日 05:19:09 +00:00Commented Mar 4, 2019 at 5:19
-
OK, updated to pull the elevationsMarc Pfister– Marc Pfister2019年03月04日 15:00:58 +00:00Commented Mar 4, 2019 at 15:00
-
it returns NAN instead of Z/elevation on the output GeoJSON.Eslam Farag– Eslam Farag2019年03月04日 15:10:49 +00:00Commented Mar 4, 2019 at 15:10
-
Are you using the first example? I had a
filter
instead ofmap
to extract the elevationsMarc Pfister– Marc Pfister2019年03月04日 15:23:57 +00:00Commented Mar 4, 2019 at 15:23 -
It works now, but i need to add that polyline on the map as a GeoJSON layer, in order to implement elevation profile chart on it and calculate some values about elevations.Eslam Farag– Eslam Farag2019年03月04日 21:41:05 +00:00Commented Mar 4, 2019 at 21:41
lang-js