Fit to the bounds of a LineString
This source code of this example is adapted from the MapLibre GL JS example - Fit to the bounds of a LineString.
Uncomment the following line to install leafmap if needed.
In [1]:
Copied!
# %pip install "leafmap[maplibre]"
# %pip install "leafmap[maplibre]"
In [2]:
Copied!
import leafmap.maplibregl as leafmap
import leafmap.maplibregl as leafmap
In [3]:
Copied!
# import os
# os.environ["MAPTILER_KEY"] = "YOUR_API_KEY"
# import os
# os.environ["MAPTILER_KEY"] = "YOUR_API_KEY"
In [4]:
Copied!
m = leafmap.Map(center=[-77.0214, 38.897], zoom=12, style="streets")
geojson = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "LineString",
"properties": {},
"coordinates": [
[-77.0366048812866, 38.89873175227713],
[-77.03364372253417, 38.89876515143842],
[-77.03364372253417, 38.89549195896866],
[-77.02982425689697, 38.89549195896866],
[-77.02400922775269, 38.89387200688839],
[-77.01519012451172, 38.891416957534204],
[-77.01521158218382, 38.892068305429156],
[-77.00813055038452, 38.892051604275686],
[-77.00832366943358, 38.89143365883688],
[-77.00818419456482, 38.89082405874451],
[-77.00815200805664, 38.88989712255097],
],
},
}
],
}
m.add_source("LineString", {"type": "geojson", "data": geojson})
layer = {
"id": "LineString",
"type": "line",
"source": "LineString",
"layout": {"line-join": "round", "line-cap": "round"},
"paint": {"line-color": "#BF93E4", "line-width": 5},
}
m.add_layer(layer)
m
m = leafmap.Map(center=[-77.0214, 38.897], zoom=12, style="streets")
geojson = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "LineString",
"properties": {},
"coordinates": [
[-77.0366048812866, 38.89873175227713],
[-77.03364372253417, 38.89876515143842],
[-77.03364372253417, 38.89549195896866],
[-77.02982425689697, 38.89549195896866],
[-77.02400922775269, 38.89387200688839],
[-77.01519012451172, 38.891416957534204],
[-77.01521158218382, 38.892068305429156],
[-77.00813055038452, 38.892051604275686],
[-77.00832366943358, 38.89143365883688],
[-77.00818419456482, 38.89082405874451],
[-77.00815200805664, 38.88989712255097],
],
},
}
],
}
m.add_source("LineString", {"type": "geojson", "data": geojson})
layer = {
"id": "LineString",
"type": "line",
"source": "LineString",
"layout": {"line-join": "round", "line-cap": "round"},
"paint": {"line-color": "#BF93E4", "line-width": 5},
}
m.add_layer(layer)
m
Failed to retrieve the MapTiler style. Defaulting to 'dark-matter' style.
In [5]:
Copied!
bounds = leafmap.geojson_bounds(geojson)
bounds
bounds = leafmap.geojson_bounds(geojson)
bounds
Out[5]:
[np.float64(-77.0366048812866), np.float64(38.88989712255097), np.float64(-77.00813055038452), np.float64(38.89876515143842)]
In [6]:
Copied!
m.fit_bounds(bounds)
m.fit_bounds(bounds)