在地图框中转换北纬、南纬、东西经和缩放到中心和大小

Convert North, South latutudes, East, West longitudes and Zoom to Center and Size in mapbox

因为我的问题 Convert North, South, East, West and Zoom to Center and Size in mapbox 昨天已经关闭,所以我今天找到了答案。我正在创建一个新问题。

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

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

获取with:东西经减去像素坐标,获取高度:南北纬减去像素坐标。

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

下面是生成地图框的 python 代码 url

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)