Home > Back-end >  Calculate area boundaries with only coordinates of the OSM map centre and the zoom factor
Calculate area boundaries with only coordinates of the OSM map centre and the zoom factor

Time:05-17

I'm using MapSCII (by rastapasta) for a project with python and nodejs. I need to render some objects by their location within the MapSCII output. MapSCII uses OSM tile layers to generate the ASCII map. I only know the coordinates of the center of the map, the zoom level as well as the number of rows/columns of the ASCII map.

Do you have any hints on how to calculate the boundaries (upper left and lower right corner), so that I can map a local coordinate system onto the ACSII data?

Take these variables for example:

def calculate_boundaries(lat, lng, zoom, width, height) -> tuple:
    ...

lat = 51.5252178
lng = -0.0925642
zoom = 17
width = 80
height = 24
upper_left, lower_right = calculate_boundaries(lat, lng, zoom, width, height)

I stumbled across this wiki entry, but it does not seem to be helpful, as I do not work with the tile numbers but with latitude/longitude.

// Edit Is this even feasible? Or would it be easier to note down, how much lat/lng change when moving in the 2D MapSCII array on each zoom level?

CodePudding user response:

Let's consider width and height in pixels.

Calculation of Meters per Pixel (m/px) The distance (S) represented by 01 (one) pixel is given by:

S=C*cos(y)/2^(z 8) Where:

C is the circumference of the Earth at the Equator; z is the zoom level; y is the latitude where you want to get the scale.

Source: https://wiki.openstreetmap.org/wiki/Pt:Zoom_levels

There were a mistake while converting degree to radian. So I imported pi and convertion.

from math import cos, pi

def calculate_boundaries(lat, lng, zoom, width, height): # -> tuple:
    upper_left, lower_right = {}, {}
    C = 40075 # km - Equator distance around the world
    y = pi * lat / 180 # convert latitude degree to radian
    S = C * cos(y) / 2 ** (zoom   8) # km distance of 1 px - https://wiki.openstreetmap.org/wiki/Pt:Zoom_levels
    S_deg = S * cos(y) / 100 # convert km (distance of 1 px) to degrees (coordinates)

    upper_left['lat'] = lat   height / 2 * S_deg
    upper_left['lng'] = lng - width / 2 * S_deg

    lower_right['lat'] = lat - height / 2 * S_deg
    lower_right['lng'] = lng   width / 2 * S_deg

    return upper_left, lower_right

# main
lat = 51.5252178
lng = -0.0925642
zoom = 17 # zoom
width = 80 # considered as pixels
height = 24
upper_left, lower_right = calculate_boundaries(lat, lng, zoom, width, height)

print(upper_left, lower_right)
  • Related