nermiiine
nermiiine

Reputation: 167

Calculate altitude using Leaflet

I want to calculate altitude of a marker but I didn't find any solution in Leaflet. I found the elevation plugin which allow to draw elevation profil on map, but I don't need that. Do you have idea how to calculate altitude? Thank you.

Upvotes: 7

Views: 5162

Answers (2)

Seth Lutske
Seth Lutske

Reputation: 10676

Edit: A nice option

Adding this for anyone who might want it: since having written this answer, I wrote the plugin leaflet-topography to make doing this very fast and easy.

Original answer:

Not sure if anyone has answered yet but I cracked my head over this for a week and found a nice solution. First, you need to get the leaflet plugin leaflet-tileLayer-colorPicker:

https://github.com/frogcat/leaflet-tilelayer-colorpicker

This plugin enables you to get the color of a certain pixel on the map, given the latitude and longitude. Then, you need a dataset. One that's designed for this is the mapbox Terrain-RGB tiles:

https://docs.mapbox.com/help/troubleshooting/access-elevation-data/

These tiles have elevation data encoded in RGB format. The description on mapbox's site was not step-by-step enough for a beginner like me, so here's how you can do it:

Add the Terrain-RGB tilelayer

var colorPicker = L.tileLayer.colorPicker('https://api.mapbox.com/v4/mapbox.terrain-rgb/{z}/{x}/{y}.pngraw?access_token={accessToken}', {
  attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
  maxZoom: 18,
  id: 'mapbox.outdoors',
  accessToken: 'your mapbox accesstoken'
  }).addTo(yourMap)
  .setOpacity(0); // optional

Create a function which takes in latlng and outputs RGB as an array

function getElevation(location){
var color = colorPicker.getColor(location)
// location is an array [lat, lng]

Pick apart the RGB values of the array and put into mapbox's elevation equation

   let R = color[0];
   let G = color[1];
   let B = color[2];

   let height = -10000 + ((R * 256 * 256 + G * 256 + B) * 0.1)
   let heightRounded = Math.round( height * 10) / 10 + ' meters';
   return heightRounded;
}

That last bit is just to give a nice number rounded to the first decimal, output as a string like "182 meters", but you can write it however you like.

Upvotes: 6

zankuralt
zankuralt

Reputation: 173

I had a similar problem working on a Shiny app with leaflet and found a workaround using Google Elevation API and google_elevation() function of googleway package

The latter (R part) is probably not in your interest but the Google Elevation API implementation should work for you.

Upvotes: 5

Related Questions