Skip to content

Commit

Permalink
add scale to Leaflet map
Browse files Browse the repository at this point in the history
  • Loading branch information
wang-boyu authored and rht committed Nov 25, 2022
1 parent 3873ca3 commit 99eeec3
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
1 change: 1 addition & 0 deletions examples/urban_growth/urban_growth/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ def render(self, model):
zoom=12.1,
map_height=394,
map_width=531,
scale_options={"imperial": False},
)
urbanized_text = UrbanizedText()
urbanized_chart = mesa.visualization.ChartModule(
Expand Down
16 changes: 12 additions & 4 deletions mesa_geo/visualization/modules/MapVisualization.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ def __init__(
zoom=None,
map_width=500,
map_height=500,
scale_options=None,
):
"""
Create a new MapModule.
Expand All @@ -68,14 +69,21 @@ def __init__(
of the space. Default is None.
:param map_width: The width of the map in pixels. Default is 500.
:param map_height: The height of the map in pixels. Default is 500.
:param scale_options: A dictionary of options for the map scale. Default is None (no map scale).
The available options can be found at: https://leafletjs.com/reference.html#control-scale-option
"""
self.portrayal_method = portrayal_method
self._crs = "epsg:4326"

if view is None and zoom is None:
new_element = f"new MapModule(null, null, {map_width}, {map_height})"
else:
new_element = f"new MapModule({view}, {zoom}, {map_width}, {map_height})"
view_js = "null" if view is None else view
zoom_js = "null" if zoom is None else zoom
scale_options_js = (
"null"
if scale_options is None
else str(scale_options).replace("True", "true").replace("False", "false")
)

new_element = f"new MapModule({view_js}, {zoom_js}, {map_width}, {map_height}, {scale_options_js})"
self.js_code = f"elements.push({new_element});"

def render(self, model):
Expand Down
5 changes: 4 additions & 1 deletion mesa_geo/visualization/templates/js/MapModule.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const MapModule = function (view, zoom, map_width, map_height) {
const MapModule = function (view, zoom, map_width, map_height, scale_options) {
// Create the map tag
const map_tag = document.createElement("div");
map_tag.style.width = map_width + "px";
Expand All @@ -16,6 +16,9 @@ const MapModule = function (view, zoom, map_width, map_height) {
if (customView) {
Lmap.setView(view, zoom)
}
if (scale_options !== null) {
L.control.scale(scale_options).addTo(Lmap)
}
let agentLayer = L.geoJSON().addTo(Lmap)

// create the OSM tile layer with correct attribution
Expand Down

0 comments on commit 99eeec3

Please sign in to comment.