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":[

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.