Last active
December 27, 2021 01:36
-
-
Save mappingvermont/d534539fa3ebe4a1e242644e528bf7b9 to your computer and use it in GitHub Desktop.
Finding best-fit zoom level given a shapely geometry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{"type":"Feature","properties":{},"geometry":{"type":"Point","coordinates":[-80.00696897506714,40.440431297805645]}} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment