Skip to content

Instantly share code, notes, and snippets.

@mappingvermont
Last active December 27, 2021 01:36
Show Gist options
  • Save mappingvermont/d534539fa3ebe4a1e242644e528bf7b9 to your computer and use it in GitHub Desktop.
Save mappingvermont/d534539fa3ebe4a1e242644e528bf7b9 to your computer and use it in GitHub Desktop.
Finding best-fit zoom level given a shapely geometry
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
import json
import math
from shapely.geometry import shape, MultiPoint
def find_zoom(geom, paddingFactor):
# translated from C# code here: https://gis.stackexchange.com/a/19652/
minX, minY, maxX, maxY = geom.bounds
ry1 = math.log((math.sin(deg2rad(minY)) + 1) / math.cos(deg2rad(minY)))
ry2 = math.log((math.sin(deg2rad(maxY)) + 1) / math.cos(deg2rad(maxY)))
ryc = (ry1 + ry2) / 2
centerY = rad2deg(math.atan(math.sinh(ryc)))
resolutionHorizontal = abs(minX - maxX) / 500.
vy0 = math.log(math.tan(math.pi*(0.25 + centerY / 360)))
vy1 = math.log(math.tan(math.pi*(0.25 + maxX/360)))
viewHeightHalf = 300. / 2.
zoomFactorPowered = viewHeightHalf / (40.7436654315252*(vy1 - vy0))
resolutionVertical = 360.0 / (zoomFactorPowered * 256)
resolution = max(resolutionHorizontal, resolutionVertical) * paddingFactor
zoom = math.log(360 / (resolution * 256), 2)
return zoom
def deg2rad(degree):
return degree*(math.pi/180)
def rad2deg(rad):
return (rad*180) / math.pi
if __name__ == '__main__':
with open('startpoint.geojson') as src:
start_pt = shape(json.load(src)['geometry'])
with open('endpoint.geojson') as src:
end_pt = shape(json.load(src)['geometry'])
multi_point = MultiPoint([start_pt, end_pt])
paddingFactor = 1
zoom = find_zoom(multi_point, paddingFactor)
print(zoom)
print(multi_point.centroid.coords[0])
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment