emilhe / dash-leaflet

MIT License
204 stars 33 forks source link

Define map extent using bounds #209

Closed albavilanova closed 8 months ago

albavilanova commented 9 months ago

Hello,

I would like to know if there is any way to create a map object and set its bounds given a set of coordinates, instead of providing the map center and zoom level.

Thank you,

Alba

prl900 commented 9 months ago

I think the issue here is that the size and aspect ratio of the map window normally depend on things such as the device, screen size/resolution, or browser window size. If you were to define the bounds of the map, those will need to match the aspect ratio and size of the client's map window.

I guess you could fix the map's window size in pixels but the app would be quite inflexible in terms of client's devices. Setting just the map's centre and zoom level simplifies this problem as you don't need to worry about having to know the map window size on the client size.

If you don't need to match the exact bounds and have some flexibility around the edges, you could easily calculate the centre of your bounding box and, with a little bit of code, determine the zoom level that best matches your bounds.

emilhe commented 8 months ago

You can do that using the bounds property. The map will be fitted to include the bounds defined the by corner coordinates provided, e.g.

from dash import Dash, html
import dash_leaflet as dl

app = Dash()
app.layout = html.Div([
    dl.Map(dl.TileLayer(), bounds=[[56, 10], [55, 8]], style={'height': '50vh'}, id="map"),
    html.Div(id="log")
])
if __name__ == '__main__':
    app.run_server()
albavilanova commented 8 months ago

Hi @prl900 and @emilhe, thank you very much for your comments, at the end I used contextily to create the static maps I needed.