0

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

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
6
  • Thanks, i just need to add "height" value as well to geometry.coordinates in the polyline. Commented Mar 4, 2019 at 5:19
  • OK, updated to pull the elevations Commented Mar 4, 2019 at 15:00
  • it returns NAN instead of Z/elevation on the output GeoJSON. Commented Mar 4, 2019 at 15:10
  • Are you using the first example? I had a filter instead of map to extract the elevations Commented 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. Commented Mar 4, 2019 at 21:41

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.