I am trying to create a Leaflet.js web map that gives users the opportunity to draw lines. this line will be sent to mapquest elevation API to be retun to the map as a GeoJSON with elevation data calculated in order to showing some info about elevation in a popup for that drawn line.
The function goes well, but when i try to draw another line it doesn't work well and returns the first drawn line.
Here is my code:
map.on(L.Draw.Event.CREATED, function(event) {
var layer = event.layer;
// var content = getPopupContent(layer);
// if (content !== null) {
// layer.bindPopup(content);
// }
drawnItems.addLayer(layer);
drawData = drawnItems.toGeoJSON();
function showElevation(layer) {
var coords = layer.feature.geometry.coordinates;
var minPoint = minHPoint(coords, (layer.feature.geometry.type == 'LineString'));
var maxPoint = maxHPoint(coords, (layer.feature.geometry.type == 'LineString'));
minH = minPoint[2];
maxH = maxPoint[2]
if (elevationDisplayed && (currFeature === layer.feature)) {
map.removeControl(el);
elevationDisplayed = false;
}
else {
el.clear();
if (!elevationDisplayed) el.addTo(map);
el.addData(layer.feature);
currFeature = layer.feature;
elevationDisplayed = true;
}
};
var profile = drawData.features[0].geometry.coordinates;
fetch('http://open.mapquestapi.com/elevation/v1/profile?key=tHXSNAGXRx6LAoBNdgjjLycOhGqJalg7&shapeFormat=raw&latLngCollection='+profile)
.then(r => r.json())
.then(data => {
var latlngs = [];
for (var i=0; i<data.shapePoints.length; i=i+2) {
latlngs.push([data.shapePoints[i], data.shapePoints[i+1], data.elevationProfile[i/2].height]);
}
geojson = {
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": latlngs
}
};
var popupGeojson = L.popup();
L.geoJSON(geojson, {
style: function(feature, layer) {
return {'color': 'red'}
},
onEachFeature: function(feature, layer){
showElevation(layer);
$('#hideElevation').show();
$('#hideElevation').click(function() {
$('.background').toggle();
});
var firstPoint = feature.geometry.coordinates[0][2];
gainElevation = maxH - firstPoint;
var length = turf.length(geojson, {units: 'kilometers'});
popupGeojson.setContent("Distance: "+'<strong>'+Math.round(length)+ " km"+'</strong>'+'<br>'+"Low point: "+'<strong>'+minH+' meters'+'</strong>'+'<br>'+"High point: "+'<strong>'+maxH+' meters'+'</strong>'+'<br>'+"Gain: "+'<strong>'+Math.round(gainElevation)+" meters"+'</strong>');
//layer.bindPopup(popupGeojson);
map.on("zoomend", function() {
layer.bindPopup(popupGeojson).openPopup();
});
map.fitBounds(layer.getBounds());
}
}).addTo(drawnLine);
drawnLine.addTo(map);
})
});