Coverage for src/sensai/geoanalytics/_globalmaptiles.py: 0%
90 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-13 22:17 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-13 22:17 +0000
1#!/usr/bin/env python
2###############################################################################
3# $Id$
4#
5# Project: GDAL2Tiles, Google Summer of Code 2007 & 2008
6# Global Map Tiles Classes
7# Purpose: Convert a raster into TMS tiles, create KML SuperOverlay EPSG:4326,
8# generate a simple HTML viewers based on Google Maps and OpenLayers
9# Author: Klokan Petr Pridal, klokan at klokan dot cz
10# Web: http://www.klokan.cz/projects/gdal2tiles/
11#
12###############################################################################
13# Copyright (c) 2008 Klokan Petr Pridal. All rights reserved.
14#
15# Permission is hereby granted, free of charge, to any person obtaining a
16# copy of this software and associated documentation files (the "Software"),
17# to deal in the Software without restriction, including without limitation
18# the rights to use, copy, modify, merge, publish, distribute, sublicense,
19# and/or sell copies of the Software, and to permit persons to whom the
20# Software is furnished to do so, subject to the following conditions:
21#
22# The above copyright notice and this permission notice shall be included
23# in all copies or substantial portions of the Software.
24#
25# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
26# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
28# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
30# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
31# DEALINGS IN THE SOFTWARE.
32###############################################################################
34"""
35_globalmaptiles.py
37Global Map Tiles as defined in MapTile Map Service (TMS) Profiles
38==============================================================
40Functions necessary for generation of global tiles used on the web.
41It contains classes implementing coordinate conversions for:
43 - GlobalMercator (based on EPSG:900913 = EPSG:3785)
44 for Google Maps, Yahoo Maps, Microsoft Maps compatible tiles
45 - GlobalGeodetic (based on EPSG:4326)
46 for OpenLayers Base Map and Google Earth compatible tiles
48More info at:
50http://wiki.osgeo.org/wiki/Tile_Map_Service_Specification
51http://wiki.osgeo.org/wiki/WMS_Tiling_Client_Recommendation
52http://msdn.microsoft.com/en-us/library/bb259689.aspx
53http://code.google.com/apis/maps/documentation/overlays.html#Google_Maps_Coordinates
55Created by Klokan Petr Pridal on 2008-07-03.
56Google Summer of Code 2008, project GDAL2Tiles for OSGEO.
58In case you use this class in your product, translate it to another language
59or find it usefull for your project please let me know.
60My email: klokan at klokan dot cz.
61I would like to know where it was used.
63Class is available under the open-source GDAL license (www.gdal.org).
64"""
66import math
67from typing import Tuple
70class GlobalMercator(object):
71 """
72 TMS Global Mercator Profile
73 ---------------------------
75 Functions necessary for generation of tiles in Spherical Mercator projection,
76 EPSG:900913 (EPSG:gOOglE, Google Maps Global Mercator), EPSG:3785, OSGEO:41001.
78 Such tiles are compatible with Google Maps, Microsoft Virtual Earth, Yahoo Maps,
79 UK Ordnance Survey OpenSpace API, ...
80 and you can overlay them on top of base maps of those web mapping applications.
82 Pixel and tile coordinates are in TMS notation (origin [0,0] in bottom-left).
84 What coordinate conversions do we need for TMS Global Mercator tiles::
86 LatLon <-> Meters <-> Pixels <-> MapTile
88 WGS84 coordinates Spherical Mercator Pixels in pyramid Tiles in pyramid
89 lat/lon XY in metres XY pixels Z zoom XYZ from TMS
90 EPSG:4326 EPSG:900913
91 .----. --------- -- TMS
92 / \ <-> | | <-> /----/ <-> Google
93 \ / | | /--------/ QuadTree
94 ----- --------- /------------/
95 KML, public WebMapService Web Clients TileMapService
97 What is the coordinate extent of Earth in EPSG:900913?
99 [-20037508.342789244, -20037508.342789244, 20037508.342789244, 20037508.342789244]
100 Constant 20037508.342789244 comes from the circumference of the Earth in meters,
101 which is 40 thousand kilometers, the coordinate origin is in the middle of extent.
102 In fact you can calculate the constant as: 2 * math.pi * 6378137 / 2.0
103 $ echo 180 85 | gdaltransform -s_srs EPSG:4326 -t_srs EPSG:900913
104 Polar areas with abs(latitude) bigger then 85.05112878 are clipped off.
106 What are zoom level constants (pixels/meter) for pyramid with EPSG:900913?
108 whole region is on top of pyramid (zoom=0) covered by 256x256 pixels tile,
109 every lower zoom level resolution is always divided by two
110 initialResolution = 20037508.342789244 * 2 / 256 = 156543.03392804062
112 What is the difference between TMS and Google Maps/QuadTree tile name convention?
114 The tile raster itself is the same (equal extent, projection, pixel size),
115 there is just different identification of the same raster tile.
116 Tiles in TMS are counted from [0,0] in the bottom-left corner, id is XYZ.
117 Google placed the origin [0,0] to the top-left corner, reference is XYZ.
118 Microsoft is referencing tiles by a QuadTree name, defined on the website:
119 http://msdn2.microsoft.com/en-us/library/bb259689.aspx
121 The lat/lon coordinates are using WGS84 datum, yeh?
123 Yes, all lat/lon we are mentioning should use WGS84 Geodetic Datum.
124 Well, the web clients like Google Maps are projecting those coordinates by
125 Spherical Mercator, so in fact lat/lon coordinates on sphere are treated as if
126 the were on the WGS84 ellipsoid.
128 From MSDN documentation:
129 To simplify the calculations, we use the spherical form of projection, not
130 the ellipsoidal form. Since the projection is used only for map display,
131 and not for displaying numeric coordinates, we don't need the extra precision
132 of an ellipsoidal projection. The spherical projection causes approximately
133 0.33 percent scale distortion in the Y direction, which is not visually noticable.
135 How do I create a raster in EPSG:900913 and convert coordinates with PROJ.4?
137 You can use standard GIS tools like gdalwarp, cs2cs or gdaltransform.
138 All of the tools supports -t_srs 'epsg:900913'.
140 For other GIS programs check the exact definition of the projection:
141 More info at http://spatialreference.org/ref/user/google-projection/
142 The same projection is degined as EPSG:3785. WKT definition is in the official
143 EPSG database.
145 Proj4 Text:
146 +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0
147 +k=1.0 +units=m +nadgrids=@null +no_defs
149 Human readable WKT format of EPGS:900913:
150 PROJCS["Google Maps Global Mercator",
151 GEOGCS["WGS 84",
152 DATUM["WGS_1984",
153 SPHEROID["WGS 84",6378137,298.2572235630016,
154 AUTHORITY["EPSG","7030"]],
155 AUTHORITY["EPSG","6326"]],
156 PRIMEM["Greenwich",0],
157 UNIT["degree",0.0174532925199433],
158 AUTHORITY["EPSG","4326"]],
159 PROJECTION["Mercator_1SP"],
160 PARAMETER["central_meridian",0],
161 PARAMETER["scale_factor",1],
162 PARAMETER["false_easting",0],
163 PARAMETER["false_northing",0],
164 UNIT["metre",1,
165 AUTHORITY["EPSG","9001"]]]
166 """
168 def __init__(self, tileSize=256):
169 """
170 Initialize the TMS Global Mercator pyramid
172 :param tileSize: the tile size in pixels
173 """
174 self.tileSize = tileSize
175 self.initialResolution = 2 * math.pi * 6378137 / self.tileSize
176 # 156543.03392804062 for tileSize 256 pixels
177 self.originShift = 2 * math.pi * 6378137 / 2.0
178 # 20037508.342789244
180 def LatLonToMeters(self, lat: float, lon: float):
181 """"Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:900913"""
183 mx = lon * self.originShift / 180.0
184 my = math.log(math.tan((90 + lat) * math.pi / 360.0)) / (math.pi / 180.0)
186 my = my * self.originShift / 180.0
187 return mx, my
189 def MetersToLatLon(self, mx, my):
190 """Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 Datum"""
192 lon = (mx / self.originShift) * 180.0
193 lat = (my / self.originShift) * 180.0
195 lat = 180 / math.pi * (2 * math.atan(math.exp(lat * math.pi / 180.0)) - math.pi / 2.0)
196 return lat, lon
198 def PixelsToMeters(self, px, py, zoom):
199 """Converts pixel coordinates in given zoom level of pyramid to EPSG:900913"""
201 res = self.Resolution(zoom)
202 mx = px * res - self.originShift
203 my = py * res - self.originShift
204 return mx, my
206 def MetersToPixels(self, mx, my, zoom):
207 """Converts EPSG:900913 to pyramid pixel coordinates in given zoom level"""
209 res = self.Resolution(zoom)
210 px = (mx + self.originShift) / res
211 py = (my + self.originShift) / res
212 return px, py
214 def PixelsToTile(self, px, py):
215 """Returns a tile covering region in given pixel coordinates"""
217 tx = int(math.ceil(px / float(self.tileSize)) - 1)
218 ty = int(math.ceil(py / float(self.tileSize)) - 1)
219 return tx, ty
221 def PixelsToRaster(self, px, py, zoom):
222 """Move the origin of pixel coordinates to top-left corner"""
224 mapSize = self.tileSize << zoom
225 return px, mapSize - py
227 def MetersToTile(self, mx, my, zoom):
228 """Returns tile for given mercator coordinates"""
230 px, py = self.MetersToPixels(mx, my, zoom)
231 return self.PixelsToTile(px, py)
233 def LatLonToTile(self, lat, lon, zoom) -> Tuple[int, int]:
234 return self.MetersToTile(*self.LatLonToMeters(lat, lon), zoom)
236 def TileBounds(self, tx, ty, zoom):
237 """Returns bounds of the given tile in EPSG:900913 coordinates"""
239 minx, miny = self.PixelsToMeters(tx*self.tileSize, ty*self.tileSize, zoom)
240 maxx, maxy = self.PixelsToMeters((tx+1)*self.tileSize, (ty+1)*self.tileSize, zoom)
241 return minx, miny, maxx, maxy
243 def TileLatLonBounds(self, tx, ty, zoom):
244 """Returns bounds of the given tile in latutude/longitude using WGS84 datum"""
246 bounds = self.TileBounds(tx, ty, zoom)
247 minLat, minLon = self.MetersToLatLon(bounds[0], bounds[1])
248 maxLat, maxLon = self.MetersToLatLon(bounds[2], bounds[3])
250 return minLat, minLon, maxLat, maxLon
252 def Resolution(self, zoom):
253 """Resolution (meters/pixel) for given zoom level (measured at Equator)"""
255 # return (2 * math.pi * 6378137) / (self.tileSize * 2**zoom)
256 return self.initialResolution / (2**zoom)
258 def ZoomForPixelSize(self, pixelSize):
259 """Maximal scaledown zoom of the pyramid closest to the pixelSize."""
261 for i in range(30):
262 if pixelSize > self.Resolution(i):
263 return i-1 if i != 0 else 0 # We don't want to scale up
265 @staticmethod
266 def GoogleTile(tx, ty, zoom):
267 """Converts TMS tile coordinates to Google MapTile coordinates"""
269 # coordinate origin is moved from bottom-left to top-left corner of the extent
270 return tx, (2**zoom - 1) - ty
272 @staticmethod
273 def QuadTree(tx, ty, zoom):
274 """Converts TMS tile coordinates to Microsoft QuadTree"""
276 quadKey = ""
277 ty = (2**zoom - 1) - ty
278 for i in range(zoom, 0, -1):
279 digit = 0
280 mask = 1 << (i-1)
281 if (tx & mask) != 0:
282 digit += 1
283 if (ty & mask) != 0:
284 digit += 2
285 quadKey += str(digit)
287 return quadKey
290class GlobalGeodetic(object):
291 """
292 TMS Global Geodetic Profile
293 ---------------------------
295 Functions necessary for generation of global tiles in Plate Carre projection,
296 EPSG:4326, "unprojected profile".
298 Such tiles are compatible with Google Earth (as any other EPSG:4326 rasters)
299 and you can overlay the tiles on top of OpenLayers base map.
301 Pixel and tile coordinates are in TMS notation (origin [0,0] in bottom-left).
303 What coordinate conversions do we need for TMS Global Geodetic tiles?
305 Global Geodetic tiles are using geodetic coordinates (latitude,longitude)
306 directly as planar coordinates XY (it is also called Unprojected or Plate
307 Carre). We need only scaling to pixel pyramid and cutting to tiles.
308 Pyramid has on top level two tiles, so it is not square but rectangle.
309 Area [-180,-90,180,90] is scaled to 512x256 pixels.
310 TMS has coordinate origin (for pixels and tiles) in bottom-left corner.
311 Rasters are in EPSG:4326 and therefore are compatible with Google Earth.
313 LatLon <-> Pixels <-> Tiles
315 WGS84 coordinates Pixels in pyramid Tiles in pyramid
316 lat/lon XY pixels Z zoom XYZ from TMS
317 EPSG:4326
318 .----. ----
319 / \ <-> /--------/ <-> TMS
320 \ / /--------------/
321 ----- /--------------------/
322 WMS, KML Web Clients, Google Earth TileMapService
323 """
325 def __init__(self, tileSize=256):
326 self.tileSize = tileSize
328 @staticmethod
329 def LatLonToPixels(lat, lon, zoom):
330 """Converts lat/lon to pixel coordinates in given zoom of the EPSG:4326 pyramid"""
332 res = 180 / 256.0 / 2**zoom
333 px = (180 + lat) / res
334 py = (90 + lon) / res
335 return px, py
337 def PixelsToTile(self, px, py):
338 """Returns coordinates of the tile covering region in pixel coordinates"""
340 tx = int(math.ceil(px / float(self.tileSize)) - 1)
341 ty = int(math.ceil(py / float(self.tileSize)) - 1)
342 return tx, ty
344 @staticmethod
345 def Resolution(zoom):
346 """Resolution (arc/pixel) for given zoom level (measured at Equator)"""
348 return 180 / 256.0 / 2**zoom
349 #return 180 / float(1 << (8+zoom))
351 @staticmethod
352 def TileBounds(tx, ty, zoom):
353 """Returns bounds of the given tile"""
354 res = 180 / 256.0 / 2**zoom
355 return (
356 tx*256*res - 180,
357 ty*256*res - 90,
358 (tx+1)*256*res - 180,
359 (ty+1)*256*res - 90)