This repository has been archived on 2024-07-04. You can view files and clone it, but cannot push or open issues or pull requests.
osm_map_processing/pymapsforge/poly.py

93 lines
2.5 KiB
Python

# Copyright 2018 Mike "KemoNine" Crosson
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Adapted from https://github.com/mapsforge/mapsforge-creator/blob/master/poly2bb.pl
import re, os
BOUND_BUFFER = 0.1
COORD_MATCHER = re.compile('^\s*([0-9.E+-]+)\s+([0-9.E+-]+)\s*$')
def calculate_total_bounds(maps_dir, map_lists):
cached_maps_dir = os.path.abspath(maps_dir)
x_min = 360.0
x_max = -360.0
y_min = 360.0
y_max = -360.0
for alist in map_lists:
with open(alist, 'r') as maps:
for line in maps:
current_map = line.strip().split('/')[-1]
bounds = calculate_bounds(os.path.join(cached_maps_dir, current_map + '.poly'))
if bounds['bottom'] < y_min:
y_min = bounds['bottom']
if bounds['left'] < x_min:
x_min = bounds['left']
if bounds['top'] > y_max:
y_max = bounds['top']
if bounds['right'] > x_max:
x_max = bounds['right']
values = {}
values['bottom'] = y_min
values['left'] = x_min
values['top'] = y_max
values['right'] = x_max
return values
def calculate_bounds(mappoly):
# Opposite of max possible values so we find the right bounding box later
x_min = 360.0
x_max = -360.0
y_min = 360.0
y_max = -360.0
with open(mappoly, 'r') as polyfile:
for line in polyfile:
if COORD_MATCHER.match(line.strip()):
values = line.split()
x = float(values[0])
y = float(values[1])
if x < x_min:
x_min = x
if x > x_max:
x_max = x
if y < y_min:
y_min = y
if y > y_max:
y_max = y
# Buffer bounds
x_min = x_min - BOUND_BUFFER
x_max = x_max + BOUND_BUFFER
y_min = y_min - BOUND_BUFFER
y_max = y_max + BOUND_BUFFER
# Cleanup bounding (per original script)
x_min = -180 if x_min < -180 else x_min
x_max = 180 if x_max > 180 else x_max
y_min = -90 if y_min < -90 else y_min
y_max = 90 if y_max > 90 else y_max
# Dict w/ useful values
values = {}
values['bottom'] = y_min
values['left'] = x_min
values['top'] = y_max
values['right'] = x_max
x_center = (x_min + x_max) / 2.0
y_center = (y_min + y_max) / 2.0
values['lat'] = y_center
values['lon'] = x_center
return values