python - 自动缩放 "Mapbox maps"

标签 python mapbox plotly-python

在情节网站Map Configuration and Styling in Python描述了如何自动缩放“地理 map ”:

import plotly.express as px

fig = px.line_geo(lat=[0,15,20,35], lon=[5,10,25,30])            # Creates a "Geo map" figure
fig.update_geos(fitbounds="locations")                           # Automatic Zooming !!!!
fig.show()
这有效,此外,如果我在“Mapbox map ”上尝试相同,它不会应用自动缩放:
fig = px.scatter_mapbox(filtered_df, lat="latitude", lon="longitude", color="ID")  # Creates a "Mapbox map" figure
fig.update_layout(mapbox_style="open-street-map")
fig.update_geos(fitbounds="locations")                                             # Automatic Zooming not working!!!
Mapbox Map Layers in Python 中没有有关如何操作的信息.

最佳答案

我与其他 geojson 一起编写了自己的函数rv_geojson.py 中的兼容功能
它采用位置列表并找到矩形绑定(bind)框的几何高度和宽度,非常适合与墨卡托投影一起使用。它返回缩放和中心。

def zoom_center(lons: tuple=None, lats: tuple=None, lonlats: tuple=None,
        format: str='lonlat', projection: str='mercator',
        width_to_height: float=2.0) -> (float, dict):
    """Finds optimal zoom and centering for a plotly mapbox.
    Must be passed (lons & lats) or lonlats.
    Temporary solution awaiting official implementation, see:
    https://github.com/plotly/plotly.js/issues/3434
    
    Parameters
    --------
    lons: tuple, optional, longitude component of each location
    lats: tuple, optional, latitude component of each location
    lonlats: tuple, optional, gps locations
    format: str, specifying the order of longitud and latitude dimensions,
        expected values: 'lonlat' or 'latlon', only used if passed lonlats
    projection: str, only accepting 'mercator' at the moment,
        raises `NotImplementedError` if other is passed
    width_to_height: float, expected ratio of final graph's with to height,
        used to select the constrained axis.
    
    Returns
    --------
    zoom: float, from 1 to 20
    center: dict, gps position with 'lon' and 'lat' keys

    >>> print(zoom_center((-109.031387, -103.385460),
    ...     (25.587101, 31.784620)))
    (5.75, {'lon': -106.208423, 'lat': 28.685861})
    """
    if lons is None and lats is None:
        if isinstance(lonlats, tuple):
            lons, lats = zip(*lonlats)
        else:
            raise ValueError(
                'Must pass lons & lats or lonlats'
            )
    
    maxlon, minlon = max(lons), min(lons)
    maxlat, minlat = max(lats), min(lats)
    center = {
        'lon': round((maxlon + minlon) / 2, 6),
        'lat': round((maxlat + minlat) / 2, 6)
    }
    
    # longitudinal range by zoom level (20 to 1)
    # in degrees, if centered at equator
    lon_zoom_range = np.array([
        0.0007, 0.0014, 0.003, 0.006, 0.012, 0.024, 0.048, 0.096,
        0.192, 0.3712, 0.768, 1.536, 3.072, 6.144, 11.8784, 23.7568,
        47.5136, 98.304, 190.0544, 360.0
    ])
    
    if projection == 'mercator':
        margin = 1.2
        height = (maxlat - minlat) * margin * width_to_height
        width = (maxlon - minlon) * margin
        lon_zoom = np.interp(width , lon_zoom_range, range(20, 0, -1))
        lat_zoom = np.interp(height, lon_zoom_range, range(20, 0, -1))
        zoom = round(min(lon_zoom, lat_zoom), 2)
    else:
        raise NotImplementedError(
            f'{projection} projection is not implemented'
        )
    
    return zoom, center
用它作为
zoom, center = zoom_center(
    lons=[5, 10, 25, 30],
    lats=[0, 15, 20, 35]
)
fig = px.scatter_mapbox(
    filtered_df, lat="latitude", lon="longitude", color="ID",
    zoom=zoom, center=center
)  # Creates a "Mapbox map" figure

关于python - 自动缩放 "Mapbox maps",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63787612/

相关文章:

python - 从特定目录在 python 中打开 csv 文件时出错

mapbox - 如何将中心标记向右偏移?

javascript - setFeatureState 不更新 Mapbox 中的值

python - 在 plotly 表达动画中隐藏播放和停止按钮

python - 如何使用 python 列表理解/字典将每一列打印为唯一变量

python - 这段代码有什么错误?

javascript - MapBox GLJS - 使用 for 循环创建标记时不显示

python - 更改plotlys悬停提示文本颜色

python - Pandas 和 Plotly : how to access data columns in the hover text that are not used to plot the point?

python - 如何在Python3中打印unicode列表