gdal2tiles.py 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136
  1. #!/usr/bin/env python
  2. #******************************************************************************
  3. # $Id: gdal2tiles.py 15748 2008-11-17 16:30:54Z klokan $
  4. #
  5. # Project: Google Summer of Code 2007, 2008 (http://code.google.com/soc/)
  6. # Support: BRGM (http://www.brgm.fr)
  7. # Purpose: Convert a raster into TMS (Tile Map Service) tiles in a directory.
  8. # - generate Google Earth metadata (KML SuperOverlay)
  9. # - generate simple HTML viewer based on Google Maps and OpenLayers
  10. # - support of global tiles (Spherical Mercator) for compatibility
  11. # with interactive web maps a la Google Maps
  12. # Author: Klokan Petr Pridal, klokan at klokan dot cz
  13. # Web: http://www.klokan.cz/projects/gdal2tiles/
  14. # GUI: http://www.maptiler.org/
  15. #
  16. ###############################################################################
  17. # Copyright (c) 2008, Klokan Petr Pridal
  18. #
  19. # Permission is hereby granted, free of charge, to any person obtaining a
  20. # copy of this software and associated documentation files (the "Software"),
  21. # to deal in the Software without restriction, including without limitation
  22. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  23. # and/or sell copies of the Software, and to permit persons to whom the
  24. # Software is furnished to do so, subject to the following conditions:
  25. #
  26. # The above copyright notice and this permission notice shall be included
  27. # in all copies or substantial portions of the Software.
  28. #
  29. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  30. # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  31. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  32. # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  33. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  34. # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  35. # DEALINGS IN THE SOFTWARE.
  36. #******************************************************************************
  37. try:
  38. from osgeo import gdal
  39. from osgeo import osr
  40. except ImportError:
  41. import gdal
  42. import osr
  43. import sys
  44. import os
  45. import math
  46. try:
  47. from PIL import Image
  48. import numpy
  49. import osgeo.gdal_array as gdalarray
  50. except:
  51. # 'antialias' resampling is not available
  52. pass
  53. __version__ = "$Id: gdal2tiles.py 15748 2008-11-17 16:30:54Z klokan $"
  54. resampling_list = ('average','near','bilinear','cubic','cubicspline','lanczos','antialias')
  55. profile_list = ('mercator','geodetic','raster') #,'zoomify')
  56. webviewer_list = ('all','google','openlayers','none')
  57. # =============================================================================
  58. # =============================================================================
  59. # =============================================================================
  60. __doc__globalmaptiles = """
  61. globalmaptiles.py
  62. Global Map Tiles as defined in Tile Map Service (TMS) Profiles
  63. ==============================================================
  64. Functions necessary for generation of global tiles used on the web.
  65. It contains classes implementing coordinate conversions for:
  66. - GlobalMercator (based on EPSG:900913 = EPSG:3785)
  67. for Google Maps, Yahoo Maps, Microsoft Maps compatible tiles
  68. - GlobalGeodetic (based on EPSG:4326)
  69. for OpenLayers Base Map and Google Earth compatible tiles
  70. More info at:
  71. http://wiki.osgeo.org/wiki/Tile_Map_Service_Specification
  72. http://wiki.osgeo.org/wiki/WMS_Tiling_Client_Recommendation
  73. http://msdn.microsoft.com/en-us/library/bb259689.aspx
  74. http://code.google.com/apis/maps/documentation/overlays.html#Google_Maps_Coordinates
  75. Created by Klokan Petr Pridal on 2008-07-03.
  76. Google Summer of Code 2008, project GDAL2Tiles for OSGEO.
  77. In case you use this class in your product, translate it to another language
  78. or find it usefull for your project please let me know.
  79. My email: klokan at klokan dot cz.
  80. I would like to know where it was used.
  81. Class is available under the open-source GDAL license (www.gdal.org).
  82. """
  83. import math
  84. MAXZOOMLEVEL = 32
  85. class GlobalMercator(object):
  86. """
  87. TMS Global Mercator Profile
  88. ---------------------------
  89. Functions necessary for generation of tiles in Spherical Mercator projection,
  90. EPSG:900913 (EPSG:gOOglE, Google Maps Global Mercator), EPSG:3785, OSGEO:41001.
  91. Such tiles are compatible with Google Maps, Microsoft Virtual Earth, Yahoo Maps,
  92. UK Ordnance Survey OpenSpace API, ...
  93. and you can overlay them on top of base maps of those web mapping applications.
  94. Pixel and tile coordinates are in TMS notation (origin [0,0] in bottom-left).
  95. What coordinate conversions do we need for TMS Global Mercator tiles::
  96. LatLon <-> Meters <-> Pixels <-> Tile
  97. WGS84 coordinates Spherical Mercator Pixels in pyramid Tiles in pyramid
  98. lat/lon XY in metres XY pixels Z zoom XYZ from TMS
  99. EPSG:4326 EPSG:900913
  100. .----. --------- -- TMS
  101. / \ <-> | | <-> /----/ <-> Google
  102. \ / | | /--------/ QuadTree
  103. ----- --------- /------------/
  104. KML, public WebMapService Web Clients TileMapService
  105. What is the coordinate extent of Earth in EPSG:900913?
  106. [-20037508.342789244, -20037508.342789244, 20037508.342789244, 20037508.342789244]
  107. Constant 20037508.342789244 comes from the circumference of the Earth in meters,
  108. which is 40 thousand kilometers, the coordinate origin is in the middle of extent.
  109. In fact you can calculate the constant as: 2 * math.pi * 6378137 / 2.0
  110. $ echo 180 85 | gdaltransform -s_srs EPSG:4326 -t_srs EPSG:900913
  111. Polar areas with abs(latitude) bigger then 85.05112878 are clipped off.
  112. What are zoom level constants (pixels/meter) for pyramid with EPSG:900913?
  113. whole region is on top of pyramid (zoom=0) covered by 256x256 pixels tile,
  114. every lower zoom level resolution is always divided by two
  115. initialResolution = 20037508.342789244 * 2 / 256 = 156543.03392804062
  116. What is the difference between TMS and Google Maps/QuadTree tile name convention?
  117. The tile raster itself is the same (equal extent, projection, pixel size),
  118. there is just different identification of the same raster tile.
  119. Tiles in TMS are counted from [0,0] in the bottom-left corner, id is XYZ.
  120. Google placed the origin [0,0] to the top-left corner, reference is XYZ.
  121. Microsoft is referencing tiles by a QuadTree name, defined on the website:
  122. http://msdn2.microsoft.com/en-us/library/bb259689.aspx
  123. The lat/lon coordinates are using WGS84 datum, yeh?
  124. Yes, all lat/lon we are mentioning should use WGS84 Geodetic Datum.
  125. Well, the web clients like Google Maps are projecting those coordinates by
  126. Spherical Mercator, so in fact lat/lon coordinates on sphere are treated as if
  127. 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.
  134. How do I create a raster in EPSG:900913 and convert coordinates with PROJ.4?
  135. You can use standard GIS tools like gdalwarp, cs2cs or gdaltransform.
  136. All of the tools supports -t_srs 'epsg:900913'.
  137. For other GIS programs check the exact definition of the projection:
  138. More info at http://spatialreference.org/ref/user/google-projection/
  139. The same projection is degined as EPSG:3785. WKT definition is in the official
  140. EPSG database.
  141. Proj4 Text:
  142. +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0
  143. +k=1.0 +units=m +nadgrids=@null +no_defs
  144. Human readable WKT format of EPGS:900913:
  145. PROJCS["Google Maps Global Mercator",
  146. GEOGCS["WGS 84",
  147. DATUM["WGS_1984",
  148. SPHEROID["WGS 84",6378137,298.2572235630016,
  149. AUTHORITY["EPSG","7030"]],
  150. AUTHORITY["EPSG","6326"]],
  151. PRIMEM["Greenwich",0],
  152. UNIT["degree",0.0174532925199433],
  153. AUTHORITY["EPSG","4326"]],
  154. PROJECTION["Mercator_1SP"],
  155. PARAMETER["central_meridian",0],
  156. PARAMETER["scale_factor",1],
  157. PARAMETER["false_easting",0],
  158. PARAMETER["false_northing",0],
  159. UNIT["metre",1,
  160. AUTHORITY["EPSG","9001"]]]
  161. """
  162. def __init__(self, tileSize=256):
  163. "Initialize the TMS Global Mercator pyramid"
  164. self.tileSize = tileSize
  165. self.initialResolution = 2 * math.pi * 6378137 / self.tileSize
  166. # 156543.03392804062 for tileSize 256 pixels
  167. self.originShift = 2 * math.pi * 6378137 / 2.0
  168. # 20037508.342789244
  169. def LatLonToMeters(self, lat, lon ):
  170. "Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:900913"
  171. mx = lon * self.originShift / 180.0
  172. my = math.log( math.tan((90 + lat) * math.pi / 360.0 )) / (math.pi / 180.0)
  173. my = my * self.originShift / 180.0
  174. return mx, my
  175. def MetersToLatLon(self, mx, my ):
  176. "Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 Datum"
  177. lon = (mx / self.originShift) * 180.0
  178. lat = (my / self.originShift) * 180.0
  179. lat = 180 / math.pi * (2 * math.atan( math.exp( lat * math.pi / 180.0)) - math.pi / 2.0)
  180. return lat, lon
  181. def PixelsToMeters(self, px, py, zoom):
  182. "Converts pixel coordinates in given zoom level of pyramid to EPSG:900913"
  183. res = self.Resolution( zoom )
  184. mx = px * res - self.originShift
  185. my = py * res - self.originShift
  186. return mx, my
  187. def MetersToPixels(self, mx, my, zoom):
  188. "Converts EPSG:900913 to pyramid pixel coordinates in given zoom level"
  189. res = self.Resolution( zoom )
  190. px = (mx + self.originShift) / res
  191. py = (my + self.originShift) / res
  192. return px, py
  193. def PixelsToTile(self, px, py):
  194. "Returns a tile covering region in given pixel coordinates"
  195. tx = int( math.ceil( px / float(self.tileSize) ) - 1 )
  196. ty = int( math.ceil( py / float(self.tileSize) ) - 1 )
  197. return tx, ty
  198. def PixelsToRaster(self, px, py, zoom):
  199. "Move the origin of pixel coordinates to top-left corner"
  200. mapSize = self.tileSize << zoom
  201. return px, mapSize - py
  202. def MetersToTile(self, mx, my, zoom):
  203. "Returns tile for given mercator coordinates"
  204. px, py = self.MetersToPixels( mx, my, zoom)
  205. return self.PixelsToTile( px, py)
  206. def TileBounds(self, tx, ty, zoom):
  207. "Returns bounds of the given tile in EPSG:900913 coordinates"
  208. minx, miny = self.PixelsToMeters( tx*self.tileSize, ty*self.tileSize, zoom )
  209. maxx, maxy = self.PixelsToMeters( (tx+1)*self.tileSize, (ty+1)*self.tileSize, zoom )
  210. return ( minx, miny, maxx, maxy )
  211. def TileLatLonBounds(self, tx, ty, zoom ):
  212. "Returns bounds of the given tile in latutude/longitude using WGS84 datum"
  213. bounds = self.TileBounds( tx, ty, zoom)
  214. minLat, minLon = self.MetersToLatLon(bounds[0], bounds[1])
  215. maxLat, maxLon = self.MetersToLatLon(bounds[2], bounds[3])
  216. return ( minLat, minLon, maxLat, maxLon )
  217. def Resolution(self, zoom ):
  218. "Resolution (meters/pixel) for given zoom level (measured at Equator)"
  219. # return (2 * math.pi * 6378137) / (self.tileSize * 2**zoom)
  220. return self.initialResolution / (2**zoom)
  221. def ZoomForPixelSize(self, pixelSize ):
  222. "Maximal scaledown zoom of the pyramid closest to the pixelSize."
  223. for i in range(MAXZOOMLEVEL):
  224. if pixelSize > self.Resolution(i):
  225. if i!=0:
  226. return i-1
  227. else:
  228. return 0 # We don't want to scale up
  229. def GoogleTile(self, tx, ty, zoom):
  230. "Converts TMS tile coordinates to Google Tile coordinates"
  231. # coordinate origin is moved from bottom-left to top-left corner of the extent
  232. return tx, (2**zoom - 1) - ty
  233. def QuadTree(self, tx, ty, zoom ):
  234. "Converts TMS tile coordinates to Microsoft QuadTree"
  235. quadKey = ""
  236. ty = (2**zoom - 1) - ty
  237. for i in range(zoom, 0, -1):
  238. digit = 0
  239. mask = 1 << (i-1)
  240. if (tx & mask) != 0:
  241. digit += 1
  242. if (ty & mask) != 0:
  243. digit += 2
  244. quadKey += str(digit)
  245. return quadKey
  246. #---------------------
  247. class GlobalGeodetic(object):
  248. """
  249. TMS Global Geodetic Profile
  250. ---------------------------
  251. Functions necessary for generation of global tiles in Plate Carre projection,
  252. EPSG:4326, "unprojected profile".
  253. Such tiles are compatible with Google Earth (as any other EPSG:4326 rasters)
  254. and you can overlay the tiles on top of OpenLayers base map.
  255. Pixel and tile coordinates are in TMS notation (origin [0,0] in bottom-left).
  256. What coordinate conversions do we need for TMS Global Geodetic tiles?
  257. Global Geodetic tiles are using geodetic coordinates (latitude,longitude)
  258. directly as planar coordinates XY (it is also called Unprojected or Plate
  259. Carre). We need only scaling to pixel pyramid and cutting to tiles.
  260. Pyramid has on top level two tiles, so it is not square but rectangle.
  261. Area [-180,-90,180,90] is scaled to 512x256 pixels.
  262. TMS has coordinate origin (for pixels and tiles) in bottom-left corner.
  263. Rasters are in EPSG:4326 and therefore are compatible with Google Earth.
  264. LatLon <-> Pixels <-> Tiles
  265. WGS84 coordinates Pixels in pyramid Tiles in pyramid
  266. lat/lon XY pixels Z zoom XYZ from TMS
  267. EPSG:4326
  268. .----. ----
  269. / \ <-> /--------/ <-> TMS
  270. \ / /--------------/
  271. ----- /--------------------/
  272. WMS, KML Web Clients, Google Earth TileMapService
  273. """
  274. def __init__(self, tileSize = 256):
  275. self.tileSize = tileSize
  276. def LatLonToPixels(self, lat, lon, zoom):
  277. "Converts lat/lon to pixel coordinates in given zoom of the EPSG:4326 pyramid"
  278. res = 180.0 / self.tileSize / 2**zoom
  279. px = (180 + lat) / res
  280. py = (90 + lon) / res
  281. return px, py
  282. def PixelsToTile(self, px, py):
  283. "Returns coordinates of the tile covering region in pixel coordinates"
  284. tx = int( math.ceil( px / float(self.tileSize) ) - 1 )
  285. ty = int( math.ceil( py / float(self.tileSize) ) - 1 )
  286. return tx, ty
  287. def LatLonToTile(self, lat, lon, zoom):
  288. "Returns the tile for zoom which covers given lat/lon coordinates"
  289. px, py = self.LatLonToPixels( lat, lon, zoom)
  290. return self.PixelsToTile(px,py)
  291. def Resolution(self, zoom ):
  292. "Resolution (arc/pixel) for given zoom level (measured at Equator)"
  293. return 180.0 / self.tileSize / 2**zoom
  294. #return 180 / float( 1 << (8+zoom) )
  295. def ZoomForPixelSize(self, pixelSize ):
  296. "Maximal scaledown zoom of the pyramid closest to the pixelSize."
  297. for i in range(MAXZOOMLEVEL):
  298. if pixelSize > self.Resolution(i):
  299. if i!=0:
  300. return i-1
  301. else:
  302. return 0 # We don't want to scale up
  303. def TileBounds(self, tx, ty, zoom):
  304. "Returns bounds of the given tile"
  305. res = 180.0 / self.tileSize / 2**zoom
  306. return (
  307. tx*self.tileSize*res - 180,
  308. ty*self.tileSize*res - 90,
  309. (tx+1)*self.tileSize*res - 180,
  310. (ty+1)*self.tileSize*res - 90
  311. )
  312. def TileLatLonBounds(self, tx, ty, zoom):
  313. "Returns bounds of the given tile in the SWNE form"
  314. b = self.TileBounds(tx, ty, zoom)
  315. return (b[1],b[0],b[3],b[2])
  316. #---------------------
  317. # TODO: Finish Zoomify implemtentation!!!
  318. class Zoomify(object):
  319. """
  320. Tiles compatible with the Zoomify viewer
  321. ----------------------------------------
  322. """
  323. def __init__(self, width, height, tilesize = 256, tileformat='jpg'):
  324. """Initialization of the Zoomify tile tree"""
  325. self.tilesize = tilesize
  326. self.tileformat = tileformat
  327. imagesize = (width, height)
  328. tiles = ( math.ceil( width / tilesize ), math.ceil( height / tilesize ) )
  329. # Size (in tiles) for each tier of pyramid.
  330. self.tierSizeInTiles = []
  331. self.tierSizeInTiles.push( tiles )
  332. # Image size in pixels for each pyramid tierself
  333. self.tierImageSize = []
  334. self.tierImageSize.append( imagesize );
  335. while (imagesize[0] > tilesize or imageSize[1] > tilesize ):
  336. imagesize = (math.floor( imagesize[0] / 2 ), math.floor( imagesize[1] / 2) )
  337. tiles = ( math.ceil( imagesize[0] / tilesize ), math.ceil( imagesize[1] / tilesize ) )
  338. self.tierSizeInTiles.append( tiles )
  339. self.tierImageSize.append( imagesize )
  340. self.tierSizeInTiles.reverse()
  341. self.tierImageSize.reverse()
  342. # Depth of the Zoomify pyramid, number of tiers (zoom levels)
  343. self.numberOfTiers = len(self.tierSizeInTiles)
  344. # Number of tiles up to the given tier of pyramid.
  345. self.tileCountUpToTier = []
  346. self.tileCountUpToTier[0] = 0
  347. for i in range(1, self.numberOfTiers+1):
  348. self.tileCountUpToTier.append(
  349. self.tierSizeInTiles[i-1][0] * self.tierSizeInTiles[i-1][1] + self.tileCountUpToTier[i-1]
  350. )
  351. def tilefilename(self, x, y, z):
  352. """Returns filename for tile with given coordinates"""
  353. tileIndex = x + y * self.tierSizeInTiles[z][0] + self.tileCountUpToTier[z]
  354. return os.path.join("TileGroup%.0f" % math.floor( tileIndex / 256 ),
  355. "%s-%s-%s.%s" % ( z, x, y, self.tileformat))
  356. # =============================================================================
  357. # =============================================================================
  358. # =============================================================================
  359. class GDAL2Tiles(object):
  360. # -------------------------------------------------------------------------
  361. def process(self):
  362. """The main processing function, runs all the main steps of processing"""
  363. # Opening and preprocessing of the input file
  364. self.open_input()
  365. # Generation of main metadata files and HTML viewers
  366. self.generate_metadata()
  367. # Generation of the lowest tiles
  368. self.generate_base_tiles()
  369. # Generation of the overview tiles (higher in the pyramid)
  370. self.generate_overview_tiles()
  371. # -------------------------------------------------------------------------
  372. def error(self, msg, details = "" ):
  373. """Print an error message and stop the processing"""
  374. if details:
  375. self.parser.error(msg + "\n\n" + details)
  376. else:
  377. self.parser.error(msg)
  378. # -------------------------------------------------------------------------
  379. def progressbar(self, complete = 0.0):
  380. """Print progressbar for float value 0..1"""
  381. gdal.TermProgress_nocb(complete)
  382. # -------------------------------------------------------------------------
  383. def __init__(self, arguments ):
  384. """Constructor function - initialization"""
  385. self.input = None
  386. self.output = None
  387. # Tile format
  388. self.tilesize = 256
  389. self.tiledriver = 'PNG'
  390. self.tileext = 'png'
  391. # Should we read bigger window of the input raster and scale it down?
  392. # Note: Modified leter by open_input()
  393. # Not for 'near' resampling
  394. # Not for Wavelet based drivers (JPEG2000, ECW, MrSID)
  395. # Not for 'raster' profile
  396. self.scaledquery = True
  397. # How big should be query window be for scaling down
  398. # Later on reset according the chosen resampling algorightm
  399. self.querysize = 4 * self.tilesize
  400. # Should we use Read on the input file for generating overview tiles?
  401. # Note: Modified later by open_input()
  402. # Otherwise the overview tiles are generated from existing underlying tiles
  403. self.overviewquery = False
  404. # RUN THE ARGUMENT PARSER:
  405. self.optparse_init()
  406. self.options, self.args = self.parser.parse_args(args=arguments)
  407. if not self.args:
  408. self.error("No input file specified")
  409. # POSTPROCESSING OF PARSED ARGUMENTS:
  410. # Workaround for old versions of GDAL
  411. try:
  412. if (self.options.verbose and self.options.resampling == 'near') or gdal.TermProgress_nocb:
  413. pass
  414. except:
  415. self.error("This version of GDAL is not supported. Please upgrade to 1.6+.")
  416. #,"You can try run crippled version of gdal2tiles with parameters: -v -r 'near'")
  417. # Is output directory the last argument?
  418. # Test output directory, if it doesn't exist
  419. if os.path.isdir(self.args[-1]) or ( len(self.args) > 1 and not os.path.exists(self.args[-1])):
  420. self.output = self.args[-1]
  421. self.args = self.args[:-1]
  422. # More files on the input not directly supported yet
  423. if (len(self.args) > 1):
  424. self.error("Processing of several input files is not supported.",
  425. """Please first use a tool like gdal_vrtmerge.py or gdal_merge.py on the files:
  426. gdal_vrtmerge.py -o merged.vrt %s""" % " ".join(self.args))
  427. # TODO: Call functions from gdal_vrtmerge.py directly
  428. self.input = self.args[0]
  429. # Default values for not given options
  430. if not self.output:
  431. # Directory with input filename without extension in actual directory
  432. self.output = os.path.splitext(os.path.basename( self.input ))[0]
  433. if not self.options.title:
  434. self.options.title = os.path.basename( self.input )
  435. if self.options.url and not self.options.url.endswith('/'):
  436. self.options.url += '/'
  437. if self.options.url:
  438. self.options.url += os.path.basename( self.output ) + '/'
  439. # Supported options
  440. self.resampling = None
  441. if self.options.resampling == 'average':
  442. try:
  443. if gdal.RegenerateOverview:
  444. pass
  445. except:
  446. self.error("'average' resampling algorithm is not available.", "Please use -r 'near' argument or upgrade to newer version of GDAL.")
  447. elif self.options.resampling == 'antialias':
  448. try:
  449. if numpy:
  450. pass
  451. except:
  452. self.error("'antialias' resampling algorithm is not available.", "Install PIL (Python Imaging Library) and numpy.")
  453. elif self.options.resampling == 'near':
  454. self.resampling = gdal.GRA_NearestNeighbour
  455. self.querysize = self.tilesize
  456. elif self.options.resampling == 'bilinear':
  457. self.resampling = gdal.GRA_Bilinear
  458. self.querysize = self.tilesize * 2
  459. elif self.options.resampling == 'cubic':
  460. self.resampling = gdal.GRA_Cubic
  461. elif self.options.resampling == 'cubicspline':
  462. self.resampling = gdal.GRA_CubicSpline
  463. elif self.options.resampling == 'lanczos':
  464. self.resampling = gdal.GRA_Lanczos
  465. # User specified zoom levels
  466. self.tminz = None
  467. self.tmaxz = None
  468. if self.options.zoom:
  469. minmax = self.options.zoom.split('-',1)
  470. minmax.extend([''])
  471. min, max = minmax[:2]
  472. self.tminz = int(min)
  473. if max:
  474. self.tmaxz = int(max)
  475. else:
  476. self.tmaxz = min
  477. # KML generation
  478. self.kml = self.options.kml
  479. # Output the results
  480. if self.options.verbose:
  481. print "Options:", self.options
  482. print "Input:", self.input
  483. print "Output:", self.output
  484. print "Cache: %s MB" % (gdal.GetCacheMax() / 1024 / 1024)
  485. print
  486. # -------------------------------------------------------------------------
  487. def optparse_init(self):
  488. """Prepare the option parser for input (argv)"""
  489. from optparse import OptionParser, OptionGroup
  490. usage = "Usage: %prog [options] input_file(s) [output]"
  491. p = OptionParser(usage, version="%prog "+ __version__)
  492. p.add_option("-p", "--profile", dest='profile', type='choice', choices=profile_list,
  493. help="Tile cutting profile (%s) - default 'mercator' (Google Maps compatible)" % ",".join(profile_list))
  494. p.add_option("-r", "--resampling", dest="resampling", type='choice', choices=resampling_list,
  495. help="Resampling method (%s) - default 'average'" % ",".join(resampling_list))
  496. p.add_option('-s', '--s_srs', dest="s_srs", metavar="SRS",
  497. help="The spatial reference system used for the source input data")
  498. p.add_option('-z', '--zoom', dest="zoom",
  499. help="Zoom levels to render (format:'2-5' or '10').")
  500. p.add_option('-e', '--resume', dest="resume", action="store_true",
  501. help="Resume mode. Generate only missing files.")
  502. # TODO: NODATA: ds.GetRasterBand(i).SetNoDataValue( float(null_value) )
  503. # But this would have to be done on in memory VRT - created by CreateCopy()
  504. # Let's do that together with merging of files later...
  505. #p.add_option('-n', '--srcnodata', dest="srcnodata", metavar="NODATA",
  506. # help="NODATA transparency value to assign to the input data")
  507. p.add_option("-v", "--verbose",
  508. action="store_true", dest="verbose",
  509. help="Print status messages to stdout")
  510. # KML options
  511. g = OptionGroup(p, "KML (Google Earth) options", "Options for generated Google Earth SuperOverlay metadata")
  512. g.add_option("-k", "--force-kml", dest='kml', action="store_true",
  513. help="Generate KML for Google Earth - default for 'geodetic' profile and 'raster' in EPSG:4326. For a dataset with different projection use with caution!")
  514. g.add_option("-n", "--no-kml", dest='kml', action="store_false",
  515. help="Avoid automatic generation of KML files for EPSG:4326")
  516. g.add_option("-u", "--url", dest='url',
  517. help="URL address where the generated tiles are going to be published")
  518. p.add_option_group(g)
  519. # HTML options
  520. g = OptionGroup(p, "Web viewer options", "Options for generated HTML viewers a la Google Maps")
  521. g.add_option("-w", "--webviewer", dest='webviewer', type='choice', choices=webviewer_list,
  522. help="Web viewer to generate (%s) - default 'all'" % ",".join(webviewer_list))
  523. g.add_option("-t", "--title", dest='title',
  524. help="Title of the map")
  525. g.add_option("-c", "--copyright", dest='copyright',
  526. help="Copyright for the map")
  527. g.add_option("-g", "--googlekey", dest='googlekey',
  528. help="Google Maps API key from http://code.google.com/apis/maps/signup.html")
  529. g.add_option("-y", "--yahookey", dest='yahookey',
  530. help="Yahoo Application ID from http://developer.yahoo.com/wsregapp/")
  531. p.add_option_group(g)
  532. # TODO: MapFile + TileIndexes per zoom level for efficient MapServer WMS
  533. #g = OptionGroup(p, "WMS MapServer metadata", "Options for generated mapfile and tileindexes for MapServer")
  534. #g.add_option("-i", "--tileindex", dest='wms', action="store_true"
  535. # help="Generate tileindex and mapfile for MapServer (WMS)")
  536. # p.add_option_group(g)
  537. p.set_defaults(verbose=False, profile="mercator", kml=False, url='',
  538. webviewer='all', copyright='', resampling='average', resume=False,
  539. googlekey='INSERT_YOUR_KEY_HERE', yahookey='INSERT_YOUR_YAHOO_APP_ID_HERE')
  540. self.parser = p
  541. # -------------------------------------------------------------------------
  542. def open_input(self):
  543. """Initialization of the input raster, reprojection if necessary"""
  544. gdal.AllRegister()
  545. # Initialize necessary GDAL drivers
  546. self.out_drv = gdal.GetDriverByName( self.tiledriver )
  547. self.mem_drv = gdal.GetDriverByName( 'MEM' )
  548. if not self.out_drv:
  549. raise Exception("The '%s' driver was not found, is it available in this GDAL build?", self.tiledriver)
  550. if not self.mem_drv:
  551. raise Exception("The 'MEM' driver was not found, is it available in this GDAL build?")
  552. # Open the input file
  553. if self.input:
  554. self.in_ds = gdal.Open(self.input, gdal.GA_ReadOnly)
  555. else:
  556. raise Exception("No input file was specified")
  557. if self.options.verbose:
  558. print "Input file:", "( %sP x %sL - %s bands)" % (self.in_ds.RasterXSize, self.in_ds.RasterYSize, self.in_ds.RasterCount)
  559. if not self.in_ds:
  560. # Note: GDAL prints the ERROR message too
  561. self.error("It is not possible to open the input file '%s'." % self.input )
  562. # Read metadata from the input file
  563. if self.in_ds.RasterCount == 0:
  564. self.error( "Input file '%s' has no raster band" % self.input )
  565. if self.in_ds.GetRasterBand(1).GetRasterColorTable():
  566. # TODO: Process directly paletted dataset by generating VRT in memory
  567. self.error( "Please convert this file to RGB/RGBA and run gdal2tiles on the result.",
  568. """From paletted file you can create RGBA file (temp.vrt) by:
  569. gdal_translate -of vrt -expand rgba %s temp.vrt
  570. then run:
  571. gdal2tiles temp.vrt""" % self.input )
  572. #
  573. # Here we should have RGBA input dataset opened in self.in_ds
  574. #
  575. if self.options.verbose:
  576. print "Preprocessed file:", "( %sP x %sL - %s bands)" % (self.in_ds.RasterXSize, self.in_ds.RasterYSize, self.in_ds.RasterCount)
  577. # Spatial Reference System of the input raster
  578. self.in_srs = None
  579. if self.options.s_srs:
  580. self.in_srs = osr.SpatialReference()
  581. self.in_srs.SetFromUserInput(self.options.s_srs)
  582. self.in_srs_wkt = self.in_srs.ExportToWkt()
  583. else:
  584. self.in_srs_wkt = self.in_ds.GetProjection()
  585. if not self.in_srs_wkt and self.in_ds.GetGCPCount() != 0:
  586. self.in_srs_wkt = self.in_ds.GetGCPProjection()
  587. if self.in_srs_wkt:
  588. self.in_srs = osr.SpatialReference()
  589. self.in_srs.ImportFromWkt(self.in_srs_wkt)
  590. #elif self.options.profile != 'raster':
  591. # self.error("There is no spatial reference system info included in the input file.","You should run gdal2tiles with --s_srs EPSG:XXXX or similar.")
  592. # Spatial Reference System of tiles
  593. self.out_srs = osr.SpatialReference()
  594. if self.options.profile == 'mercator':
  595. self.out_srs.ImportFromEPSG(900913)
  596. elif self.options.profile == 'geodetic':
  597. self.out_srs.ImportFromEPSG(4326)
  598. else:
  599. self.out_srs = self.in_srs
  600. # Are the reference systems the same? Reproject if necessary.
  601. self.out_ds = None
  602. if self.options.profile in ('mercator', 'geodetic'):
  603. if (self.in_ds.GetGeoTransform() == (0.0, 1.0, 0.0, 0.0, 0.0, 1.0)) and (self.in_ds.GetGCPCount() == 0):
  604. self.error("There is no georeference - neither affine transformation (worldfile) nor GCPs. You can generate only 'raster' profile tiles.",
  605. "Either gdal2tiles with parameter -p 'raster' or use another GIS software for georeference e.g. gdal_transform -gcp / -a_ullr / -a_srs")
  606. if self.in_srs:
  607. if (self.in_srs.ExportToProj4() != self.out_srs.ExportToProj4()) or (self.in_ds.GetGCPCount() != 0):
  608. # Generation of VRT dataset in tile projection, default 'nearest neighbour' warping
  609. self.out_ds = gdal.AutoCreateWarpedVRT( self.in_ds, self.in_srs_wkt, self.out_srs.ExportToWkt() )
  610. if self.options.verbose:
  611. print "Warping of the raster by AutoCreateWarpedVRT (result saved into 'tiles.vrt')"
  612. self.out_ds.GetDriver().CreateCopy("tiles.vrt", self.out_ds)
  613. # Note: self.in_srs and self.in_srs_wkt contain still the non-warped reference system!!!
  614. else:
  615. self.error("Input file has unknown SRS.", "Use --s_srs ESPG:xyz (or similar) to provide source reference system." )
  616. if self.out_ds and self.options.verbose:
  617. print "Projected file:", "tiles.vrt", "( %sP x %sL - %s bands)" % (self.out_ds.RasterXSize, self.out_ds.RasterYSize, self.out_ds.RasterCount)
  618. if not self.out_ds:
  619. self.out_ds = self.in_ds
  620. #
  621. # Here we should have a raster (out_ds) in the correct Spatial Reference system
  622. #
  623. # Get alpha band (either directly or from NODATA value)
  624. self.alphaband = self.out_ds.GetRasterBand(1).GetMaskBand()
  625. if (self.alphaband.GetMaskFlags() & gdal.GMF_ALPHA) or self.out_ds.RasterCount==4 or self.out_ds.RasterCount==2:
  626. # TODO: Better test for alpha band in the dataset
  627. self.dataBandsCount = self.out_ds.RasterCount - 1
  628. else:
  629. self.dataBandsCount = self.out_ds.RasterCount
  630. # KML test
  631. self.isepsg4326 = False
  632. srs4326 = osr.SpatialReference()
  633. srs4326.ImportFromEPSG(4326)
  634. if self.out_srs and srs4326.ExportToProj4() == self.out_srs.ExportToProj4():
  635. self.kml = True
  636. self.isepsg4326 = True
  637. if self.options.verbose:
  638. print "KML autotest OK!"
  639. # Read the georeference
  640. self.out_gt = self.out_ds.GetGeoTransform()
  641. #originX, originY = self.out_gt[0], self.out_gt[3]
  642. #pixelSize = self.out_gt[1] # = self.out_gt[5]
  643. # Test the size of the pixel
  644. if self.out_gt[1] != (-1 * self.out_gt[5]) and self.options.profile != 'raster':
  645. # TODO: Process corectly coordinates with are have swichted Y axis (display in OpenLayers too)
  646. self.error("Size of the pixel in the output differ for X and Y axes.")
  647. # Report error in case rotation/skew is in geotransform (possible only in 'raster' profile)
  648. if (self.out_gt[2], self.out_gt[4]) != (0,0):
  649. self.error("Georeference of the raster contains rotation or skew. Such raster is not supported. Please use gdalwarp first.")
  650. # TODO: Do the warping in this case automaticaly
  651. #
  652. # Here we expect: pixel is square, no rotation on the raster
  653. #
  654. # Output Bounds - coordinates in the output SRS
  655. self.ominx = self.out_gt[0]
  656. self.omaxx = self.out_gt[0]+self.out_ds.RasterXSize*self.out_gt[1]
  657. self.omaxy = self.out_gt[3]
  658. self.ominy = self.out_gt[3]-self.out_ds.RasterYSize*self.out_gt[1]
  659. # Note: maybe round(x, 14) to avoid the gdal_translate behaviour, when 0 becomes -1e-15
  660. if self.options.verbose:
  661. print "Bounds (output srs):", round(self.ominx, 13), self.ominy, self.omaxx, self.omaxy
  662. #
  663. # Calculating ranges for tiles in different zoom levels
  664. #
  665. if self.options.profile == 'mercator':
  666. self.mercator = GlobalMercator() # from globalmaptiles.py
  667. # Function which generates SWNE in LatLong for given tile
  668. self.tileswne = self.mercator.TileLatLonBounds
  669. # Generate table with min max tile coordinates for all zoomlevels
  670. self.tminmax = range(0,32)
  671. for tz in range(0, 32):
  672. tminx, tminy = self.mercator.MetersToTile( self.ominx, self.ominy, tz )
  673. tmaxx, tmaxy = self.mercator.MetersToTile( self.omaxx, self.omaxy, tz )
  674. # crop tiles extending world limits (+-180,+-90)
  675. tminx, tminy = max(0, tminx), max(0, tminy)
  676. tmaxx, tmaxy = min(2**tz-1, tmaxx), min(2**tz-1, tmaxy)
  677. self.tminmax[tz] = (tminx, tminy, tmaxx, tmaxy)
  678. # TODO: Maps crossing 180E (Alaska?)
  679. # Get the minimal zoom level (map covers area equivalent to one tile)
  680. if self.tminz == None:
  681. self.tminz = self.mercator.ZoomForPixelSize( self.out_gt[1] * max( self.out_ds.RasterXSize, self.out_ds.RasterYSize) / float(self.tilesize) )
  682. # Get the maximal zoom level (closest possible zoom level up on the resolution of raster)
  683. if self.tmaxz == None:
  684. self.tmaxz = self.mercator.ZoomForPixelSize( self.out_gt[1] )
  685. if self.options.verbose:
  686. print "Bounds (latlong):", self.mercator.MetersToLatLon( self.ominx, self.ominy), self.mercator.MetersToLatLon( self.omaxx, self.omaxy)
  687. print 'MinZoomLevel:', self.tminz
  688. print "MaxZoomLevel:", self.tmaxz, "(", self.mercator.Resolution( self.tmaxz ),")"
  689. if self.options.profile == 'geodetic':
  690. self.geodetic = GlobalGeodetic() # from globalmaptiles.py
  691. # Function which generates SWNE in LatLong for given tile
  692. self.tileswne = self.geodetic.TileLatLonBounds
  693. # Generate table with min max tile coordinates for all zoomlevels
  694. self.tminmax = range(0,32)
  695. for tz in range(0, 32):
  696. tminx, tminy = self.geodetic.LatLonToTile( self.ominx, self.ominy, tz )
  697. tmaxx, tmaxy = self.geodetic.LatLonToTile( self.omaxx, self.omaxy, tz )
  698. # crop tiles extending world limits (+-180,+-90)
  699. tminx, tminy = max(0, tminx), max(0, tminy)
  700. tmaxx, tmaxy = min(2**(tz+1)-1, tmaxx), min(2**tz-1, tmaxy)
  701. self.tminmax[tz] = (tminx, tminy, tmaxx, tmaxy)
  702. # TODO: Maps crossing 180E (Alaska?)
  703. # Get the maximal zoom level (closest possible zoom level up on the resolution of raster)
  704. if self.tminz == None:
  705. self.tminz = self.geodetic.ZoomForPixelSize( self.out_gt[1] * max( self.out_ds.RasterXSize, self.out_ds.RasterYSize) / float(self.tilesize) )
  706. # Get the maximal zoom level (closest possible zoom level up on the resolution of raster)
  707. if self.tmaxz == None:
  708. self.tmaxz = self.geodetic.ZoomForPixelSize( self.out_gt[1] )
  709. if self.options.verbose:
  710. print "Bounds (latlong):", self.ominx, self.ominy, self.omaxx, self.omaxy
  711. if self.options.profile == 'raster':
  712. log2 = lambda x: math.log10(x) / math.log10(2) # log2 (base 2 logarithm)
  713. self.nativezoom = int(max( math.ceil(log2(self.out_ds.RasterXSize/float(self.tilesize))),
  714. math.ceil(log2(self.out_ds.RasterYSize/float(self.tilesize)))))
  715. if self.options.verbose:
  716. print "Native zoom of the raster:", self.nativezoom
  717. # Get the minimal zoom level (whole raster in one tile)
  718. if self.tminz == None:
  719. self.tminz = 0
  720. # Get the maximal zoom level (native resolution of the raster)
  721. if self.tmaxz == None:
  722. self.tmaxz = self.nativezoom
  723. # Generate table with min max tile coordinates for all zoomlevels
  724. self.tminmax = range(0, self.tmaxz+1)
  725. self.tsize = range(0, self.tmaxz+1)
  726. for tz in range(0, self.tmaxz+1):
  727. tsize = 2.0**(self.nativezoom-tz)*self.tilesize
  728. tminx, tminy = 0, 0
  729. tmaxx = int(math.ceil( self.out_ds.RasterXSize / tsize )) - 1
  730. tmaxy = int(math.ceil( self.out_ds.RasterYSize / tsize )) - 1
  731. self.tsize[tz] = math.ceil(tsize)
  732. self.tminmax[tz] = (tminx, tminy, tmaxx, tmaxy)
  733. # Function which generates SWNE in LatLong for given tile
  734. if self.kml and self.in_srs_wkt:
  735. self.ct = osr.CoordinateTransformation(self.in_srs, srs4326)
  736. def rastertileswne(x,y,z):
  737. pixelsizex = (2**(self.tmaxz-z) * self.out_gt[1]) # X-pixel size in level
  738. pixelsizey = (2**(self.tmaxz-z) * self.out_gt[1]) # Y-pixel size in level (usually -1*pixelsizex)
  739. west = self.out_gt[0] + x*self.tilesize*pixelsizex
  740. east = west + self.tilesize*pixelsizex
  741. north = self.out_gt[3] - (self.tminmax[z][3]-y)*self.tilesize*pixelsizey
  742. south = north - self.tilesize*pixelsizey
  743. if not self.isepsg4326:
  744. # Transformation to EPSG:4326 (WGS84 datum)
  745. west, south = self.ct.TransformPoint(west, south)[:2]
  746. east, north = self.ct.TransformPoint(east, north)[:2]
  747. return south, west, north, east
  748. self.tileswne = rastertileswne
  749. else:
  750. self.tileswne = lambda x, y, z: (0,0,0,0)
  751. # -------------------------------------------------------------------------
  752. def generate_metadata(self):
  753. """Generation of main metadata files and HTML viewers (metadata related to particular tiles are generated during the tile processing)."""
  754. if not os.path.exists(self.output):
  755. os.makedirs(self.output)
  756. if self.options.profile == 'mercator':
  757. south, west = self.mercator.MetersToLatLon( self.ominx, self.ominy)
  758. north, east = self.mercator.MetersToLatLon( self.omaxx, self.omaxy)
  759. south, west = max(-85.05112878, south), max(-180.0, west)
  760. north, east = min(85.05112878, north), min(180.0, east)
  761. self.swne = (south, west, north, east)
  762. # Generate googlemaps.html
  763. if self.options.webviewer in ('all','google') and self.options.profile == 'mercator':
  764. if not self.options.resume or not os.path.exists(os.path.join(self.output, 'googlemaps.html')):
  765. f = open(os.path.join(self.output, 'googlemaps.html'), 'w')
  766. f.write( self.generate_googlemaps() )
  767. f.close()
  768. # Generate openlayers.html
  769. if self.options.webviewer in ('all','openlayers'):
  770. if not self.options.resume or not os.path.exists(os.path.join(self.output, 'openlayers.html')):
  771. f = open(os.path.join(self.output, 'openlayers.html'), 'w')
  772. f.write( self.generate_openlayers() )
  773. f.close()
  774. elif self.options.profile == 'geodetic':
  775. west, south = self.ominx, self.ominy
  776. east, north = self.omaxx, self.omaxy
  777. south, west = max(-90.0, south), max(-180.0, west)
  778. north, east = min(90.0, north), min(180.0, east)
  779. self.swne = (south, west, north, east)
  780. # Generate openlayers.html
  781. if self.options.webviewer in ('all','openlayers'):
  782. if not self.options.resume or not os.path.exists(os.path.join(self.output, 'openlayers.html')):
  783. f = open(os.path.join(self.output, 'openlayers.html'), 'w')
  784. f.write( self.generate_openlayers() )
  785. f.close()
  786. elif self.options.profile == 'raster':
  787. west, south = self.ominx, self.ominy
  788. east, north = self.omaxx, self.omaxy
  789. self.swne = (south, west, north, east)
  790. # Generate openlayers.html
  791. if self.options.webviewer in ('all','openlayers'):
  792. if not self.options.resume or not os.path.exists(os.path.join(self.output, 'openlayers.html')):
  793. f = open(os.path.join(self.output, 'openlayers.html'), 'w')
  794. f.write( self.generate_openlayers() )
  795. f.close()
  796. # Generate tilemapresource.xml.
  797. if not self.options.resume or not os.path.exists(os.path.join(self.output, 'tilemapresource.xml')):
  798. f = open(os.path.join(self.output, 'tilemapresource.xml'), 'w')
  799. f.write( self.generate_tilemapresource())
  800. f.close()
  801. if self.kml:
  802. # TODO: Maybe problem for not automatically generated tminz
  803. # The root KML should contain links to all tiles in the tminz level
  804. children = []
  805. xmin, ymin, xmax, ymax = self.tminmax[self.tminz]
  806. for x in range(xmin, xmax+1):
  807. for y in range(ymin, ymax+1):
  808. children.append( [ x, y, self.tminz ] )
  809. # Generate Root KML
  810. if self.kml:
  811. if not self.options.resume or not os.path.exists(os.path.join(self.output, 'doc.kml')):
  812. f = open(os.path.join(self.output, 'doc.kml'), 'w')
  813. f.write( self.generate_kml( None, None, None, children) )
  814. f.close()
  815. # -------------------------------------------------------------------------
  816. def generate_base_tiles(self):
  817. """Generation of the base tiles (the lowest in the pyramid) directly from the input raster"""
  818. print "Generating Base Tiles:"
  819. if self.options.verbose:
  820. #mx, my = self.out_gt[0], self.out_gt[3] # OriginX, OriginY
  821. #px, py = self.mercator.MetersToPixels( mx, my, self.tmaxz)
  822. #print "Pixel coordinates:", px, py, (mx, my)
  823. print
  824. print "Tiles generated from the max zoom level:"
  825. print "----------------------------------------"
  826. print
  827. # Set the bounds
  828. tminx, tminy, tmaxx, tmaxy = self.tminmax[self.tmaxz]
  829. # Just the center tile
  830. #tminx = tminx+ (tmaxx - tminx)/2
  831. #tminy = tminy+ (tmaxy - tminy)/2
  832. #tmaxx = tminx
  833. #tmaxy = tminy
  834. ds = self.out_ds
  835. tilebands = self.dataBandsCount + 1
  836. querysize = self.querysize
  837. if self.options.verbose:
  838. print "dataBandsCount: ", self.dataBandsCount
  839. print "tilebands: ", tilebands
  840. #print tminx, tminy, tmaxx, tmaxy
  841. tcount = (1+abs(tmaxx-tminx)) * (1+abs(tmaxy-tminy))
  842. #print tcount
  843. ti = 0
  844. tz = self.tmaxz
  845. for ty in range(tmaxy, tminy-1, -1): #range(tminy, tmaxy+1):
  846. for tx in range(tminx, tmaxx+1):
  847. ti += 1
  848. tilefilename = os.path.join(self.output, str(tz), str(tx), "%s.%s" % (ty, self.tileext))
  849. if self.options.verbose:
  850. print ti,'/',tcount, tilefilename #, "( TileMapService: z / x / y )"
  851. if self.options.resume and os.path.exists(tilefilename):
  852. if self.options.verbose:
  853. print "Tile generation skiped because of --resume"
  854. else:
  855. self.progressbar( ti / float(tcount) )
  856. continue
  857. # Create directories for the tile
  858. if not os.path.exists(os.path.dirname(tilefilename)):
  859. os.makedirs(os.path.dirname(tilefilename))
  860. if self.options.profile == 'mercator':
  861. # Tile bounds in EPSG:900913
  862. b = self.mercator.TileBounds(tx, ty, tz)
  863. elif self.options.profile == 'geodetic':
  864. b = self.geodetic.TileBounds(tx, ty, tz)
  865. #print "\tgdalwarp -ts 256 256 -te %s %s %s %s %s %s_%s_%s.tif" % ( b[0], b[1], b[2], b[3], "tiles.vrt", tz, tx, ty)
  866. # Don't scale up by nearest neighbour, better change the querysize
  867. # to the native resolution (and return smaller query tile) for scaling
  868. if self.options.profile in ('mercator','geodetic'):
  869. rb, wb = self.geo_query( ds, b[0], b[3], b[2], b[1])
  870. nativesize = wb[0]+wb[2] # Pixel size in the raster covering query geo extent
  871. if self.options.verbose:
  872. print "\tNative Extent (querysize",nativesize,"): ", rb, wb
  873. # Tile bounds in raster coordinates for ReadRaster query
  874. rb, wb = self.geo_query( ds, b[0], b[3], b[2], b[1], querysize=querysize)
  875. rx, ry, rxsize, rysize = rb
  876. wx, wy, wxsize, wysize = wb
  877. else: # 'raster' profile:
  878. tsize = int(self.tsize[tz]) # tilesize in raster coordinates for actual zoom
  879. xsize = self.out_ds.RasterXSize # size of the raster in pixels
  880. ysize = self.out_ds.RasterYSize
  881. if tz >= self.nativezoom:
  882. querysize = self.tilesize # int(2**(self.nativezoom-tz) * self.tilesize)
  883. rx = (tx) * tsize
  884. rxsize = 0
  885. if tx == tmaxx:
  886. rxsize = xsize % tsize
  887. if rxsize == 0:
  888. rxsize = tsize
  889. rysize = 0
  890. if ty == tmaxy:
  891. rysize = ysize % tsize
  892. if rysize == 0:
  893. rysize = tsize
  894. ry = ysize - (ty * tsize) - rysize
  895. wx, wy = 0, 0
  896. wxsize, wysize = int(rxsize/float(tsize) * self.tilesize), int(rysize/float(tsize) * self.tilesize)
  897. if wysize != self.tilesize:
  898. wy = self.tilesize - wysize
  899. if self.options.verbose:
  900. print "\tReadRaster Extent: ", (rx, ry, rxsize, rysize), (wx, wy, wxsize, wysize)
  901. # Query is in 'nearest neighbour' but can be bigger in then the tilesize
  902. # We scale down the query to the tilesize by supplied algorithm.
  903. # Tile dataset in memory
  904. dstile = self.mem_drv.Create('', self.tilesize, self.tilesize, tilebands)
  905. data = ds.ReadRaster(rx, ry, rxsize, rysize, wxsize, wysize, band_list=range(1,self.dataBandsCount+1))
  906. alpha = self.alphaband.ReadRaster(rx, ry, rxsize, rysize, wxsize, wysize)
  907. if self.tilesize == querysize:
  908. # Use the ReadRaster result directly in tiles ('nearest neighbour' query)
  909. dstile.WriteRaster(wx, wy, wxsize, wysize, data, band_list=range(1,self.dataBandsCount+1))
  910. dstile.WriteRaster(wx, wy, wxsize, wysize, alpha, band_list=[tilebands])
  911. # Note: For source drivers based on WaveLet compression (JPEG2000, ECW, MrSID)
  912. # the ReadRaster function returns high-quality raster (not ugly nearest neighbour)
  913. # TODO: Use directly 'near' for WaveLet files
  914. else:
  915. # Big ReadRaster query in memory scaled to the tilesize - all but 'near' algo
  916. dsquery = self.mem_drv.Create('', querysize, querysize, tilebands)
  917. # TODO: fill the null value in case a tile without alpha is produced (now only png tiles are supported)
  918. #for i in range(1, tilebands+1):
  919. # dsquery.GetRasterBand(1).Fill(tilenodata)
  920. dsquery.WriteRaster(wx, wy, wxsize, wysize, data, band_list=range(1,self.dataBandsCount+1))
  921. dsquery.WriteRaster(wx, wy, wxsize, wysize, alpha, band_list=[tilebands])
  922. self.scale_query_to_tile(dsquery, dstile, tilefilename)
  923. del dsquery
  924. del data
  925. if self.options.resampling != 'antialias':
  926. # Write a copy of tile to png/jpg
  927. self.out_drv.CreateCopy(tilefilename, dstile, strict=0)
  928. del dstile
  929. # Create a KML file for this tile.
  930. if self.kml:
  931. kmlfilename = os.path.join(self.output, str(tz), str(tx), '%d.kml' % ty)
  932. if not self.options.resume or not os.path.exists(kmlfilename):
  933. f = open( kmlfilename, 'w')
  934. f.write( self.generate_kml( tx, ty, tz ))
  935. f.close()
  936. if not self.options.verbose:
  937. self.progressbar( ti / float(tcount) )
  938. # -------------------------------------------------------------------------
  939. def generate_overview_tiles(self):
  940. """Generation of the overview tiles (higher in the pyramid) based on existing tiles"""
  941. print "Generating Overview Tiles:"
  942. tilebands = self.dataBandsCount + 1
  943. # Usage of existing tiles: from 4 underlying tiles generate one as overview.
  944. tcount = 0
  945. for tz in range(self.tmaxz-1, self.tminz-1, -1):
  946. tminx, tminy, tmaxx, tmaxy = self.tminmax[tz]
  947. tcount += (1+abs(tmaxx-tminx)) * (1+abs(tmaxy-tminy))
  948. ti = 0
  949. # querysize = tilesize * 2
  950. for tz in range(self.tmaxz-1, self.tminz-1, -1):
  951. tminx, tminy, tmaxx, tmaxy = self.tminmax[tz]
  952. for ty in range(tmaxy, tminy-1, -1): #range(tminy, tmaxy+1):
  953. for tx in range(tminx, tmaxx+1):
  954. ti += 1
  955. tilefilename = os.path.join( self.output, str(tz), str(tx), "%s.%s" % (ty, self.tileext) )
  956. if self.options.verbose:
  957. print ti,'/',tcount, tilefilename #, "( TileMapService: z / x / y )"
  958. if self.options.resume and os.path.exists(tilefilename):
  959. if self.options.verbose:
  960. print "Tile generation skiped because of --resume"
  961. else:
  962. self.progressbar( ti / float(tcount) )
  963. continue
  964. # Create directories for the tile
  965. if not os.path.exists(os.path.dirname(tilefilename)):
  966. os.makedirs(os.path.dirname(tilefilename))
  967. dsquery = self.mem_drv.Create('', 2*self.tilesize, 2*self.tilesize, tilebands)
  968. # TODO: fill the null value
  969. #for i in range(1, tilebands+1):
  970. # dsquery.GetRasterBand(1).Fill(tilenodata)
  971. dstile = self.mem_drv.Create('', self.tilesize, self.tilesize, tilebands)
  972. # TODO: Implement more clever walking on the tiles with cache functionality
  973. # probably walk should start with reading of four tiles from top left corner
  974. # Hilbert curve...
  975. children = []
  976. # Read the tiles and write them to query window
  977. for y in range(2*ty,2*ty+2):
  978. for x in range(2*tx,2*tx+2):
  979. minx, miny, maxx, maxy = self.tminmax[tz+1]
  980. if x >= minx and x <= maxx and y >= miny and y <= maxy:
  981. dsquerytile = gdal.Open( os.path.join( self.output, str(tz+1), str(x), "%s.%s" % (y, self.tileext)), gdal.GA_ReadOnly)
  982. if (ty==0 and y==1) or (ty!=0 and (y % (2*ty)) != 0):
  983. tileposy = 0
  984. else:
  985. tileposy = self.tilesize
  986. if tx:
  987. tileposx = x % (2*tx) * self.tilesize
  988. elif tx==0 and x==1:
  989. tileposx = self.tilesize
  990. else:
  991. tileposx = 0
  992. dsquery.WriteRaster( tileposx, tileposy, self.tilesize, self.tilesize,
  993. dsquerytile.ReadRaster(0,0,self.tilesize,self.tilesize),
  994. band_list=range(1,tilebands+1))
  995. children.append( [x, y, tz+1] )
  996. self.scale_query_to_tile(dsquery, dstile, tilefilename)
  997. # Write a copy of tile to png/jpg
  998. self.out_drv.CreateCopy(tilefilename, dstile, strict=0)
  999. if self.options.verbose:
  1000. print "\tbuild from zoom", tz+1," tiles:", (2*tx, 2*ty), (2*tx+1, 2*ty),(2*tx, 2*ty+1), (2*tx+1, 2*ty+1)
  1001. # Create a KML file for this tile.
  1002. if self.kml:
  1003. f = open( os.path.join(self.output, '%d/%d/%d.kml' % (tz, tx, ty)), 'w')
  1004. f.write( self.generate_kml( tx, ty, tz, children ) )
  1005. f.close()
  1006. if not self.options.verbose:
  1007. self.progressbar( ti / float(tcount) )
  1008. # -------------------------------------------------------------------------
  1009. def geo_query(self, ds, ulx, uly, lrx, lry, querysize = 0):
  1010. """For given dataset and query in cartographic coordinates
  1011. returns parameters for ReadRaster() in raster coordinates and
  1012. x/y shifts (for border tiles). If the querysize is not given, the
  1013. extent is returned in the native resolution of dataset ds."""
  1014. geotran = ds.GetGeoTransform()
  1015. rx= int((ulx - geotran[0]) / geotran[1] + 0.001)
  1016. ry= int((uly - geotran[3]) / geotran[5] + 0.001)
  1017. rxsize= int((lrx - ulx) / geotran[1] + 0.5)
  1018. rysize= int((lry - uly) / geotran[5] + 0.5)
  1019. if not querysize:
  1020. wxsize, wysize = rxsize, rysize
  1021. else:
  1022. wxsize, wysize = querysize, querysize
  1023. # Coordinates should not go out of the bounds of the raster
  1024. wx = 0
  1025. if rx < 0:
  1026. rxshift = abs(rx)
  1027. wx = int( wxsize * (float(rxshift) / rxsize) )
  1028. wxsize = wxsize - wx
  1029. rxsize = rxsize - int( rxsize * (float(rxshift) / rxsize) )
  1030. rx = 0
  1031. if rx+rxsize > ds.RasterXSize:
  1032. wxsize = int( wxsize * (float(ds.RasterXSize - rx) / rxsize) )
  1033. rxsize = ds.RasterXSize - rx
  1034. wy = 0
  1035. if ry < 0:
  1036. ryshift = abs(ry)
  1037. wy = int( wysize * (float(ryshift) / rysize) )
  1038. wysize = wysize - wy
  1039. rysize = rysize - int( rysize * (float(ryshift) / rysize) )
  1040. ry = 0
  1041. if ry+rysize > ds.RasterYSize:
  1042. wysize = int( wysize * (float(ds.RasterYSize - ry) / rysize) )
  1043. rysize = ds.RasterYSize - ry
  1044. return (rx, ry, rxsize, rysize), (wx, wy, wxsize, wysize)
  1045. # -------------------------------------------------------------------------
  1046. def scale_query_to_tile(self, dsquery, dstile, tilefilename=''):
  1047. """Scales down query dataset to the tile dataset"""
  1048. querysize = dsquery.RasterXSize
  1049. tilesize = dstile.RasterXSize
  1050. tilebands = dstile.RasterCount
  1051. if self.options.resampling == 'average':
  1052. # Function: gdal.RegenerateOverview()
  1053. for i in range(1,tilebands+1):
  1054. # Black border around NODATA
  1055. #if i != 4:
  1056. # dsquery.GetRasterBand(i).SetNoDataValue(0)
  1057. res = gdal.RegenerateOverview( dsquery.GetRasterBand(i),
  1058. dstile.GetRasterBand(i), 'average' )
  1059. if res != 0:
  1060. self.error("RegenerateOverview() failed on %s, error %d" % (tilefilename, res))
  1061. elif self.options.resampling == 'antialias':
  1062. # Scaling by PIL (Python Imaging Library) - improved Lanczos
  1063. array = numpy.zeros((querysize, querysize, tilebands), numpy.uint8)
  1064. for i in range(tilebands):
  1065. array[:,:,i] = gdalarray.BandReadAsArray(dsquery.GetRasterBand(i+1), 0, 0, querysize, querysize)
  1066. if tilebands == 4:
  1067. im = Image.fromarray(array, 'RGBA')
  1068. else:
  1069. im = Image.fromarray(array, 'RGB')
  1070. im1 = im.resize((tilesize,tilesize), Image.ANTIALIAS)
  1071. im1.save(tilefilename,self.tiledriver)
  1072. else:
  1073. # Other algorithms are implemented by gdal.ReprojectImage().
  1074. dsquery.SetGeoTransform( (0.0, tilesize / float(querysize), 0.0, 0.0, 0.0, tilesize / float(querysize)) )
  1075. dstile.SetGeoTransform( (0.0, 1.0, 0.0, 0.0, 0.0, 1.0) )
  1076. res = gdal.ReprojectImage(dsquery, dstile, None, None, self.resampling)
  1077. if res != 0:
  1078. self.error("ReprojectImage() failed on %s, error %d" % (tilefilename, res))
  1079. # -------------------------------------------------------------------------
  1080. def generate_tilemapresource(self):
  1081. """
  1082. Template for tilemapresource.xml. Returns filled string. Expected variables:
  1083. title, north, south, east, west, isepsg4326, projection, publishurl,
  1084. zoompixels, tilesize, tileformat, profile
  1085. """
  1086. args = {}
  1087. args['title'] = self.options.title
  1088. args['south'], args['west'], args['north'], args['east'] = self.swne
  1089. args['tilesize'] = self.tilesize
  1090. args['tileformat'] = self.tileext
  1091. args['publishurl'] = self.options.url
  1092. args['profile'] = self.options.profile
  1093. if self.options.profile == 'mercator':
  1094. args['srs'] = "EPSG:900913"
  1095. elif self.options.profile == 'geodetic':
  1096. args['srs'] = "EPSG:4326"
  1097. elif self.options.s_srs:
  1098. args['srs'] = self.options.s_srs
  1099. elif self.out_srs:
  1100. args['srs'] = self.out_srs.ExportToWkt()
  1101. else:
  1102. args['srs'] = ""
  1103. s = """<?xml version="1.0" encoding="utf-8"?>
  1104. <TileMap version="1.0.0" tilemapservice="http://tms.osgeo.org/1.0.0">
  1105. <Title>%(title)s</Title>
  1106. <Abstract></Abstract>
  1107. <SRS>%(srs)s</SRS>
  1108. <BoundingBox minx="%(south).14f" miny="%(west).14f" maxx="%(north).14f" maxy="%(east).14f"/>
  1109. <Origin x="%(south).14f" y="%(west).14f"/>
  1110. <TileFormat width="%(tilesize)d" height="%(tilesize)d" mime-type="image/%(tileformat)s" extension="%(tileformat)s"/>
  1111. <TileSets profile="%(profile)s">
  1112. """ % args
  1113. for z in range(self.tminz, self.tmaxz+1):
  1114. if self.options.profile == 'raster':
  1115. s += """ <TileSet href="%s%d" units-per-pixel="%.14f" order="%d"/>\n""" % (args['publishurl'], z, (2**(self.nativezoom-z) * self.out_gt[1]), z)
  1116. elif self.options.profile == 'mercator':
  1117. s += """ <TileSet href="%s%d" units-per-pixel="%.14f" order="%d"/>\n""" % (args['publishurl'], z, 156543.0339/2**z, z)
  1118. elif self.options.profile == 'geodetic':
  1119. s += """ <TileSet href="%s%d" units-per-pixel="%.14f" order="%d"/>\n""" % (args['publishurl'], z, 0.703125/2**z, z)
  1120. s += """ </TileSets>
  1121. </TileMap>
  1122. """
  1123. return s
  1124. # -------------------------------------------------------------------------
  1125. def generate_kml(self, tx, ty, tz, children = [], **args ):
  1126. """
  1127. Template for the KML. Returns filled string.
  1128. """
  1129. args['tx'], args['ty'], args['tz'] = tx, ty, tz
  1130. args['tileformat'] = self.tileext
  1131. if not args.has_key('tilesize'):
  1132. args['tilesize'] = self.tilesize
  1133. if not args.has_key('minlodpixels'):
  1134. args['minlodpixels'] = int( args['tilesize'] / 2 ) # / 2.56) # default 128
  1135. if not args.has_key('maxlodpixels'):
  1136. args['maxlodpixels'] = int( args['tilesize'] * 8 ) # 1.7) # default 2048 (used to be -1)
  1137. if children == []:
  1138. args['maxlodpixels'] = -1
  1139. if tx==None:
  1140. tilekml = False
  1141. args['title'] = self.options.title
  1142. else:
  1143. tilekml = True
  1144. args['title'] = "%d/%d/%d.kml" % (tz, tx, ty)
  1145. args['south'], args['west'], args['north'], args['east'] = self.tileswne(tx, ty, tz)
  1146. url = self.options.url
  1147. if not url:
  1148. if tilekml:
  1149. url = "../../"
  1150. else:
  1151. url = ""
  1152. s = """<?xml version="1.0" encoding="utf-8"?>
  1153. <kml xmlns="http://earth.google.com/kml/2.1">
  1154. <Document>
  1155. <Name>%(title)s</Name>
  1156. <Description></Description>
  1157. <Style>
  1158. <ListStyle id="hideChildren">
  1159. <listItemType>checkHideChildren</listItemType>
  1160. </ListStyle>
  1161. </Style>""" % args
  1162. if tilekml:
  1163. s += """
  1164. <Region>
  1165. <Lod>
  1166. <minLodPixels>%(minlodpixels)d</minLodPixels>
  1167. <maxLodPixels>%(maxlodpixels)d</maxLodPixels>
  1168. </Lod>
  1169. <LatLonAltBox>
  1170. <north>%(north).14f</north>
  1171. <south>%(south).14f</south>
  1172. <east>%(east).14f</east>
  1173. <west>%(west).14f</west>
  1174. </LatLonAltBox>
  1175. </Region>
  1176. <GroundOverlay>
  1177. <drawOrder>%(tz)d</drawOrder>
  1178. <Icon>
  1179. <href>%(ty)d.%(tileformat)s</href>
  1180. </Icon>
  1181. <LatLonBox>
  1182. <north>%(north).14f</north>
  1183. <south>%(south).14f</south>
  1184. <east>%(east).14f</east>
  1185. <west>%(west).14f</west>
  1186. </LatLonBox>
  1187. </GroundOverlay>
  1188. """ % args
  1189. for cx, cy, cz in children:
  1190. csouth, cwest, cnorth, ceast = self.tileswne(cx, cy, cz)
  1191. s += """
  1192. <NetworkLink>
  1193. <name>%d/%d/%d.%s</name>
  1194. <Region>
  1195. <Lod>
  1196. <minLodPixels>%d</minLodPixels>
  1197. <maxLodPixels>-1</maxLodPixels>
  1198. </Lod>
  1199. <LatLonAltBox>
  1200. <north>%.14f</north>
  1201. <south>%.14f</south>
  1202. <east>%.14f</east>
  1203. <west>%.14f</west>
  1204. </LatLonAltBox>
  1205. </Region>
  1206. <Link>
  1207. <href>%s%d/%d/%d.kml</href>
  1208. <viewRefreshMode>onRegion</viewRefreshMode>
  1209. <viewFormat/>
  1210. </Link>
  1211. </NetworkLink>
  1212. """ % (cz, cx, cy, args['tileformat'], args['minlodpixels'], cnorth, csouth, ceast, cwest, url, cz, cx, cy)
  1213. s += """ </Document>
  1214. </kml>
  1215. """
  1216. return s
  1217. # -------------------------------------------------------------------------
  1218. def generate_googlemaps(self):
  1219. """
  1220. Template for googlemaps.html implementing Overlay of tiles for 'mercator' profile.
  1221. It returns filled string. Expected variables:
  1222. title, googlemapskey, north, south, east, west, minzoom, maxzoom, tilesize, tileformat, publishurl
  1223. """
  1224. args = {}
  1225. args['title'] = self.options.title
  1226. args['googlemapskey'] = self.options.googlekey
  1227. args['south'], args['west'], args['north'], args['east'] = self.swne
  1228. args['minzoom'] = self.tminz
  1229. args['maxzoom'] = self.tmaxz
  1230. args['tilesize'] = self.tilesize
  1231. args['tileformat'] = self.tileext
  1232. args['publishurl'] = self.options.url
  1233. args['copyright'] = self.options.copyright
  1234. s = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  1235. <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
  1236. <head>
  1237. <title>%(title)s</title>
  1238. <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  1239. <meta http-equiv='imagetoolbar' content='no'/>
  1240. <style type="text/css"> v\:* {behavior:url(#default#VML);}
  1241. html, body { overflow: hidden; padding: 0; height: 100%%; width: 100%%; font-family: 'Lucida Grande',Geneva,Arial,Verdana,sans-serif; }
  1242. body { margin: 10px; background: #fff; }
  1243. h1 { margin: 0; padding: 6px; border:0; font-size: 20pt; }
  1244. #header { height: 43px; padding: 0; background-color: #eee; border: 1px solid #888; }
  1245. #subheader { height: 12px; text-align: right; font-size: 10px; color: #555;}
  1246. #map { height: 95%%; border: 1px solid #888; }
  1247. </style>
  1248. <script src='http://maps.google.com/maps?file=api&amp;v=2&amp;key=%(googlemapskey)s' type='text/javascript'></script>
  1249. <script type="text/javascript">
  1250. //<![CDATA[
  1251. /*
  1252. * Constants for given map
  1253. * TODO: read it from tilemapresource.xml
  1254. */
  1255. var mapBounds = new GLatLngBounds(new GLatLng(%(south)s, %(west)s), new GLatLng(%(north)s, %(east)s));
  1256. var mapMinZoom = %(minzoom)s;
  1257. var mapMaxZoom = %(maxzoom)s;
  1258. var opacity = 0.75;
  1259. var map;
  1260. var hybridOverlay;
  1261. /*
  1262. * Create a Custom Opacity GControl
  1263. * http://www.maptiler.org/google-maps-overlay-opacity-control/
  1264. */
  1265. var CTransparencyLENGTH = 58;
  1266. // maximum width that the knob can move (slide width minus knob width)
  1267. function CTransparencyControl( overlay ) {
  1268. this.overlay = overlay;
  1269. this.opacity = overlay.getTileLayer().getOpacity();
  1270. }
  1271. CTransparencyControl.prototype = new GControl();
  1272. // This function positions the slider to match the specified opacity
  1273. CTransparencyControl.prototype.setSlider = function(pos) {
  1274. var left = Math.round((CTransparencyLENGTH*pos));
  1275. this.slide.left = left;
  1276. this.knob.style.left = left+"px";
  1277. }
  1278. // This function reads the slider and sets the overlay opacity level
  1279. CTransparencyControl.prototype.setOpacity = function() {
  1280. // set the global variable
  1281. opacity = this.slide.left/CTransparencyLENGTH;
  1282. this.map.clearOverlays();
  1283. this.map.addOverlay(this.overlay, { zPriority: 0 });
  1284. if (this.map.getCurrentMapType() == G_HYBRID_MAP) {
  1285. this.map.addOverlay(hybridOverlay);
  1286. }
  1287. }
  1288. // This gets called by the API when addControl(new CTransparencyControl())
  1289. CTransparencyControl.prototype.initialize = function(map) {
  1290. var that=this;
  1291. this.map = map;
  1292. // Is this MSIE, if so we need to use AlphaImageLoader
  1293. var agent = navigator.userAgent.toLowerCase();
  1294. if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){this.ie = true} else {this.ie = false}
  1295. // create the background graphic as a <div> containing an image
  1296. var container = document.createElement("div");
  1297. container.style.width="70px";
  1298. container.style.height="21px";
  1299. // Handle transparent PNG files in MSIE
  1300. if (this.ie) {
  1301. var loader = "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://www.maptiler.org/img/opacity-slider.png', sizingMethod='crop');";
  1302. container.innerHTML = '<div style="height:21px; width:70px; ' +loader+ '" ></div>';
  1303. } else {
  1304. container.innerHTML = '<div style="height:21px; width:70px; background-image: url(http://www.maptiler.org/img/opacity-slider.png)" ></div>';
  1305. }
  1306. // create the knob as a GDraggableObject
  1307. // Handle transparent PNG files in MSIE
  1308. if (this.ie) {
  1309. var loader = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://www.maptiler.org/img/opacity-slider.png', sizingMethod='crop');";
  1310. this.knob = document.createElement("div");
  1311. this.knob.style.height="21px";
  1312. this.knob.style.width="13px";
  1313. this.knob.style.overflow="hidden";
  1314. this.knob_img = document.createElement("div");
  1315. this.knob_img.style.height="21px";
  1316. this.knob_img.style.width="83px";
  1317. this.knob_img.style.filter=loader;
  1318. this.knob_img.style.position="relative";
  1319. this.knob_img.style.left="-70px";
  1320. this.knob.appendChild(this.knob_img);
  1321. } else {
  1322. this.knob = document.createElement("div");
  1323. this.knob.style.height="21px";
  1324. this.knob.style.width="13px";
  1325. this.knob.style.backgroundImage="url(http://www.maptiler.org/img/opacity-slider.png)";
  1326. this.knob.style.backgroundPosition="-70px 0px";
  1327. }
  1328. container.appendChild(this.knob);
  1329. this.slide=new GDraggableObject(this.knob, {container:container});
  1330. this.slide.setDraggableCursor('pointer');
  1331. this.slide.setDraggingCursor('pointer');
  1332. this.container = container;
  1333. // attach the control to the map
  1334. map.getContainer().appendChild(container);
  1335. // init slider
  1336. this.setSlider(this.opacity);
  1337. // Listen for the slider being moved and set the opacity
  1338. GEvent.addListener(this.slide, "dragend", function() {that.setOpacity()});
  1339. //GEvent.addListener(this.container, "click", function( x, y ) { alert(x, y) });
  1340. return container;
  1341. }
  1342. // Set the default position for the control
  1343. CTransparencyControl.prototype.getDefaultPosition = function() {
  1344. return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 47));
  1345. }
  1346. /*
  1347. * Full-screen Window Resize
  1348. */
  1349. function getWindowHeight() {
  1350. if (self.innerHeight) return self.innerHeight;
  1351. if (document.documentElement && document.documentElement.clientHeight)
  1352. return document.documentElement.clientHeight;
  1353. if (document.body) return document.body.clientHeight;
  1354. return 0;
  1355. }
  1356. function getWindowWidth() {
  1357. if (self.innerWidth) return self.innerWidth;
  1358. if (document.documentElement && document.documentElement.clientWidth)
  1359. return document.documentElement.clientWidth;
  1360. if (document.body) return document.body.clientWidth;
  1361. return 0;
  1362. }
  1363. function resize() {
  1364. var map = document.getElementById("map");
  1365. var header = document.getElementById("header");
  1366. var subheader = document.getElementById("subheader");
  1367. map.style.height = (getWindowHeight()-80) + "px";
  1368. map.style.width = (getWindowWidth()-20) + "px";
  1369. header.style.width = (getWindowWidth()-20) + "px";
  1370. subheader.style.width = (getWindowWidth()-20) + "px";
  1371. // map.checkResize();
  1372. }
  1373. /*
  1374. * Main load function:
  1375. */
  1376. function load() {
  1377. if (GBrowserIsCompatible()) {
  1378. // Bug in the Google Maps: Copyright for Overlay is not correctly displayed
  1379. var gcr = GMapType.prototype.getCopyrights;
  1380. GMapType.prototype.getCopyrights = function(bounds,zoom) {
  1381. return ["%(copyright)s"].concat(gcr.call(this,bounds,zoom));
  1382. }
  1383. map = new GMap2( document.getElementById("map"), { backgroundColor: '#fff' } );
  1384. map.addMapType(G_PHYSICAL_MAP);
  1385. map.setMapType(G_PHYSICAL_MAP);
  1386. map.setCenter( mapBounds.getCenter(), map.getBoundsZoomLevel( mapBounds ));
  1387. hybridOverlay = new GTileLayerOverlay( G_HYBRID_MAP.getTileLayers()[1] );
  1388. GEvent.addListener(map, "maptypechanged", function() {
  1389. if (map.getCurrentMapType() == G_HYBRID_MAP) {
  1390. map.addOverlay(hybridOverlay);
  1391. } else {
  1392. map.removeOverlay(hybridOverlay);
  1393. }
  1394. } );
  1395. var tilelayer = new GTileLayer(GCopyrightCollection(''), mapMinZoom, mapMaxZoom);
  1396. var mercator = new GMercatorProjection(mapMaxZoom+1);
  1397. tilelayer.getTileUrl = function(tile,zoom) {
  1398. if ((zoom < mapMinZoom) || (zoom > mapMaxZoom)) {
  1399. return "http://www.maptiler.org/img/none.png";
  1400. }
  1401. var ymax = 1 << zoom;
  1402. var y = ymax - tile.y -1;
  1403. var tileBounds = new GLatLngBounds(
  1404. mercator.fromPixelToLatLng( new GPoint( (tile.x)*256, (tile.y+1)*256 ) , zoom ),
  1405. mercator.fromPixelToLatLng( new GPoint( (tile.x+1)*256, (tile.y)*256 ) , zoom )
  1406. );
  1407. if (mapBounds.intersects(tileBounds)) {
  1408. return zoom+"/"+tile.x+"/"+y+".png";
  1409. } else {
  1410. return "http://www.maptiler.org/img/none.png";
  1411. }
  1412. }
  1413. // IE 7-: support for PNG alpha channel
  1414. // Unfortunately, the opacity for whole overlay is then not changeable, either or...
  1415. tilelayer.isPng = function() { return true;};
  1416. tilelayer.getOpacity = function() { return opacity; }
  1417. overlay = new GTileLayerOverlay( tilelayer );
  1418. map.addOverlay(overlay);
  1419. map.addControl(new GLargeMapControl());
  1420. map.addControl(new GHierarchicalMapTypeControl());
  1421. map.addControl(new CTransparencyControl( overlay ));
  1422. """ % args
  1423. if self.kml:
  1424. s += """
  1425. map.addMapType(G_SATELLITE_3D_MAP);
  1426. map.getEarthInstance(getEarthInstanceCB);
  1427. """
  1428. s += """
  1429. map.enableContinuousZoom();
  1430. map.enableScrollWheelZoom();
  1431. map.setMapType(G_HYBRID_MAP);
  1432. }
  1433. resize();
  1434. }
  1435. """
  1436. if self.kml:
  1437. s += """
  1438. function getEarthInstanceCB(object) {
  1439. var ge = object;
  1440. if (ge) {
  1441. var link = ge.createLink("");
  1442. link.setHref("%(publishurl)s/doc.kml");
  1443. var networkLink = ge.createNetworkLink("");
  1444. networkLink.setName("TMS Map Overlay");
  1445. networkLink.setFlyToView(true);
  1446. networkLink.setLink(link);
  1447. ge.getFeatures().appendChild(networkLink);
  1448. } else {
  1449. // alert("You should open a KML in Google Earth");
  1450. // add div with the link to generated KML... - maybe JavaScript redirect to the URL of KML?
  1451. }
  1452. }
  1453. """ % args
  1454. s += """
  1455. onresize=function(){ resize(); };
  1456. //]]>
  1457. </script>
  1458. </head>
  1459. <body onload="load()">
  1460. <div id="header"><h1>%(title)s</h1></div>
  1461. <div id="subheader">Generated by <a href="http://www.maptiler.org/">MapTiler</a>/<a href="http://www.klokan.cz/projects/gdal2tiles/">GDAL2Tiles</a>, Copyright &copy; 2008 <a href="http://www.klokan.cz/">Klokan Petr Pridal</a>, <a href="http://www.gdal.org/">GDAL</a> &amp; <a href="http://www.osgeo.org/">OSGeo</a> <a href="http://code.google.com/soc/">GSoC</a>
  1462. <!-- PLEASE, LET THIS NOTE ABOUT AUTHOR AND PROJECT SOMEWHERE ON YOUR WEBSITE, OR AT LEAST IN THE COMMENT IN HTML. THANK YOU -->
  1463. </div>
  1464. <div id="map"></div>
  1465. </body>
  1466. </html>
  1467. """ % args
  1468. return s
  1469. # -------------------------------------------------------------------------
  1470. def generate_openlayers( self ):
  1471. """
  1472. Template for openlayers.html implementing overlay of available Spherical Mercator layers.
  1473. It returns filled string. Expected variables:
  1474. title, googlemapskey, yahooappid, north, south, east, west, minzoom, maxzoom, tilesize, tileformat, publishurl
  1475. """
  1476. args = {}
  1477. args['title'] = self.options.title
  1478. args['googlemapskey'] = self.options.googlekey
  1479. args['yahooappid'] = self.options.yahookey
  1480. args['south'], args['west'], args['north'], args['east'] = self.swne
  1481. args['minzoom'] = self.tminz
  1482. args['maxzoom'] = self.tmaxz
  1483. args['tilesize'] = self.tilesize
  1484. args['tileformat'] = self.tileext
  1485. args['publishurl'] = self.options.url
  1486. args['copyright'] = self.options.copyright
  1487. if self.options.profile == 'raster':
  1488. args['rasterzoomlevels'] = self.tmaxz+1
  1489. args['rastermaxresolution'] = 2**(self.nativezoom) * self.out_gt[1]
  1490. s = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  1491. <html xmlns="http://www.w3.org/1999/xhtml"
  1492. <head>
  1493. <title>%(title)s</title>
  1494. <meta http-equiv='imagetoolbar' content='no'/>
  1495. <style type="text/css"> v\:* {behavior:url(#default#VML);}
  1496. html, body { overflow: hidden; padding: 0; height: 100%%; width: 100%%; font-family: 'Lucida Grande',Geneva,Arial,Verdana,sans-serif; }
  1497. body { margin: 10px; background: #fff; }
  1498. h1 { margin: 0; padding: 6px; border:0; font-size: 20pt; }
  1499. #header { height: 43px; padding: 0; background-color: #eee; border: 1px solid #888; }
  1500. #subheader { height: 12px; text-align: right; font-size: 10px; color: #555;}
  1501. #map { height: 95%%; border: 1px solid #888; }
  1502. </style>""" % args
  1503. if self.options.profile == 'mercator':
  1504. s += """
  1505. <script src='http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1'></script>
  1506. <script src='http://maps.google.com/maps?file=api&amp;v=2&amp;key=%(googlemapskey)s' type='text/javascript'></script>
  1507. <script src="http://api.maps.yahoo.com/ajaxymap?v=3.0&amp;appid=%(yahooappid)s"></script>""" % args
  1508. s += """
  1509. <script src="http://www.openlayers.org/api/2.7/OpenLayers.js" type="text/javascript"></script>
  1510. <script type="text/javascript">
  1511. var map;
  1512. var mapBounds = new OpenLayers.Bounds( %(west)s, %(south)s, %(east)s, %(north)s);
  1513. var mapMinZoom = %(minzoom)s;
  1514. var mapMaxZoom = %(maxzoom)s;
  1515. // avoid pink tiles
  1516. OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
  1517. OpenLayers.Util.onImageLoadErrorColor = "transparent";
  1518. function init(){""" % args
  1519. if self.options.profile == 'mercator':
  1520. s += """
  1521. var options = {
  1522. controls: [],
  1523. projection: new OpenLayers.Projection("EPSG:900913"),
  1524. displayProjection: new OpenLayers.Projection("EPSG:4326"),
  1525. units: "m",
  1526. maxResolution: 156543.0339,
  1527. maxExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508, 20037508.34)
  1528. };
  1529. map = new OpenLayers.Map('map', options);
  1530. // create Google Mercator layers
  1531. var gmap = new OpenLayers.Layer.Google("Google Streets",
  1532. { sphericalMercator: true, numZoomLevels: 20} );
  1533. var gsat = new OpenLayers.Layer.Google("Google Satellite",
  1534. {type: G_SATELLITE_MAP, sphericalMercator: true, numZoomLevels: 20} );
  1535. var ghyb = new OpenLayers.Layer.Google("Google Hybrid",
  1536. {type: G_HYBRID_MAP, sphericalMercator: true, numZoomLevels: 20});
  1537. var gter = new OpenLayers.Layer.Google("Google Terrain",
  1538. {type: G_PHYSICAL_MAP, sphericalMercator: true, numZoomLevels: 20 });
  1539. // create Virtual Earth layers
  1540. OpenLayers.Layer.VirtualEarth.prototype.MAX_ZOOM_LEVEL=19;
  1541. OpenLayers.Layer.VirtualEarth.prototype.RESOLUTIONS=OpenLayers.Layer.Google.prototype.RESOLUTIONS
  1542. var veroad = new OpenLayers.Layer.VirtualEarth("Virtual Earth Roads",
  1543. {'type': VEMapStyle.Road, 'sphericalMercator': true, numZoomLevels: 20});
  1544. var veaer = new OpenLayers.Layer.VirtualEarth("Virtual Earth Aerial",
  1545. {'type': VEMapStyle.Aerial, 'sphericalMercator': true, numZoomLevels: 20 });
  1546. var vehyb = new OpenLayers.Layer.VirtualEarth("Virtual Earth Hybrid",
  1547. {'type': VEMapStyle.Hybrid, 'sphericalMercator': true});
  1548. // create Yahoo layer
  1549. var yahoo = new OpenLayers.Layer.Yahoo("Yahoo Street",
  1550. {'sphericalMercator': true});
  1551. var yahoosat = new OpenLayers.Layer.Yahoo("Yahoo Satellite",
  1552. {'type': YAHOO_MAP_SAT, 'sphericalMercator': true});
  1553. var yahoohyb = new OpenLayers.Layer.Yahoo("Yahoo Hybrid",
  1554. {'type': YAHOO_MAP_HYB, 'sphericalMercator': true});
  1555. // create OSM/OAM layer
  1556. var osm = new OpenLayers.Layer.TMS( "OpenStreetMap",
  1557. "http://tile.openstreetmap.org/",
  1558. { type: 'png', getURL: osm_getTileURL, displayOutsideMaxExtent: true, attribution: '<a href="http://www.openstreetmap.org/">OpenStreetMap</a>'} );
  1559. var oam = new OpenLayers.Layer.TMS( "OpenAerialMap",
  1560. "http://tile.openaerialmap.org/tiles/1.0.0/openaerialmap-900913/",
  1561. { type: 'png', getURL: osm_getTileURL } );
  1562. // create TMS Overlay layer
  1563. var tmsoverlay = new OpenLayers.Layer.TMS( "TMS Overlay", "",
  1564. { // url: '', serviceVersion: '.', layername: '.',
  1565. type: 'png', getURL: overlay_getTileURL, alpha: true,
  1566. isBaseLayer: false
  1567. });
  1568. if (OpenLayers.Util.alphaHack() == false) { tmsoverlay.setOpacity(0.7); }
  1569. map.addLayers([gmap, gsat, ghyb, gter, veroad, veaer, vehyb,
  1570. yahoo, yahoosat, yahoohyb, osm, oam,
  1571. tmsoverlay]);
  1572. var switcherControl = new OpenLayers.Control.LayerSwitcher();
  1573. map.addControl(switcherControl);
  1574. switcherControl.maximizeControl();
  1575. map.zoomToExtent( mapBounds.transform(map.displayProjection, map.projection ) );
  1576. """ % args
  1577. elif self.options.profile == 'geodetic':
  1578. s += """
  1579. var options = {
  1580. controls: [],
  1581. projection: new OpenLayers.Projection("EPSG:4326"),
  1582. maxResolution: 0.703125,
  1583. maxExtent: new OpenLayers.Bounds(-180, -90, 180, 90)
  1584. };
  1585. map = new OpenLayers.Map('map', options);
  1586. layer = new OpenLayers.Layer.WMS( "Blue Marble",
  1587. "http://labs.metacarta.com/wms-c/Basic.py?", {layers: 'satellite' } );
  1588. map.addLayer(layer);
  1589. wms = new OpenLayers.Layer.WMS( "VMap0",
  1590. "http://labs.metacarta.com/wms-c/Basic.py?", {layers: 'basic', format: 'image/png' } );
  1591. map.addLayer(wms);
  1592. var tmsoverlay = new OpenLayers.Layer.TMS( "TMS Overlay", "",
  1593. {
  1594. serviceVersion: '.', layername: '.', alpha: true,
  1595. type: 'png', getURL: overlay_getTileURL,
  1596. isBaseLayer: false
  1597. });
  1598. map.addLayer(tmsoverlay);
  1599. if (OpenLayers.Util.alphaHack() == false) { tmsoverlay.setOpacity(0.7); }
  1600. var switcherControl = new OpenLayers.Control.LayerSwitcher();
  1601. map.addControl(switcherControl);
  1602. switcherControl.maximizeControl();
  1603. map.zoomToExtent( mapBounds );
  1604. """
  1605. elif self.options.profile == 'raster':
  1606. s += """
  1607. var options = {
  1608. controls: [],
  1609. maxExtent: new OpenLayers.Bounds( %(west)s, %(south)s, %(east)s, %(north)s ),
  1610. maxResolution: %(rastermaxresolution)f,
  1611. numZoomLevels: %(rasterzoomlevels)d
  1612. };
  1613. map = new OpenLayers.Map('map', options);
  1614. var layer = new OpenLayers.Layer.TMS( "TMS Layer","",
  1615. { url: '', serviceVersion: '.', layername: '.', alpha: true,
  1616. type: 'png', getURL: overlay_getTileURL
  1617. });
  1618. map.addLayer(layer);
  1619. map.zoomToExtent( mapBounds );
  1620. """ % args
  1621. s += """
  1622. map.addControl(new OpenLayers.Control.PanZoomBar());
  1623. map.addControl(new OpenLayers.Control.MousePosition());
  1624. map.addControl(new OpenLayers.Control.MouseDefaults());
  1625. map.addControl(new OpenLayers.Control.KeyboardDefaults());
  1626. }
  1627. """ % args
  1628. if self.options.profile == 'mercator':
  1629. s += """
  1630. function osm_getTileURL(bounds) {
  1631. var res = this.map.getResolution();
  1632. var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
  1633. var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
  1634. var z = this.map.getZoom();
  1635. var limit = Math.pow(2, z);
  1636. if (y < 0 || y >= limit) {
  1637. return "http://www.maptiler.org/img/none.png";
  1638. } else {
  1639. x = ((x %% limit) + limit) %% limit;
  1640. return this.url + z + "/" + x + "/" + y + "." + this.type;
  1641. }
  1642. }
  1643. function overlay_getTileURL(bounds) {
  1644. var res = this.map.getResolution();
  1645. var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
  1646. var y = Math.round((bounds.bottom - this.tileOrigin.lat) / (res * this.tileSize.h));
  1647. var z = this.map.getZoom();
  1648. if (this.map.baseLayer.name == 'Virtual Earth Roads' || this.map.baseLayer.name == 'Virtual Earth Aerial' || this.map.baseLayer.name == 'Virtual Earth Hybrid') {
  1649. z = z + 1;
  1650. }
  1651. if (mapBounds.intersectsBounds( bounds ) && z >= mapMinZoom && z <= mapMaxZoom ) {
  1652. //console.log( this.url + z + "/" + x + "/" + y + "." + this.type);
  1653. return this.url + z + "/" + x + "/" + y + "." + this.type;
  1654. } else {
  1655. return "http://www.maptiler.org/img/none.png";
  1656. }
  1657. }
  1658. """ % args
  1659. elif self.options.profile == 'geodetic':
  1660. s += """
  1661. function overlay_getTileURL(bounds) {
  1662. bounds = this.adjustBounds(bounds);
  1663. var res = this.map.getResolution();
  1664. var x = Math.round((bounds.left - this.tileOrigin.lon) / (res * this.tileSize.w));
  1665. var y = Math.round((bounds.bottom - this.tileOrigin.lat) / (res * this.tileSize.h));
  1666. var z = this.map.getZoom();
  1667. var path = this.serviceVersion + "/" + this.layername + "/" + z + "/" + x + "/" + y + "." + this.type;
  1668. var url = this.url;
  1669. if (mapBounds.intersectsBounds( bounds ) && z >= mapMinZoom && z <= mapMaxZoom) {
  1670. // console.log( this.url + z + "/" + x + "/" + y + "." + this.type);
  1671. return this.url + z + "/" + x + "/" + y + "." + this.type;
  1672. } else {
  1673. return "http://www.maptiler.org/img/none.png";
  1674. }
  1675. }
  1676. """ % args
  1677. elif self.options.profile == 'raster':
  1678. s += """
  1679. function overlay_getTileURL(bounds) {
  1680. var res = this.map.getResolution();
  1681. var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
  1682. var y = Math.round((bounds.bottom - this.maxExtent.bottom) / (res * this.tileSize.h));
  1683. var z = this.map.getZoom();
  1684. if (x >= 0 && y >= 0) {
  1685. return this.url + z + "/" + x + "/" + y + "." + this.type;
  1686. } else {
  1687. return "http://www.maptiler.org/img/none.png";
  1688. }
  1689. }
  1690. """ % args
  1691. s += """
  1692. function getWindowHeight() {
  1693. if (self.innerHeight) return self.innerHeight;
  1694. if (document.documentElement && document.documentElement.clientHeight)
  1695. return document.documentElement.clientHeight;
  1696. if (document.body) return document.body.clientHeight;
  1697. return 0;
  1698. }
  1699. function getWindowWidth() {
  1700. if (self.innerWidth) return self.innerWidth;
  1701. if (document.documentElement && document.documentElement.clientWidth)
  1702. return document.documentElement.clientWidth;
  1703. if (document.body) return document.body.clientWidth;
  1704. return 0;
  1705. }
  1706. function resize() {
  1707. var map = document.getElementById("map");
  1708. var header = document.getElementById("header");
  1709. var subheader = document.getElementById("subheader");
  1710. map.style.height = (getWindowHeight()-80) + "px";
  1711. map.style.width = (getWindowWidth()-20) + "px";
  1712. header.style.width = (getWindowWidth()-20) + "px";
  1713. subheader.style.width = (getWindowWidth()-20) + "px";
  1714. if (map.updateSize) { map.updateSize(); };
  1715. }
  1716. onresize=function(){ resize(); };
  1717. </script>
  1718. </head>
  1719. <body onload="init()">
  1720. <div id="header"><h1>%(title)s</h1></div>
  1721. <div id="subheader">Generated by <a href="http://www.maptiler.org/">MapTiler</a>/<a href="http://www.klokan.cz/projects/gdal2tiles/">GDAL2Tiles</a>, Copyright &copy; 2008 <a href="http://www.klokan.cz/">Klokan Petr Pridal</a>, <a href="http://www.gdal.org/">GDAL</a> &amp; <a href="http://www.osgeo.org/">OSGeo</a> <a href="http://code.google.com/soc/">GSoC</a>
  1722. <!-- PLEASE, LET THIS NOTE ABOUT AUTHOR AND PROJECT SOMEWHERE ON YOUR WEBSITE, OR AT LEAST IN THE COMMENT IN HTML. THANK YOU -->
  1723. </div>
  1724. <div id="map"></div>
  1725. <script type="text/javascript" >resize()</script>
  1726. </body>
  1727. </html>""" % args
  1728. return s
  1729. # =============================================================================
  1730. # =============================================================================
  1731. # =============================================================================
  1732. if __name__=='__main__':
  1733. argv = gdal.GeneralCmdLineProcessor( sys.argv )
  1734. if argv:
  1735. gdal2tiles = GDAL2Tiles( argv[1:] )
  1736. gdal2tiles.process()