首页 > 解决方案 > 在地图框中转换北、南纬度、东、西经度并缩放到中心和大小

问题描述

自从我的问题将北、南、东、西和缩放到地图框中的中心和大小昨天关闭,我今天找到了答案。我正在创建一个新问题。

如上一个问题所述。我想在 mapbox 上创建一个图像,该图像以北纬、东经、南纬、西经和缩放因子为界。结果应该是宽度、高度、中心纬度和中心经度。

标签: pythonmapboxmapbox-static-maps

解决方案


在 Web Mercator Wikipedia 页面上,您可以找到将纬度和经度转换为像素坐标的公式:https ://en.wikipedia.org/wiki/Web_Mercator_projection

得到:从东经和西经减去像素坐标,得到高度:从南纬和北纬减去像素坐标。

要获得中心坐标,请从像素坐标的中心计算纬度和经度。

您可以在下面找到生成 mapbox url 的 python 代码

import math

def zoom_factor(zoom):
    return 256/math.pi * 2**zoom

def latitude_to_pixel(latitude, zoom):
    return zoom_factor(zoom) * (math.pi - math.log(math.tan((math.pi/2 + math.radians(latitude))/2)))

def longitude_to_pixel(longitude, zoom):
    return zoom_factor(zoom) * (math.radians(longitude) + math.pi)

def pixel_to_latitude(y, zoom):
    #return math.degrees(2 * math.atan(math.exp(y / zoom_factor(zoom) - math.pi)) - math.pi/2)
    return math.degrees(2 * math.atan(math.exp(math.pi - y / zoom_factor(zoom))) - math.pi/2)

def pixel_to_longitude(x, zoom):
    return math.degrees(x / zoom_factor(zoom) - math.pi)

def mapbox_dimensions(south, north, west, east, zoom):
    top = math.floor(latitude_to_pixel(north, zoom))
    bottom = math.ceil(latitude_to_pixel(south, zoom))
    left = math.floor(longitude_to_pixel(west, zoom))
    right = math.ceil(longitude_to_pixel(east, zoom))
    return {
        'width': right - left,
        'height': bottom - top,
        'latitude': pixel_to_latitude((top+bottom)/2, zoom),
        'longitude': pixel_to_longitude((left+right)/2, zoom),
        'zoom': zoom,
}

dimensions = mapbox_dimensions(49, 54, 2, 8, 6)
dimensions['style'] = 'streets-v11'
dimensions['token'] = 'Your token'

print('https://api.mapbox.com/styles/v1/mapbox/%(style)s/static/%(longitude)s,%(latitude)s,%(zoom)s,0,0/%(width)sx%(height)s?access_token=%(token)s' % dimensions)

推荐阅读