Search code examples
pythonleafletipywidgetsipyleaflet

Change area calculation to km2 in ipyleaflet DrawControl


When creating a DrawControl in ipyleaflet, I am able to draw a polygon in the map. An example below:

[![from ipyleaflet import Map, basemaps, basemap_to_tiles, DrawControl

watercolor = basemap_to_tiles(basemaps.Stadia.StamenTerrain)

m = Map(layers=(watercolor, ), center=(50, 354), zoom=5)

draw_control = DrawControl()
draw_control.polyline =  {
    "shapeOptions": {
        "color": "#6bc2e5",
        "weight": 8,
        "opacity": 1.0
    }
}
draw_control.polygon = {
    "shapeOptions": {
        "fillColor": "#6be5c3",
        "color": "#6be5c3",
        "fillOpacity": 1.0
    },
    "drawError": {
        "color": "#dd253b",
        "message": "Oups!"
    },
    "allowIntersection": False
}
draw_control.circle = {
    "shapeOptions": {
        "fillColor": "#efed69",
        "color": "#efed69",
        "fillOpacity": 1.0
    }
}
draw_control.rectangle = {
    "shapeOptions": {
        "fillColor": "#fca45d",
        "color": "#fca45d",
        "fillOpacity": 1.0
    }
}

m.add(draw_control)

m

When drawing it, the area of the drawn polygon appears in ha. Would it be possible to change to km2? So far, I have not found any documentation on that possibility.

enter image description here


Solution

  • Add the units to a metric option of your shape:

    
    draw_control.rectangle = {
        "shapeOptions": {
            "fillColor": "#aca45d",
            "color": "#fca45d",
            "fillOpacity": 1.0,  
        },
         "metric": ['km','ha','m']
    }
    

    In this case, the values will be in square meters until 1ha (10,000 m2), then in ha, then in km2 for areas bigger than 1km2 (100ha).

    If you just put "metric":"m", it will all be in m2.

    The unit option is a polygon option and not a shapeOption, as detailed here:

    https://leaflet.github.io/Leaflet.draw/docs/leaflet-draw-latest.html#drawoptions