Advertisement
Guest User

gdal2tiles.py - #4379 patch2

a guest
Feb 22nd, 2012
1,842
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 90.83 KB | None | 0 0
  1. #!/usr/bin/env python
  2. #******************************************************************************
  3. # $Id: gdal2tiles.py 19288 2010-04-02 18:36:17Z rouault $
  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.  
  38. import sys
  39.  
  40. try:
  41. from osgeo import gdal
  42. from osgeo import osr
  43. except:
  44. import gdal
  45. print('You are using "old gen" bindings. gdal2tiles needs "new gen" bindings.')
  46. sys.exit(1)
  47.  
  48. import os
  49. import math
  50.  
  51. try:
  52. from PIL import Image
  53. import numpy
  54. import osgeo.gdal_array as gdalarray
  55. except:
  56. # 'antialias' resampling is not available
  57. pass
  58.  
  59. import multiprocessing
  60. import tempfile
  61. from optparse import OptionParser, OptionGroup
  62.  
  63. __version__ = "$Id: gdal2tiles.py 19288 2010-04-02 18:36:17Z rouault $"
  64.  
  65. resampling_list = ('average','near','bilinear','cubic','cubicspline','lanczos','antialias')
  66. profile_list = ('mercator','geodetic','raster') #,'zoomify')
  67. webviewer_list = ('all','google','openlayers','none')
  68. queue = multiprocessing.Queue()
  69.  
  70. # =============================================================================
  71. # =============================================================================
  72. # =============================================================================
  73.  
  74. __doc__globalmaptiles = """
  75. globalmaptiles.py
  76.  
  77. Global Map Tiles as defined in Tile Map Service (TMS) Profiles
  78. ==============================================================
  79.  
  80. Functions necessary for generation of global tiles used on the web.
  81. It contains classes implementing coordinate conversions for:
  82.  
  83. - GlobalMercator (based on EPSG:900913 = EPSG:3785)
  84. for Google Maps, Yahoo Maps, Microsoft Maps compatible tiles
  85. - GlobalGeodetic (based on EPSG:4326)
  86. for OpenLayers Base Map and Google Earth compatible tiles
  87.  
  88. More info at:
  89.  
  90. http://wiki.osgeo.org/wiki/Tile_Map_Service_Specification
  91. http://wiki.osgeo.org/wiki/WMS_Tiling_Client_Recommendation
  92. http://msdn.microsoft.com/en-us/library/bb259689.aspx
  93. http://code.google.com/apis/maps/documentation/overlays.html#Google_Maps_Coordinates
  94.  
  95. Created by Klokan Petr Pridal on 2008-07-03.
  96. Google Summer of Code 2008, project GDAL2Tiles for OSGEO.
  97.  
  98. In case you use this class in your product, translate it to another language
  99. or find it usefull for your project please let me know.
  100. My email: klokan at klokan dot cz.
  101. I would like to know where it was used.
  102.  
  103. Class is available under the open-source GDAL license (www.gdal.org).
  104. """
  105.  
  106. MAXZOOMLEVEL = 32
  107.  
  108. class GlobalMercator(object):
  109. """
  110. TMS Global Mercator Profile
  111. ---------------------------
  112.  
  113. Functions necessary for generation of tiles in Spherical Mercator projection,
  114. EPSG:900913 (EPSG:gOOglE, Google Maps Global Mercator), EPSG:3785, OSGEO:41001.
  115.  
  116. Such tiles are compatible with Google Maps, Microsoft Virtual Earth, Yahoo Maps,
  117. UK Ordnance Survey OpenSpace API, ...
  118. and you can overlay them on top of base maps of those web mapping applications.
  119.  
  120. Pixel and tile coordinates are in TMS notation (origin [0,0] in bottom-left).
  121.  
  122. What coordinate conversions do we need for TMS Global Mercator tiles::
  123.  
  124. LatLon <-> Meters <-> Pixels <-> Tile
  125.  
  126. WGS84 coordinates Spherical Mercator Pixels in pyramid Tiles in pyramid
  127. lat/lon XY in metres XY pixels Z zoom XYZ from TMS
  128. EPSG:4326 EPSG:900913
  129. .----. --------- -- TMS
  130. / \ <-> | | <-> /----/ <-> Google
  131. \ / | | /--------/ QuadTree
  132. ----- --------- /------------/
  133. KML, public WebMapService Web Clients TileMapService
  134.  
  135. What is the coordinate extent of Earth in EPSG:900913?
  136.  
  137. [-20037508.342789244, -20037508.342789244, 20037508.342789244, 20037508.342789244]
  138. Constant 20037508.342789244 comes from the circumference of the Earth in meters,
  139. which is 40 thousand kilometers, the coordinate origin is in the middle of extent.
  140. In fact you can calculate the constant as: 2 * math.pi * 6378137 / 2.0
  141. $ echo 180 85 | gdaltransform -s_srs EPSG:4326 -t_srs EPSG:900913
  142. Polar areas with abs(latitude) bigger then 85.05112878 are clipped off.
  143.  
  144. What are zoom level constants (pixels/meter) for pyramid with EPSG:900913?
  145.  
  146. whole region is on top of pyramid (zoom=0) covered by 256x256 pixels tile,
  147. every lower zoom level resolution is always divided by two
  148. initialResolution = 20037508.342789244 * 2 / 256 = 156543.03392804062
  149.  
  150. What is the difference between TMS and Google Maps/QuadTree tile name convention?
  151.  
  152. The tile raster itself is the same (equal extent, projection, pixel size),
  153. there is just different identification of the same raster tile.
  154. Tiles in TMS are counted from [0,0] in the bottom-left corner, id is XYZ.
  155. Google placed the origin [0,0] to the top-left corner, reference is XYZ.
  156. Microsoft is referencing tiles by a QuadTree name, defined on the website:
  157. http://msdn2.microsoft.com/en-us/library/bb259689.aspx
  158.  
  159. The lat/lon coordinates are using WGS84 datum, yeh?
  160.  
  161. Yes, all lat/lon we are mentioning should use WGS84 Geodetic Datum.
  162. Well, the web clients like Google Maps are projecting those coordinates by
  163. Spherical Mercator, so in fact lat/lon coordinates on sphere are treated as if
  164. the were on the WGS84 ellipsoid.
  165.  
  166. From MSDN documentation:
  167. To simplify the calculations, we use the spherical form of projection, not
  168. the ellipsoidal form. Since the projection is used only for map display,
  169. and not for displaying numeric coordinates, we don't need the extra precision
  170. of an ellipsoidal projection. The spherical projection causes approximately
  171. 0.33 percent scale distortion in the Y direction, which is not visually noticable.
  172.  
  173. How do I create a raster in EPSG:900913 and convert coordinates with PROJ.4?
  174.  
  175. You can use standard GIS tools like gdalwarp, cs2cs or gdaltransform.
  176. All of the tools supports -t_srs 'epsg:900913'.
  177.  
  178. For other GIS programs check the exact definition of the projection:
  179. More info at http://spatialreference.org/ref/user/google-projection/
  180. The same projection is degined as EPSG:3785. WKT definition is in the official
  181. EPSG database.
  182.  
  183. Proj4 Text:
  184. +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0
  185. +k=1.0 +units=m +nadgrids=@null +no_defs
  186.  
  187. Human readable WKT format of EPGS:900913:
  188. PROJCS["Google Maps Global Mercator",
  189. GEOGCS["WGS 84",
  190. DATUM["WGS_1984",
  191. SPHEROID["WGS 84",6378137,298.257223563,
  192. AUTHORITY["EPSG","7030"]],
  193. AUTHORITY["EPSG","6326"]],
  194. PRIMEM["Greenwich",0],
  195. UNIT["degree",0.0174532925199433],
  196. AUTHORITY["EPSG","4326"]],
  197. PROJECTION["Mercator_1SP"],
  198. PARAMETER["central_meridian",0],
  199. PARAMETER["scale_factor",1],
  200. PARAMETER["false_easting",0],
  201. PARAMETER["false_northing",0],
  202. UNIT["metre",1,
  203. AUTHORITY["EPSG","9001"]]]
  204. """
  205.  
  206. def __init__(self, tileSize=256):
  207. "Initialize the TMS Global Mercator pyramid"
  208. self.tileSize = tileSize
  209. self.initialResolution = 2 * math.pi * 6378137 / self.tileSize
  210. # 156543.03392804062 for tileSize 256 pixels
  211. self.originShift = 2 * math.pi * 6378137 / 2.0
  212. # 20037508.342789244
  213.  
  214. def LatLonToMeters(self, lat, lon ):
  215. "Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:900913"
  216.  
  217. mx = lon * self.originShift / 180.0
  218. my = math.log( math.tan((90 + lat) * math.pi / 360.0 )) / (math.pi / 180.0)
  219.  
  220. my = my * self.originShift / 180.0
  221. return mx, my
  222.  
  223. def MetersToLatLon(self, mx, my ):
  224. "Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 Datum"
  225.  
  226. lon = (mx / self.originShift) * 180.0
  227. lat = (my / self.originShift) * 180.0
  228.  
  229. lat = 180 / math.pi * (2 * math.atan( math.exp( lat * math.pi / 180.0)) - math.pi / 2.0)
  230. return lat, lon
  231.  
  232. def PixelsToMeters(self, px, py, zoom):
  233. "Converts pixel coordinates in given zoom level of pyramid to EPSG:900913"
  234.  
  235. res = self.Resolution( zoom )
  236. mx = px * res - self.originShift
  237. my = py * res - self.originShift
  238. return mx, my
  239.  
  240. def MetersToPixels(self, mx, my, zoom):
  241. "Converts EPSG:900913 to pyramid pixel coordinates in given zoom level"
  242.  
  243. res = self.Resolution( zoom )
  244. px = (mx + self.originShift) / res
  245. py = (my + self.originShift) / res
  246. return px, py
  247.  
  248. def PixelsToTile(self, px, py):
  249. "Returns a tile covering region in given pixel coordinates"
  250.  
  251. tx = int( math.ceil( px / float(self.tileSize) ) - 1 )
  252. ty = int( math.ceil( py / float(self.tileSize) ) - 1 )
  253. return tx, ty
  254.  
  255. def PixelsToRaster(self, px, py, zoom):
  256. "Move the origin of pixel coordinates to top-left corner"
  257.  
  258. mapSize = self.tileSize << zoom
  259. return px, mapSize - py
  260.  
  261. def MetersToTile(self, mx, my, zoom):
  262. "Returns tile for given mercator coordinates"
  263.  
  264. px, py = self.MetersToPixels( mx, my, zoom)
  265. return self.PixelsToTile( px, py)
  266.  
  267. def TileBounds(self, tx, ty, zoom):
  268. "Returns bounds of the given tile in EPSG:900913 coordinates"
  269.  
  270. minx, miny = self.PixelsToMeters( tx*self.tileSize, ty*self.tileSize, zoom )
  271. maxx, maxy = self.PixelsToMeters( (tx+1)*self.tileSize, (ty+1)*self.tileSize, zoom )
  272. return ( minx, miny, maxx, maxy )
  273.  
  274. def TileLatLonBounds(self, tx, ty, zoom ):
  275. "Returns bounds of the given tile in latutude/longitude using WGS84 datum"
  276.  
  277. bounds = self.TileBounds( tx, ty, zoom)
  278. minLat, minLon = self.MetersToLatLon(bounds[0], bounds[1])
  279. maxLat, maxLon = self.MetersToLatLon(bounds[2], bounds[3])
  280.  
  281. return ( minLat, minLon, maxLat, maxLon )
  282.  
  283. def Resolution(self, zoom ):
  284. "Resolution (meters/pixel) for given zoom level (measured at Equator)"
  285.  
  286. # return (2 * math.pi * 6378137) / (self.tileSize * 2**zoom)
  287. return self.initialResolution / (2**zoom)
  288.  
  289. def ZoomForPixelSize(self, pixelSize ):
  290. "Maximal scaledown zoom of the pyramid closest to the pixelSize."
  291.  
  292. for i in range(MAXZOOMLEVEL):
  293. if pixelSize > self.Resolution(i):
  294. if i!=0:
  295. return i-1
  296. else:
  297. return 0 # We don't want to scale up
  298.  
  299. def GoogleTile(self, tx, ty, zoom):
  300. "Converts TMS tile coordinates to Google Tile coordinates"
  301.  
  302. # coordinate origin is moved from bottom-left to top-left corner of the extent
  303. return tx, (2**zoom - 1) - ty
  304.  
  305. def QuadTree(self, tx, ty, zoom ):
  306. "Converts TMS tile coordinates to Microsoft QuadTree"
  307.  
  308. quadKey = ""
  309. ty = (2**zoom - 1) - ty
  310. for i in range(zoom, 0, -1):
  311. digit = 0
  312. mask = 1 << (i-1)
  313. if (tx & mask) != 0:
  314. digit += 1
  315. if (ty & mask) != 0:
  316. digit += 2
  317. quadKey += str(digit)
  318.  
  319. return quadKey
  320.  
  321. #---------------------
  322.  
  323. class GlobalGeodetic(object):
  324. """
  325. TMS Global Geodetic Profile
  326. ---------------------------
  327.  
  328. Functions necessary for generation of global tiles in Plate Carre projection,
  329. EPSG:4326, "unprojected profile".
  330.  
  331. Such tiles are compatible with Google Earth (as any other EPSG:4326 rasters)
  332. and you can overlay the tiles on top of OpenLayers base map.
  333.  
  334. Pixel and tile coordinates are in TMS notation (origin [0,0] in bottom-left).
  335.  
  336. What coordinate conversions do we need for TMS Global Geodetic tiles?
  337.  
  338. Global Geodetic tiles are using geodetic coordinates (latitude,longitude)
  339. directly as planar coordinates XY (it is also called Unprojected or Plate
  340. Carre). We need only scaling to pixel pyramid and cutting to tiles.
  341. Pyramid has on top level two tiles, so it is not square but rectangle.
  342. Area [-180,-90,180,90] is scaled to 512x256 pixels.
  343. TMS has coordinate origin (for pixels and tiles) in bottom-left corner.
  344. Rasters are in EPSG:4326 and therefore are compatible with Google Earth.
  345.  
  346. LatLon <-> Pixels <-> Tiles
  347.  
  348. WGS84 coordinates Pixels in pyramid Tiles in pyramid
  349. lat/lon XY pixels Z zoom XYZ from TMS
  350. EPSG:4326
  351. .----. ----
  352. / \ <-> /--------/ <-> TMS
  353. \ / /--------------/
  354. ----- /--------------------/
  355. WMS, KML Web Clients, Google Earth TileMapService
  356. """
  357.  
  358. def __init__(self, tileSize = 256):
  359. self.tileSize = tileSize
  360.  
  361. def LatLonToPixels(self, lat, lon, zoom):
  362. "Converts lat/lon to pixel coordinates in given zoom of the EPSG:4326 pyramid"
  363.  
  364. res = 180.0 / self.tileSize / 2**zoom
  365. px = (180 + lat) / res
  366. py = (90 + lon) / res
  367. return px, py
  368.  
  369. def PixelsToTile(self, px, py):
  370. "Returns coordinates of the tile covering region in pixel coordinates"
  371.  
  372. tx = int( math.ceil( px / float(self.tileSize) ) - 1 )
  373. ty = int( math.ceil( py / float(self.tileSize) ) - 1 )
  374. return tx, ty
  375.  
  376. def LatLonToTile(self, lat, lon, zoom):
  377. "Returns the tile for zoom which covers given lat/lon coordinates"
  378.  
  379. px, py = self.LatLonToPixels( lat, lon, zoom)
  380. return self.PixelsToTile(px,py)
  381.  
  382. def Resolution(self, zoom ):
  383. "Resolution (arc/pixel) for given zoom level (measured at Equator)"
  384.  
  385. return 180.0 / self.tileSize / 2**zoom
  386. #return 180 / float( 1 << (8+zoom) )
  387.  
  388. def ZoomForPixelSize(self, pixelSize ):
  389. "Maximal scaledown zoom of the pyramid closest to the pixelSize."
  390.  
  391. for i in range(MAXZOOMLEVEL):
  392. if pixelSize > self.Resolution(i):
  393. if i!=0:
  394. return i-1
  395. else:
  396. return 0 # We don't want to scale up
  397.  
  398. def TileBounds(self, tx, ty, zoom):
  399. "Returns bounds of the given tile"
  400. res = 180.0 / self.tileSize / 2**zoom
  401. return (
  402. tx*self.tileSize*res - 180,
  403. ty*self.tileSize*res - 90,
  404. (tx+1)*self.tileSize*res - 180,
  405. (ty+1)*self.tileSize*res - 90
  406. )
  407.  
  408. def TileLatLonBounds(self, tx, ty, zoom):
  409. "Returns bounds of the given tile in the SWNE form"
  410. b = self.TileBounds(tx, ty, zoom)
  411. return (b[1],b[0],b[3],b[2])
  412.  
  413. #---------------------
  414. # TODO: Finish Zoomify implemtentation!!!
  415. class Zoomify(object):
  416. """
  417. Tiles compatible with the Zoomify viewer
  418. ----------------------------------------
  419. """
  420.  
  421. def __init__(self, width, height, tilesize = 256, tileformat='jpg'):
  422. """Initialization of the Zoomify tile tree"""
  423.  
  424. self.tilesize = tilesize
  425. self.tileformat = tileformat
  426. imagesize = (width, height)
  427. tiles = ( math.ceil( width / tilesize ), math.ceil( height / tilesize ) )
  428.  
  429. # Size (in tiles) for each tier of pyramid.
  430. self.tierSizeInTiles = []
  431. self.tierSizeInTiles.push( tiles )
  432.  
  433. # Image size in pixels for each pyramid tierself
  434. self.tierImageSize = []
  435. self.tierImageSize.append( imagesize );
  436.  
  437. while (imagesize[0] > tilesize or imageSize[1] > tilesize ):
  438. imagesize = (math.floor( imagesize[0] / 2 ), math.floor( imagesize[1] / 2) )
  439. tiles = ( math.ceil( imagesize[0] / tilesize ), math.ceil( imagesize[1] / tilesize ) )
  440. self.tierSizeInTiles.append( tiles )
  441. self.tierImageSize.append( imagesize )
  442.  
  443. self.tierSizeInTiles.reverse()
  444. self.tierImageSize.reverse()
  445.  
  446. # Depth of the Zoomify pyramid, number of tiers (zoom levels)
  447. self.numberOfTiers = len(self.tierSizeInTiles)
  448.  
  449. # Number of tiles up to the given tier of pyramid.
  450. self.tileCountUpToTier = []
  451. self.tileCountUpToTier[0] = 0
  452. for i in range(1, self.numberOfTiers+1):
  453. self.tileCountUpToTier.append(
  454. self.tierSizeInTiles[i-1][0] * self.tierSizeInTiles[i-1][1] + self.tileCountUpToTier[i-1]
  455. )
  456.  
  457. def tilefilename(self, x, y, z):
  458. """Returns filename for tile with given coordinates"""
  459.  
  460. tileIndex = x + y * self.tierSizeInTiles[z][0] + self.tileCountUpToTier[z]
  461. return os.path.join("TileGroup%.0f" % math.floor( tileIndex / 256 ),
  462. "%s-%s-%s.%s" % ( z, x, y, self.tileformat))
  463.  
  464. # =============================================================================
  465. # =============================================================================
  466. # =============================================================================
  467.  
  468. class GDAL2Tiles(object):
  469.  
  470. # -------------------------------------------------------------------------
  471. def process(self):
  472. """The main processing function, runs all the main steps of processing"""
  473.  
  474. # Opening and preprocessing of the input file
  475. self.open_input()
  476.  
  477. # Generation of main metadata files and HTML viewers
  478. self.generate_metadata()
  479.  
  480. # Generation of the lowest tiles
  481. self.generate_base_tiles()
  482.  
  483. # Generation of the overview tiles (higher in the pyramid)
  484. self.generate_overview_tiles()
  485.  
  486. # -------------------------------------------------------------------------
  487. def error(self, msg, details = "" ):
  488. """Print an error message and stop the processing"""
  489.  
  490. if details:
  491. self.parser.error(msg + "\n\n" + details)
  492. else:
  493. self.parser.error(msg)
  494.  
  495. # -------------------------------------------------------------------------
  496. def progressbar(self, complete = 0.0):
  497. """Print progressbar for float value 0..1"""
  498.  
  499. gdal.TermProgress_nocb(complete)
  500.  
  501. # -------------------------------------------------------------------------
  502. def stop(self):
  503. """Stop the rendering immediately"""
  504. self.stopped = True
  505.  
  506. # -------------------------------------------------------------------------
  507. def __init__(self, arguments ):
  508. """Constructor function - initialization"""
  509.  
  510. self.stopped = False
  511. self.input = None
  512. self.output = None
  513.  
  514. # Tile format
  515. self.tilesize = 256
  516. self.tiledriver = 'PNG'
  517. self.tileext = 'png'
  518.  
  519. # Should we read bigger window of the input raster and scale it down?
  520. # Note: Modified leter by open_input()
  521. # Not for 'near' resampling
  522. # Not for Wavelet based drivers (JPEG2000, ECW, MrSID)
  523. # Not for 'raster' profile
  524. self.scaledquery = True
  525. # How big should be query window be for scaling down
  526. # Later on reset according the chosen resampling algorightm
  527. self.querysize = 4 * self.tilesize
  528.  
  529. # Should we use Read on the input file for generating overview tiles?
  530. # Note: Modified later by open_input()
  531. # Otherwise the overview tiles are generated from existing underlying tiles
  532. self.overviewquery = False
  533.  
  534. # RUN THE ARGUMENT PARSER:
  535.  
  536. self.optparse_init()
  537. self.options, self.args = self.parser.parse_args(args=arguments)
  538. if not self.args:
  539. self.error("No input file specified")
  540.  
  541. # POSTPROCESSING OF PARSED ARGUMENTS:
  542.  
  543. # Workaround for old versions of GDAL
  544. try:
  545. if (self.options.verbose and self.options.resampling == 'near') or gdal.TermProgress_nocb:
  546. pass
  547. except:
  548. self.error("This version of GDAL is not supported. Please upgrade to 1.6+.")
  549. #,"You can try run crippled version of gdal2tiles with parameters: -v -r 'near'")
  550.  
  551. # Is output directory the last argument?
  552.  
  553. # Test output directory, if it doesn't exist
  554. if os.path.isdir(self.args[-1]) or ( len(self.args) > 1 and not os.path.exists(self.args[-1])):
  555. self.output = self.args[-1]
  556. self.args = self.args[:-1]
  557.  
  558. # More files on the input not directly supported yet
  559.  
  560. if (len(self.args) > 1):
  561. self.error("Processing of several input files is not supported.",
  562. """Please first use a tool like gdal_vrtmerge.py or gdal_merge.py on the files:
  563. gdal_vrtmerge.py -o merged.vrt %s""" % " ".join(self.args))
  564. # TODO: Call functions from gdal_vrtmerge.py directly
  565.  
  566. self.input = self.args[0]
  567.  
  568. # Default values for not given options
  569.  
  570. if not self.output:
  571. # Directory with input filename without extension in actual directory
  572. self.output = os.path.splitext(os.path.basename( self.input ))[0]
  573.  
  574. if not self.options.title:
  575. self.options.title = os.path.basename( self.input )
  576.  
  577. if self.options.url and not self.options.url.endswith('/'):
  578. self.options.url += '/'
  579. if self.options.url:
  580. self.options.url += os.path.basename( self.output ) + '/'
  581.  
  582. # Supported options
  583.  
  584. self.resampling = None
  585.  
  586. if self.options.resampling == 'average':
  587. try:
  588. if gdal.RegenerateOverview:
  589. pass
  590. except:
  591. self.error("'average' resampling algorithm is not available.", "Please use -r 'near' argument or upgrade to newer version of GDAL.")
  592.  
  593. elif self.options.resampling == 'antialias':
  594. try:
  595. if numpy:
  596. pass
  597. except:
  598. self.error("'antialias' resampling algorithm is not available.", "Install PIL (Python Imaging Library) and numpy.")
  599.  
  600. elif self.options.resampling == 'near':
  601. self.resampling = gdal.GRA_NearestNeighbour
  602. self.querysize = self.tilesize
  603.  
  604. elif self.options.resampling == 'bilinear':
  605. self.resampling = gdal.GRA_Bilinear
  606. self.querysize = self.tilesize * 2
  607.  
  608. elif self.options.resampling == 'cubic':
  609. self.resampling = gdal.GRA_Cubic
  610.  
  611. elif self.options.resampling == 'cubicspline':
  612. self.resampling = gdal.GRA_CubicSpline
  613.  
  614. elif self.options.resampling == 'lanczos':
  615. self.resampling = gdal.GRA_Lanczos
  616.  
  617. # User specified zoom levels
  618. self.tminz = None
  619. self.tmaxz = None
  620. if self.options.zoom:
  621. minmax = self.options.zoom.split('-',1)
  622. minmax.extend([''])
  623. min, max = minmax[:2]
  624. self.tminz = int(min)
  625. if max:
  626. self.tmaxz = int(max)
  627. else:
  628. self.tmaxz = int(min)
  629.  
  630. # KML generation
  631. self.kml = self.options.kml
  632.  
  633. # Output the results
  634.  
  635. if self.options.verbose:
  636. print("Options:", self.options)
  637. print("Input:", self.input)
  638. print("Output:", self.output)
  639. print("Cache: %s MB" % (gdal.GetCacheMax() / 1024 / 1024))
  640. print('')
  641.  
  642. # -------------------------------------------------------------------------
  643. def optparse_init(self):
  644. """Prepare the option parser for input (argv)"""
  645.  
  646. usage = "Usage: %prog [options] input_file(s) [output]"
  647. p = OptionParser(usage, version="%prog "+ __version__)
  648. p.add_option("-p", "--profile", dest='profile', type='choice', choices=profile_list,
  649. help="Tile cutting profile (%s) - default 'mercator' (Google Maps compatible)" % ",".join(profile_list))
  650. p.add_option("-r", "--resampling", dest="resampling", type='choice', choices=resampling_list,
  651. help="Resampling method (%s) - default 'average'" % ",".join(resampling_list))
  652. p.add_option('-s', '--s_srs', dest="s_srs", metavar="SRS",
  653. help="The spatial reference system used for the source input data")
  654. p.add_option('-z', '--zoom', dest="zoom",
  655. help="Zoom levels to render (format:'2-5' or '10').")
  656. p.add_option('-e', '--resume', dest="resume", action="store_true",
  657. help="Resume mode. Generate only missing files.")
  658. p.add_option('-a', '--srcnodata', dest="srcnodata", metavar="NODATA",
  659. help="NODATA transparency value to assign to the input data")
  660. p.add_option('--processes', dest='processes', type='int', default=multiprocessing.cpu_count(),
  661. help='Number of concurrent processes (defaults to the number of cores in the system)')
  662. p.add_option("-v", "--verbose",
  663. action="store_true", dest="verbose",
  664. help="Print status messages to stdout")
  665.  
  666. # KML options
  667. g = OptionGroup(p, "KML (Google Earth) options", "Options for generated Google Earth SuperOverlay metadata")
  668. g.add_option("-k", "--force-kml", dest='kml', action="store_true",
  669. help="Generate KML for Google Earth - default for 'geodetic' profile and 'raster' in EPSG:4326. For a dataset with different projection use with caution!")
  670. g.add_option("-n", "--no-kml", dest='kml', action="store_false",
  671. help="Avoid automatic generation of KML files for EPSG:4326")
  672. g.add_option("-u", "--url", dest='url',
  673. help="URL address where the generated tiles are going to be published")
  674. p.add_option_group(g)
  675.  
  676. # HTML options
  677. g = OptionGroup(p, "Web viewer options", "Options for generated HTML viewers a la Google Maps")
  678. g.add_option("-w", "--webviewer", dest='webviewer', type='choice', choices=webviewer_list,
  679. help="Web viewer to generate (%s) - default 'all'" % ",".join(webviewer_list))
  680. g.add_option("-t", "--title", dest='title',
  681. help="Title of the map")
  682. g.add_option("-c", "--copyright", dest='copyright',
  683. help="Copyright for the map")
  684. g.add_option("-g", "--googlekey", dest='googlekey',
  685. help="Google Maps API key from http://code.google.com/apis/maps/signup.html")
  686. g.add_option("-y", "--yahookey", dest='yahookey',
  687. help="Yahoo Application ID from http://developer.yahoo.com/wsregapp/")
  688. p.add_option_group(g)
  689.  
  690. # TODO: MapFile + TileIndexes per zoom level for efficient MapServer WMS
  691. #g = OptionGroup(p, "WMS MapServer metadata", "Options for generated mapfile and tileindexes for MapServer")
  692. #g.add_option("-i", "--tileindex", dest='wms', action="store_true"
  693. # help="Generate tileindex and mapfile for MapServer (WMS)")
  694. # p.add_option_group(g)
  695.  
  696. p.set_defaults(verbose=False, profile="mercator", kml=False, url='',
  697. webviewer='all', copyright='', resampling='average', resume=False,
  698. googlekey='INSERT_YOUR_KEY_HERE', yahookey='INSERT_YOUR_YAHOO_APP_ID_HERE')
  699.  
  700. self.parser = p
  701.  
  702. # -------------------------------------------------------------------------
  703. def open_input(self):
  704. """Initialization of the input raster, reprojection if necessary"""
  705.  
  706. gdal.UseExceptions()
  707. gdal.AllRegister()
  708. if not self.options.verbose:
  709. gdal.PushErrorHandler('CPLQuietErrorHandler')
  710.  
  711. # Initialize necessary GDAL drivers
  712.  
  713. self.out_drv = gdal.GetDriverByName( self.tiledriver )
  714. self.mem_drv = gdal.GetDriverByName( 'MEM' )
  715.  
  716. if not self.out_drv:
  717. raise Exception("The '%s' driver was not found, is it available in this GDAL build?", self.tiledriver)
  718. if not self.mem_drv:
  719. raise Exception("The 'MEM' driver was not found, is it available in this GDAL build?")
  720.  
  721. # Open the input file
  722.  
  723. if self.input:
  724. self.in_ds = gdal.Open(self.input, gdal.GA_ReadOnly)
  725. else:
  726. raise Exception("No input file was specified")
  727.  
  728. if self.options.verbose:
  729. print("Input file:", "( %sP x %sL - %s bands)" % (self.in_ds.RasterXSize, self.in_ds.RasterYSize, self.in_ds.RasterCount))
  730.  
  731. if not self.in_ds:
  732. # Note: GDAL prints the ERROR message too
  733. self.error("It is not possible to open the input file '%s'." % self.input )
  734.  
  735. # Read metadata from the input file
  736. if self.in_ds.RasterCount == 0:
  737. self.error( "Input file '%s' has no raster band" % self.input )
  738.  
  739. if self.in_ds.GetRasterBand(1).GetRasterColorTable():
  740. # TODO: Process directly paletted dataset by generating VRT in memory
  741. self.error( "Please convert this file to RGB/RGBA and run gdal2tiles on the result.",
  742. """From paletted file you can create RGBA file (temp.vrt) by:
  743. gdal_translate -of vrt -expand rgba %s temp.vrt
  744. then run:
  745. gdal2tiles temp.vrt""" % self.input )
  746.  
  747. # Get NODATA value
  748. self.in_nodata = []
  749. for i in range(1, self.in_ds.RasterCount+1):
  750. if self.in_ds.GetRasterBand(i).GetNoDataValue() != None:
  751. self.in_nodata.append( self.in_ds.GetRasterBand(i).GetNoDataValue() )
  752. if self.options.srcnodata:
  753. nds = list(map( float, self.options.srcnodata.split(',')))
  754. if len(nds) < self.in_ds.RasterCount:
  755. self.in_nodata = (nds * self.in_ds.RasterCount)[:self.in_ds.RasterCount]
  756. else:
  757. self.in_nodata = nds
  758.  
  759. if self.options.verbose:
  760. print("NODATA: %s" % self.in_nodata)
  761.  
  762. #
  763. # Here we should have RGBA input dataset opened in self.in_ds
  764. #
  765.  
  766. if self.options.verbose:
  767. print("Preprocessed file:", "( %sP x %sL - %s bands)" % (self.in_ds.RasterXSize, self.in_ds.RasterYSize, self.in_ds.RasterCount))
  768.  
  769. # Spatial Reference System of the input raster
  770.  
  771.  
  772. self.in_srs = None
  773.  
  774. if self.options.s_srs:
  775. self.in_srs = osr.SpatialReference()
  776. self.in_srs.SetFromUserInput(self.options.s_srs)
  777. self.in_srs_wkt = self.in_srs.ExportToWkt()
  778. else:
  779. self.in_srs_wkt = self.in_ds.GetProjection()
  780. if not self.in_srs_wkt and self.in_ds.GetGCPCount() != 0:
  781. self.in_srs_wkt = self.in_ds.GetGCPProjection()
  782. if self.in_srs_wkt:
  783. self.in_srs = osr.SpatialReference()
  784. self.in_srs.ImportFromWkt(self.in_srs_wkt)
  785. #elif self.options.profile != 'raster':
  786. # 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.")
  787.  
  788. # Spatial Reference System of tiles
  789.  
  790. self.out_srs = osr.SpatialReference()
  791.  
  792. if self.options.profile == 'mercator':
  793. self.out_srs.ImportFromEPSG(900913)
  794. elif self.options.profile == 'geodetic':
  795. self.out_srs.ImportFromEPSG(4326)
  796. else:
  797. self.out_srs = self.in_srs
  798.  
  799. # Are the reference systems the same? Reproject if necessary.
  800.  
  801. self.out_ds = None
  802.  
  803. if self.options.profile in ('mercator', 'geodetic'):
  804.  
  805. if (self.in_ds.GetGeoTransform() == (0.0, 1.0, 0.0, 0.0, 0.0, 1.0)) and (self.in_ds.GetGCPCount() == 0):
  806. self.error("There is no georeference - neither affine transformation (worldfile) nor GCPs. You can generate only 'raster' profile tiles.",
  807. "Either gdal2tiles with parameter -p 'raster' or use another GIS software for georeference e.g. gdal_transform -gcp / -a_ullr / -a_srs")
  808.  
  809. if self.in_srs:
  810.  
  811. if (self.in_srs.ExportToProj4() != self.out_srs.ExportToProj4()) or (self.in_ds.GetGCPCount() != 0):
  812.  
  813. # Generation of VRT dataset in tile projection, default 'nearest neighbour' warping
  814. self.out_ds = gdal.AutoCreateWarpedVRT( self.in_ds, self.in_srs_wkt, self.out_srs.ExportToWkt() )
  815.  
  816. # TODO: HIGH PRIORITY: Correction of AutoCreateWarpedVRT according the max zoomlevel for correct direct warping!!!
  817.  
  818. if self.options.verbose:
  819. print("Warping of the raster by AutoCreateWarpedVRT (result saved into 'tiles.vrt')")
  820. self.out_ds.GetDriver().CreateCopy("tiles.vrt", self.out_ds)
  821.  
  822. # Note: self.in_srs and self.in_srs_wkt contain still the non-warped reference system!!!
  823.  
  824. # Correction of AutoCreateWarpedVRT for NODATA values
  825. if self.in_nodata != []:
  826. fd, tempfilename = tempfile.mkstemp('-gdal2tiles.vrt')
  827. self.out_ds.GetDriver().CreateCopy(tempfilename, self.out_ds)
  828. # open as a text file
  829. s = open(tempfilename).read()
  830. # Add the warping options
  831. s = s.replace("""<GDALWarpOptions>""","""<GDALWarpOptions>
  832. <Option name="INIT_DEST">NO_DATA</Option>
  833. <Option name="UNIFIED_SRC_NODATA">YES</Option>""")
  834. # replace BandMapping tag for NODATA bands....
  835. for i in range(len(self.in_nodata)):
  836. s = s.replace("""<BandMapping src="%i" dst="%i"/>""" % ((i+1),(i+1)),"""<BandMapping src="%i" dst="%i">
  837. <SrcNoDataReal>%i</SrcNoDataReal>
  838. <SrcNoDataImag>0</SrcNoDataImag>
  839. <DstNoDataReal>%i</DstNoDataReal>
  840. <DstNoDataImag>0</DstNoDataImag>
  841. </BandMapping>""" % ((i+1), (i+1), self.in_nodata[i], self.in_nodata[i])) # Or rewrite to white by: , 255 ))
  842. # save the corrected VRT
  843. open(tempfilename,"w").write(s)
  844. # open by GDAL as self.out_ds
  845. self.out_ds = gdal.Open(tempfilename) #, gdal.GA_ReadOnly)
  846. # delete the temporary file
  847. os.unlink(tempfilename)
  848.  
  849. # set NODATA_VALUE metadata
  850. self.out_ds.SetMetadataItem('NODATA_VALUES','%i %i %i' % (self.in_nodata[0],self.in_nodata[1],self.in_nodata[2]))
  851.  
  852. if self.options.verbose:
  853. print("Modified warping result saved into 'tiles1.vrt'")
  854. open("tiles1.vrt","w").write(s)
  855.  
  856. # -----------------------------------
  857. # Correction of AutoCreateWarpedVRT for Mono (1 band) and RGB (3 bands) files without NODATA:
  858. # equivalent of gdalwarp -dstalpha
  859. if self.in_nodata == [] and self.out_ds.RasterCount in [1,3]:
  860. fd, tempfilename = tempfile.mkstemp('-gdal2tiles.vrt')
  861. self.out_ds.GetDriver().CreateCopy(tempfilename, self.out_ds)
  862. # open as a text file
  863. s = open(tempfilename).read()
  864. # Add the warping options
  865. s = s.replace("""<BlockXSize>""","""<VRTRasterBand dataType="Byte" band="%i" subClass="VRTWarpedRasterBand">
  866. <ColorInterp>Alpha</ColorInterp>
  867. </VRTRasterBand>
  868. <BlockXSize>""" % (self.out_ds.RasterCount + 1))
  869. s = s.replace("""</GDALWarpOptions>""", """<DstAlphaBand>%i</DstAlphaBand>
  870. </GDALWarpOptions>""" % (self.out_ds.RasterCount + 1))
  871. s = s.replace("""</WorkingDataType>""", """</WorkingDataType>
  872. <Option name="INIT_DEST">0</Option>""")
  873. # save the corrected VRT
  874. open(tempfilename,"w").write(s)
  875. # open by GDAL as self.out_ds
  876. self.out_ds = gdal.Open(tempfilename) #, gdal.GA_ReadOnly)
  877. # delete the temporary file
  878. os.unlink(tempfilename)
  879.  
  880. if self.options.verbose:
  881. print("Modified -dstalpha warping result saved into 'tiles1.vrt'")
  882. open("tiles1.vrt","w").write(s)
  883. s = '''
  884. '''
  885.  
  886. else:
  887. self.error("Input file has unknown SRS.", "Use --s_srs ESPG:xyz (or similar) to provide source reference system." )
  888.  
  889. if self.out_ds and self.options.verbose:
  890. print("Projected file:", "tiles.vrt", "( %sP x %sL - %s bands)" % (self.out_ds.RasterXSize, self.out_ds.RasterYSize, self.out_ds.RasterCount))
  891.  
  892. if not self.out_ds:
  893. self.out_ds = self.in_ds
  894.  
  895. #
  896. # Here we should have a raster (out_ds) in the correct Spatial Reference system
  897. #
  898.  
  899. # Get alpha band (either directly or from NODATA value)
  900. self.alphaband = self.out_ds.GetRasterBand(1).GetMaskBand()
  901. if (self.alphaband.GetMaskFlags() & gdal.GMF_ALPHA) or self.out_ds.RasterCount==4 or self.out_ds.RasterCount==2:
  902. # TODO: Better test for alpha band in the dataset
  903. self.dataBandsCount = self.out_ds.RasterCount - 1
  904. else:
  905. self.dataBandsCount = self.out_ds.RasterCount
  906.  
  907. # KML test
  908. self.isepsg4326 = False
  909. srs4326 = osr.SpatialReference()
  910. srs4326.ImportFromEPSG(4326)
  911. if self.out_srs and srs4326.ExportToProj4() == self.out_srs.ExportToProj4():
  912. self.kml = True
  913. self.isepsg4326 = True
  914. if self.options.verbose:
  915. print("KML autotest OK!")
  916.  
  917. # Read the georeference
  918.  
  919. self.out_gt = self.out_ds.GetGeoTransform()
  920.  
  921. #originX, originY = self.out_gt[0], self.out_gt[3]
  922. #pixelSize = self.out_gt[1] # = self.out_gt[5]
  923.  
  924. # Test the size of the pixel
  925.  
  926. # MAPTILER - COMMENTED
  927. #if self.out_gt[1] != (-1 * self.out_gt[5]) and self.options.profile != 'raster':
  928. # TODO: Process corectly coordinates with are have swichted Y axis (display in OpenLayers too)
  929. #self.error("Size of the pixel in the output differ for X and Y axes.")
  930.  
  931. # Report error in case rotation/skew is in geotransform (possible only in 'raster' profile)
  932. if (self.out_gt[2], self.out_gt[4]) != (0,0):
  933. self.error("Georeference of the raster contains rotation or skew. Such raster is not supported. Please use gdalwarp first.")
  934. # TODO: Do the warping in this case automaticaly
  935.  
  936. #
  937. # Here we expect: pixel is square, no rotation on the raster
  938. #
  939.  
  940. # Output Bounds - coordinates in the output SRS
  941. self.ominx = self.out_gt[0]
  942. self.omaxx = self.out_gt[0]+self.out_ds.RasterXSize*self.out_gt[1]
  943. self.omaxy = self.out_gt[3]
  944. self.ominy = self.out_gt[3]-self.out_ds.RasterYSize*self.out_gt[1]
  945. # Note: maybe round(x, 14) to avoid the gdal_translate behaviour, when 0 becomes -1e-15
  946.  
  947. if self.options.verbose:
  948. print("Bounds (output srs):", round(self.ominx, 13), self.ominy, self.omaxx, self.omaxy)
  949.  
  950. #
  951. # Calculating ranges for tiles in different zoom levels
  952. #
  953.  
  954. if self.options.profile == 'mercator':
  955.  
  956. self.mercator = GlobalMercator() # from globalmaptiles.py
  957.  
  958. # Function which generates SWNE in LatLong for given tile
  959. self.tileswne = self.mercator.TileLatLonBounds
  960.  
  961. # Generate table with min max tile coordinates for all zoomlevels
  962. self.tminmax = list(range(0,32))
  963. for tz in range(0, 32):
  964. tminx, tminy = self.mercator.MetersToTile( self.ominx, self.ominy, tz )
  965. tmaxx, tmaxy = self.mercator.MetersToTile( self.omaxx, self.omaxy, tz )
  966. # crop tiles extending world limits (+-180,+-90)
  967. tminx, tminy = max(0, tminx), max(0, tminy)
  968. tmaxx, tmaxy = min(2**tz-1, tmaxx), min(2**tz-1, tmaxy)
  969. self.tminmax[tz] = (tminx, tminy, tmaxx, tmaxy)
  970.  
  971. # TODO: Maps crossing 180E (Alaska?)
  972.  
  973. # Get the minimal zoom level (map covers area equivalent to one tile)
  974. if self.tminz == None:
  975. self.tminz = self.mercator.ZoomForPixelSize( self.out_gt[1] * max( self.out_ds.RasterXSize, self.out_ds.RasterYSize) / float(self.tilesize) )
  976.  
  977. # Get the maximal zoom level (closest possible zoom level up on the resolution of raster)
  978. if self.tmaxz == None:
  979. self.tmaxz = self.mercator.ZoomForPixelSize( self.out_gt[1] )
  980.  
  981. if self.options.verbose:
  982. print("Bounds (latlong):", self.mercator.MetersToLatLon( self.ominx, self.ominy), self.mercator.MetersToLatLon( self.omaxx, self.omaxy))
  983. print('MinZoomLevel:', self.tminz)
  984. print("MaxZoomLevel:", self.tmaxz, "(", self.mercator.Resolution( self.tmaxz ),")")
  985.  
  986. if self.options.profile == 'geodetic':
  987.  
  988. self.geodetic = GlobalGeodetic() # from globalmaptiles.py
  989.  
  990. # Function which generates SWNE in LatLong for given tile
  991. self.tileswne = self.geodetic.TileLatLonBounds
  992.  
  993. # Generate table with min max tile coordinates for all zoomlevels
  994. self.tminmax = list(range(0,32))
  995. for tz in range(0, 32):
  996. tminx, tminy = self.geodetic.LatLonToTile( self.ominx, self.ominy, tz )
  997. tmaxx, tmaxy = self.geodetic.LatLonToTile( self.omaxx, self.omaxy, tz )
  998. # crop tiles extending world limits (+-180,+-90)
  999. tminx, tminy = max(0, tminx), max(0, tminy)
  1000. tmaxx, tmaxy = min(2**(tz+1)-1, tmaxx), min(2**tz-1, tmaxy)
  1001. self.tminmax[tz] = (tminx, tminy, tmaxx, tmaxy)
  1002.  
  1003. # TODO: Maps crossing 180E (Alaska?)
  1004.  
  1005. # Get the maximal zoom level (closest possible zoom level up on the resolution of raster)
  1006. if self.tminz == None:
  1007. self.tminz = self.geodetic.ZoomForPixelSize( self.out_gt[1] * max( self.out_ds.RasterXSize, self.out_ds.RasterYSize) / float(self.tilesize) )
  1008.  
  1009. # Get the maximal zoom level (closest possible zoom level up on the resolution of raster)
  1010. if self.tmaxz == None:
  1011. self.tmaxz = self.geodetic.ZoomForPixelSize( self.out_gt[1] )
  1012.  
  1013. if self.options.verbose:
  1014. print("Bounds (latlong):", self.ominx, self.ominy, self.omaxx, self.omaxy)
  1015.  
  1016. if self.options.profile == 'raster':
  1017.  
  1018. log2 = lambda x: math.log10(x) / math.log10(2) # log2 (base 2 logarithm)
  1019.  
  1020. self.nativezoom = int(max( math.ceil(log2(self.out_ds.RasterXSize/float(self.tilesize))),
  1021. math.ceil(log2(self.out_ds.RasterYSize/float(self.tilesize)))))
  1022.  
  1023. if self.options.verbose:
  1024. print("Native zoom of the raster:", self.nativezoom)
  1025.  
  1026. # Get the minimal zoom level (whole raster in one tile)
  1027. if self.tminz == None:
  1028. self.tminz = 0
  1029.  
  1030. # Get the maximal zoom level (native resolution of the raster)
  1031. if self.tmaxz == None:
  1032. self.tmaxz = self.nativezoom
  1033.  
  1034. # Generate table with min max tile coordinates for all zoomlevels
  1035. self.tminmax = list(range(0, self.tmaxz+1))
  1036. self.tsize = list(range(0, self.tmaxz+1))
  1037. for tz in range(0, self.tmaxz+1):
  1038. tsize = 2.0**(self.nativezoom-tz)*self.tilesize
  1039. tminx, tminy = 0, 0
  1040. tmaxx = int(math.ceil( self.out_ds.RasterXSize / tsize )) - 1
  1041. tmaxy = int(math.ceil( self.out_ds.RasterYSize / tsize )) - 1
  1042. self.tsize[tz] = math.ceil(tsize)
  1043. self.tminmax[tz] = (tminx, tminy, tmaxx, tmaxy)
  1044.  
  1045. # Function which generates SWNE in LatLong for given tile
  1046. if self.kml and self.in_srs_wkt:
  1047. self.ct = osr.CoordinateTransformation(self.in_srs, srs4326)
  1048.  
  1049. def rastertileswne(x,y,z):
  1050. pixelsizex = (2**(self.tmaxz-z) * self.out_gt[1]) # X-pixel size in level
  1051. pixelsizey = (2**(self.tmaxz-z) * self.out_gt[1]) # Y-pixel size in level (usually -1*pixelsizex)
  1052. west = self.out_gt[0] + x*self.tilesize*pixelsizex
  1053. east = west + self.tilesize*pixelsizex
  1054. south = self.ominy + y*self.tilesize*pixelsizex
  1055. north = south + self.tilesize*pixelsizex
  1056. if not self.isepsg4326:
  1057. # Transformation to EPSG:4326 (WGS84 datum)
  1058. west, south = self.ct.TransformPoint(west, south)[:2]
  1059. east, north = self.ct.TransformPoint(east, north)[:2]
  1060. return south, west, north, east
  1061.  
  1062. self.tileswne = rastertileswne
  1063. else:
  1064. self.tileswne = lambda x, y, z: (0,0,0,0)
  1065.  
  1066. # -------------------------------------------------------------------------
  1067. def generate_metadata(self):
  1068. """Generation of main metadata files and HTML viewers (metadata related to particular tiles are generated during the tile processing)."""
  1069.  
  1070. if not os.path.exists(self.output):
  1071. os.makedirs(self.output)
  1072.  
  1073. if self.options.profile == 'mercator':
  1074.  
  1075. south, west = self.mercator.MetersToLatLon( self.ominx, self.ominy)
  1076. north, east = self.mercator.MetersToLatLon( self.omaxx, self.omaxy)
  1077. south, west = max(-85.05112878, south), max(-180.0, west)
  1078. north, east = min(85.05112878, north), min(180.0, east)
  1079. self.swne = (south, west, north, east)
  1080.  
  1081. # Generate googlemaps.html
  1082. if self.options.webviewer in ('all','google') and self.options.profile == 'mercator':
  1083. if not self.options.resume or not os.path.exists(os.path.join(self.output, 'googlemaps.html')):
  1084. f = open(os.path.join(self.output, 'googlemaps.html'), 'w')
  1085. f.write( self.generate_googlemaps() )
  1086. f.close()
  1087.  
  1088. # Generate openlayers.html
  1089. if self.options.webviewer in ('all','openlayers'):
  1090. if not self.options.resume or not os.path.exists(os.path.join(self.output, 'openlayers.html')):
  1091. f = open(os.path.join(self.output, 'openlayers.html'), 'w')
  1092. f.write( self.generate_openlayers() )
  1093. f.close()
  1094.  
  1095. elif self.options.profile == 'geodetic':
  1096.  
  1097. west, south = self.ominx, self.ominy
  1098. east, north = self.omaxx, self.omaxy
  1099. south, west = max(-90.0, south), max(-180.0, west)
  1100. north, east = min(90.0, north), min(180.0, east)
  1101. self.swne = (south, west, north, east)
  1102.  
  1103. # Generate openlayers.html
  1104. if self.options.webviewer in ('all','openlayers'):
  1105. if not self.options.resume or not os.path.exists(os.path.join(self.output, 'openlayers.html')):
  1106. f = open(os.path.join(self.output, 'openlayers.html'), 'w')
  1107. f.write( self.generate_openlayers() )
  1108. f.close()
  1109.  
  1110. elif self.options.profile == 'raster':
  1111.  
  1112. west, south = self.ominx, self.ominy
  1113. east, north = self.omaxx, self.omaxy
  1114.  
  1115. self.swne = (south, west, north, east)
  1116.  
  1117. # Generate openlayers.html
  1118. if self.options.webviewer in ('all','openlayers'):
  1119. if not self.options.resume or not os.path.exists(os.path.join(self.output, 'openlayers.html')):
  1120. f = open(os.path.join(self.output, 'openlayers.html'), 'w')
  1121. f.write( self.generate_openlayers() )
  1122. f.close()
  1123.  
  1124.  
  1125. # Generate tilemapresource.xml.
  1126. if not self.options.resume or not os.path.exists(os.path.join(self.output, 'tilemapresource.xml')):
  1127. f = open(os.path.join(self.output, 'tilemapresource.xml'), 'w')
  1128. f.write( self.generate_tilemapresource())
  1129. f.close()
  1130.  
  1131. if self.kml:
  1132. # TODO: Maybe problem for not automatically generated tminz
  1133. # The root KML should contain links to all tiles in the tminz level
  1134. children = []
  1135. xmin, ymin, xmax, ymax = self.tminmax[self.tminz]
  1136. for x in range(xmin, xmax+1):
  1137. for y in range(ymin, ymax+1):
  1138. children.append( [ x, y, self.tminz ] )
  1139. # Generate Root KML
  1140. if self.kml:
  1141. if not self.options.resume or not os.path.exists(os.path.join(self.output, 'doc.kml')):
  1142. f = open(os.path.join(self.output, 'doc.kml'), 'w')
  1143. f.write( self.generate_kml( None, None, None, children) )
  1144. f.close()
  1145.  
  1146. # -------------------------------------------------------------------------
  1147. def generate_base_tiles(self, cpu):
  1148. """Generation of the base tiles (the lowest in the pyramid) directly from the input raster"""
  1149.  
  1150. if self.options.verbose:
  1151. #mx, my = self.out_gt[0], self.out_gt[3] # OriginX, OriginY
  1152. #px, py = self.mercator.MetersToPixels( mx, my, self.tmaxz)
  1153. #print "Pixel coordinates:", px, py, (mx, my)
  1154. print('')
  1155. print("Tiles generated from the max zoom level:")
  1156. print("----------------------------------------")
  1157. print('')
  1158.  
  1159.  
  1160. # Set the bounds
  1161. tminx, tminy, tmaxx, tmaxy = self.tminmax[self.tmaxz]
  1162.  
  1163. # Just the center tile
  1164. #tminx = tminx+ (tmaxx - tminx)/2
  1165. #tminy = tminy+ (tmaxy - tminy)/2
  1166. #tmaxx = tminx
  1167. #tmaxy = tminy
  1168.  
  1169. ds = self.out_ds
  1170. tilebands = self.dataBandsCount + 1
  1171. querysize = self.querysize
  1172.  
  1173. if self.options.verbose:
  1174. print("dataBandsCount: ", self.dataBandsCount)
  1175. print("tilebands: ", tilebands)
  1176.  
  1177. #print tminx, tminy, tmaxx, tmaxy
  1178. tcount = (1+abs(tmaxx-tminx)) * (1+abs(tmaxy-tminy))
  1179. #print tcount
  1180. ti = 0
  1181.  
  1182. tz = self.tmaxz
  1183. for ty in range(tmaxy, tminy-1, -1): #range(tminy, tmaxy+1):
  1184. for tx in range(tminx, tmaxx+1):
  1185.  
  1186. if self.stopped:
  1187. break
  1188. ti += 1
  1189. if (ti - 1) % self.options.processes != cpu:
  1190. continue
  1191. tilefilename = os.path.join(self.output, str(tz), str(tx), "%s.%s" % (ty, self.tileext))
  1192. if self.options.verbose:
  1193. print(ti,'/',tcount, tilefilename) #, "( TileMapService: z / x / y )"
  1194.  
  1195. if self.options.resume and os.path.exists(tilefilename):
  1196. if self.options.verbose:
  1197. print("Tile generation skiped because of --resume")
  1198. else:
  1199. queue.put(tcount)
  1200. continue
  1201.  
  1202. # Create directories for the tile
  1203. if not os.path.exists(os.path.dirname(tilefilename)):
  1204. os.makedirs(os.path.dirname(tilefilename))
  1205.  
  1206. if self.options.profile == 'mercator':
  1207. # Tile bounds in EPSG:900913
  1208. b = self.mercator.TileBounds(tx, ty, tz)
  1209. elif self.options.profile == 'geodetic':
  1210. b = self.geodetic.TileBounds(tx, ty, tz)
  1211.  
  1212. #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)
  1213.  
  1214. # Don't scale up by nearest neighbour, better change the querysize
  1215. # to the native resolution (and return smaller query tile) for scaling
  1216.  
  1217. if self.options.profile in ('mercator','geodetic'):
  1218. rb, wb = self.geo_query( ds, b[0], b[3], b[2], b[1])
  1219. nativesize = wb[0]+wb[2] # Pixel size in the raster covering query geo extent
  1220. if self.options.verbose:
  1221. print("\tNative Extent (querysize",nativesize,"): ", rb, wb)
  1222.  
  1223. # Tile bounds in raster coordinates for ReadRaster query
  1224. rb, wb = self.geo_query( ds, b[0], b[3], b[2], b[1], querysize=querysize)
  1225.  
  1226. rx, ry, rxsize, rysize = rb
  1227. wx, wy, wxsize, wysize = wb
  1228.  
  1229. else: # 'raster' profile:
  1230.  
  1231. tsize = int(self.tsize[tz]) # tilesize in raster coordinates for actual zoom
  1232. xsize = self.out_ds.RasterXSize # size of the raster in pixels
  1233. ysize = self.out_ds.RasterYSize
  1234. if tz >= self.nativezoom:
  1235. querysize = self.tilesize # int(2**(self.nativezoom-tz) * self.tilesize)
  1236.  
  1237. rx = (tx) * tsize
  1238. rxsize = 0
  1239. if tx == tmaxx:
  1240. rxsize = xsize % tsize
  1241. if rxsize == 0:
  1242. rxsize = tsize
  1243.  
  1244. rysize = 0
  1245. if ty == tmaxy:
  1246. rysize = ysize % tsize
  1247. if rysize == 0:
  1248. rysize = tsize
  1249. ry = ysize - (ty * tsize) - rysize
  1250.  
  1251. wx, wy = 0, 0
  1252. wxsize, wysize = int(rxsize/float(tsize) * self.tilesize), int(rysize/float(tsize) * self.tilesize)
  1253. if wysize != self.tilesize:
  1254. wy = self.tilesize - wysize
  1255.  
  1256. if self.options.verbose:
  1257. print("\tReadRaster Extent: ", (rx, ry, rxsize, rysize), (wx, wy, wxsize, wysize))
  1258.  
  1259. # Query is in 'nearest neighbour' but can be bigger in then the tilesize
  1260. # We scale down the query to the tilesize by supplied algorithm.
  1261.  
  1262. # Tile dataset in memory
  1263. dstile = self.mem_drv.Create('', self.tilesize, self.tilesize, tilebands)
  1264. data = ds.ReadRaster(rx, ry, rxsize, rysize, wxsize, wysize, band_list=list(range(1,self.dataBandsCount+1)))
  1265. alpha = self.alphaband.ReadRaster(rx, ry, rxsize, rysize, wxsize, wysize)
  1266.  
  1267. if self.tilesize == querysize:
  1268. # Use the ReadRaster result directly in tiles ('nearest neighbour' query)
  1269. dstile.WriteRaster(wx, wy, wxsize, wysize, data, band_list=list(range(1,self.dataBandsCount+1)))
  1270. dstile.WriteRaster(wx, wy, wxsize, wysize, alpha, band_list=[tilebands])
  1271.  
  1272. # Note: For source drivers based on WaveLet compression (JPEG2000, ECW, MrSID)
  1273. # the ReadRaster function returns high-quality raster (not ugly nearest neighbour)
  1274. # TODO: Use directly 'near' for WaveLet files
  1275. else:
  1276. # Big ReadRaster query in memory scaled to the tilesize - all but 'near' algo
  1277. dsquery = self.mem_drv.Create('', querysize, querysize, tilebands)
  1278. # TODO: fill the null value in case a tile without alpha is produced (now only png tiles are supported)
  1279. #for i in range(1, tilebands+1):
  1280. # dsquery.GetRasterBand(1).Fill(tilenodata)
  1281. dsquery.WriteRaster(wx, wy, wxsize, wysize, data, band_list=list(range(1,self.dataBandsCount+1)))
  1282. dsquery.WriteRaster(wx, wy, wxsize, wysize, alpha, band_list=[tilebands])
  1283.  
  1284. self.scale_query_to_tile(dsquery, dstile, tilefilename)
  1285. del dsquery
  1286.  
  1287. del data
  1288.  
  1289. if self.options.resampling != 'antialias':
  1290. # Write a copy of tile to png/jpg
  1291. self.out_drv.CreateCopy(tilefilename, dstile, strict=0)
  1292.  
  1293. del dstile
  1294.  
  1295. # Create a KML file for this tile.
  1296. if self.kml:
  1297. kmlfilename = os.path.join(self.output, str(tz), str(tx), '%d.kml' % ty)
  1298. if not self.options.resume or not os.path.exists(kmlfilename):
  1299. f = open( kmlfilename, 'w')
  1300. f.write( self.generate_kml( tx, ty, tz ))
  1301. f.close()
  1302.  
  1303. if not self.options.verbose:
  1304. queue.put(tcount)
  1305.  
  1306. # -------------------------------------------------------------------------
  1307. def generate_overview_tiles(self, cpu, tz):
  1308. """Generation of the overview tiles (higher in the pyramid) based on existing tiles"""
  1309.  
  1310. tilebands = self.dataBandsCount + 1
  1311.  
  1312. # Usage of existing tiles: from 4 underlying tiles generate one as overview.
  1313.  
  1314. tcount = 0
  1315. for z in range(self.tmaxz-1, self.tminz-1, -1):
  1316. tminx, tminy, tmaxx, tmaxy = self.tminmax[z]
  1317. tcount += (1+abs(tmaxx-tminx)) * (1+abs(tmaxy-tminy))
  1318.  
  1319. ti = 0
  1320.  
  1321. # querysize = tilesize * 2
  1322.  
  1323. tminx, tminy, tmaxx, tmaxy = self.tminmax[tz]
  1324. for ty in range(tmaxy, tminy-1, -1): #range(tminy, tmaxy+1):
  1325. for tx in range(tminx, tmaxx+1):
  1326.  
  1327. if self.stopped:
  1328. break
  1329.  
  1330. ti += 1
  1331. if (ti - 1) % self.options.processes != cpu:
  1332. continue
  1333. tilefilename = os.path.join( self.output, str(tz), str(tx), "%s.%s" % (ty, self.tileext) )
  1334.  
  1335. if self.options.verbose:
  1336. print(ti,'/',tcount, tilefilename) #, "( TileMapService: z / x / y )"
  1337.  
  1338. if self.options.resume and os.path.exists(tilefilename):
  1339. if self.options.verbose:
  1340. print("Tile generation skiped because of --resume")
  1341. else:
  1342. queue.put(tcount)
  1343. continue
  1344.  
  1345. # Create directories for the tile
  1346. if not os.path.exists(os.path.dirname(tilefilename)):
  1347. os.makedirs(os.path.dirname(tilefilename))
  1348.  
  1349. dsquery = self.mem_drv.Create('', 2*self.tilesize, 2*self.tilesize, tilebands)
  1350. # TODO: fill the null value
  1351. #for i in range(1, tilebands+1):
  1352. # dsquery.GetRasterBand(1).Fill(tilenodata)
  1353. dstile = self.mem_drv.Create('', self.tilesize, self.tilesize, tilebands)
  1354.  
  1355. # TODO: Implement more clever walking on the tiles with cache functionality
  1356. # probably walk should start with reading of four tiles from top left corner
  1357. # Hilbert curve...
  1358.  
  1359. children = []
  1360. # Read the tiles and write them to query window
  1361. for y in range(2*ty,2*ty+2):
  1362. for x in range(2*tx,2*tx+2):
  1363. minx, miny, maxx, maxy = self.tminmax[tz+1]
  1364. if x >= minx and x <= maxx and y >= miny and y <= maxy:
  1365. dsquerytile = gdal.Open( os.path.join( self.output, str(tz+1), str(x), "%s.%s" % (y, self.tileext)), gdal.GA_ReadOnly)
  1366. if (ty==0 and y==1) or (ty!=0 and (y % (2*ty)) != 0):
  1367. tileposy = 0
  1368. else:
  1369. tileposy = self.tilesize
  1370. if tx:
  1371. tileposx = x % (2*tx) * self.tilesize
  1372. elif tx==0 and x==1:
  1373. tileposx = self.tilesize
  1374. else:
  1375. tileposx = 0
  1376. dsquery.WriteRaster( tileposx, tileposy, self.tilesize, self.tilesize,
  1377. dsquerytile.ReadRaster(0,0,self.tilesize,self.tilesize),
  1378. band_list=list(range(1,tilebands+1)))
  1379. children.append( [x, y, tz+1] )
  1380.  
  1381. self.scale_query_to_tile(dsquery, dstile, tilefilename)
  1382. # Write a copy of tile to png/jpg
  1383. if self.options.resampling != 'antialias':
  1384. # Write a copy of tile to png/jpg
  1385. self.out_drv.CreateCopy(tilefilename, dstile, strict=0)
  1386.  
  1387. if self.options.verbose:
  1388. 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))
  1389.  
  1390. # Create a KML file for this tile.
  1391. if self.kml:
  1392. f = open( os.path.join(self.output, '%d/%d/%d.kml' % (tz, tx, ty)), 'w')
  1393. f.write( self.generate_kml( tx, ty, tz, children ) )
  1394. f.close()
  1395.  
  1396. if not self.options.verbose:
  1397. queue.put(tcount)
  1398.  
  1399.  
  1400. # -------------------------------------------------------------------------
  1401. def geo_query(self, ds, ulx, uly, lrx, lry, querysize = 0):
  1402. """For given dataset and query in cartographic coordinates
  1403. returns parameters for ReadRaster() in raster coordinates and
  1404. x/y shifts (for border tiles). If the querysize is not given, the
  1405. extent is returned in the native resolution of dataset ds."""
  1406.  
  1407. geotran = ds.GetGeoTransform()
  1408. rx= int((ulx - geotran[0]) / geotran[1] + 0.001)
  1409. ry= int((uly - geotran[3]) / geotran[5] + 0.001)
  1410. rxsize= int((lrx - ulx) / geotran[1] + 0.5)
  1411. rysize= int((lry - uly) / geotran[5] + 0.5)
  1412.  
  1413. if not querysize:
  1414. wxsize, wysize = rxsize, rysize
  1415. else:
  1416. wxsize, wysize = querysize, querysize
  1417.  
  1418. # Coordinates should not go out of the bounds of the raster
  1419. wx = 0
  1420. if rx < 0:
  1421. rxshift = abs(rx)
  1422. wx = int( wxsize * (float(rxshift) / rxsize) )
  1423. wxsize = wxsize - wx
  1424. rxsize = rxsize - int( rxsize * (float(rxshift) / rxsize) )
  1425. rx = 0
  1426. if rx+rxsize > ds.RasterXSize:
  1427. wxsize = int( wxsize * (float(ds.RasterXSize - rx) / rxsize) )
  1428. rxsize = ds.RasterXSize - rx
  1429.  
  1430. wy = 0
  1431. if ry < 0:
  1432. ryshift = abs(ry)
  1433. wy = int( wysize * (float(ryshift) / rysize) )
  1434. wysize = wysize - wy
  1435. rysize = rysize - int( rysize * (float(ryshift) / rysize) )
  1436. ry = 0
  1437. if ry+rysize > ds.RasterYSize:
  1438. wysize = int( wysize * (float(ds.RasterYSize - ry) / rysize) )
  1439. rysize = ds.RasterYSize - ry
  1440.  
  1441. return (rx, ry, rxsize, rysize), (wx, wy, wxsize, wysize)
  1442.  
  1443. # -------------------------------------------------------------------------
  1444. def scale_query_to_tile(self, dsquery, dstile, tilefilename=''):
  1445. """Scales down query dataset to the tile dataset"""
  1446.  
  1447. querysize = dsquery.RasterXSize
  1448. tilesize = dstile.RasterXSize
  1449. tilebands = dstile.RasterCount
  1450.  
  1451. if self.options.resampling == 'average':
  1452.  
  1453. # Function: gdal.RegenerateOverview()
  1454. for i in range(1,tilebands+1):
  1455. # Black border around NODATA
  1456. #if i != 4:
  1457. # dsquery.GetRasterBand(i).SetNoDataValue(0)
  1458. res = gdal.RegenerateOverview( dsquery.GetRasterBand(i),
  1459. dstile.GetRasterBand(i), 'average' )
  1460. if res != 0:
  1461. self.error("RegenerateOverview() failed on %s, error %d" % (tilefilename, res))
  1462.  
  1463. elif self.options.resampling == 'antialias':
  1464.  
  1465. # Scaling by PIL (Python Imaging Library) - improved Lanczos
  1466. array = numpy.zeros((querysize, querysize, tilebands), numpy.uint8)
  1467. for i in range(tilebands):
  1468. array[:,:,i] = gdalarray.BandReadAsArray(dsquery.GetRasterBand(i+1), 0, 0, querysize, querysize)
  1469. im = Image.fromarray(array, 'RGBA') # Always four bands
  1470. im1 = im.resize((tilesize,tilesize), Image.ANTIALIAS)
  1471. if os.path.exists(tilefilename):
  1472. im0 = Image.open(tilefilename)
  1473. im1 = Image.composite(im1, im0, im1)
  1474. im1.save(tilefilename,self.tiledriver)
  1475.  
  1476. else:
  1477.  
  1478. # Other algorithms are implemented by gdal.ReprojectImage().
  1479. dsquery.SetGeoTransform( (0.0, tilesize / float(querysize), 0.0, 0.0, 0.0, tilesize / float(querysize)) )
  1480. dstile.SetGeoTransform( (0.0, 1.0, 0.0, 0.0, 0.0, 1.0) )
  1481.  
  1482. res = gdal.ReprojectImage(dsquery, dstile, None, None, self.resampling)
  1483. if res != 0:
  1484. self.error("ReprojectImage() failed on %s, error %d" % (tilefilename, res))
  1485.  
  1486. # -------------------------------------------------------------------------
  1487. def generate_tilemapresource(self):
  1488. """
  1489. Template for tilemapresource.xml. Returns filled string. Expected variables:
  1490. title, north, south, east, west, isepsg4326, projection, publishurl,
  1491. zoompixels, tilesize, tileformat, profile
  1492. """
  1493.  
  1494. args = {}
  1495. args['title'] = self.options.title
  1496. args['south'], args['west'], args['north'], args['east'] = self.swne
  1497. args['tilesize'] = self.tilesize
  1498. args['tileformat'] = self.tileext
  1499. args['publishurl'] = self.options.url
  1500. args['profile'] = self.options.profile
  1501.  
  1502. if self.options.profile == 'mercator':
  1503. args['srs'] = "EPSG:900913"
  1504. elif self.options.profile == 'geodetic':
  1505. args['srs'] = "EPSG:4326"
  1506. elif self.options.s_srs:
  1507. args['srs'] = self.options.s_srs
  1508. elif self.out_srs:
  1509. args['srs'] = self.out_srs.ExportToWkt()
  1510. else:
  1511. args['srs'] = ""
  1512.  
  1513. s = """<?xml version="1.0" encoding="utf-8"?>
  1514. <TileMap version="1.0.0" tilemapservice="http://tms.osgeo.org/1.0.0">
  1515. <Title>%(title)s</Title>
  1516. <Abstract></Abstract>
  1517. <SRS>%(srs)s</SRS>
  1518. <BoundingBox minx="%(south).14f" miny="%(west).14f" maxx="%(north).14f" maxy="%(east).14f"/>
  1519. <Origin x="%(south).14f" y="%(west).14f"/>
  1520. <TileFormat width="%(tilesize)d" height="%(tilesize)d" mime-type="image/%(tileformat)s" extension="%(tileformat)s"/>
  1521. <TileSets profile="%(profile)s">
  1522. """ % args
  1523. for z in range(self.tminz, self.tmaxz+1):
  1524. if self.options.profile == 'raster':
  1525. s += """ <TileSet href="%s%d" units-per-pixel="%.14f" order="%d"/>\n""" % (args['publishurl'], z, (2**(self.nativezoom-z) * self.out_gt[1]), z)
  1526. elif self.options.profile == 'mercator':
  1527. s += """ <TileSet href="%s%d" units-per-pixel="%.14f" order="%d"/>\n""" % (args['publishurl'], z, 156543.0339/2**z, z)
  1528. elif self.options.profile == 'geodetic':
  1529. s += """ <TileSet href="%s%d" units-per-pixel="%.14f" order="%d"/>\n""" % (args['publishurl'], z, 0.703125/2**z, z)
  1530. s += """ </TileSets>
  1531. </TileMap>
  1532. """
  1533. return s
  1534.  
  1535. # -------------------------------------------------------------------------
  1536. def generate_kml(self, tx, ty, tz, children = [], **args ):
  1537. """
  1538. Template for the KML. Returns filled string.
  1539. """
  1540. args['tx'], args['ty'], args['tz'] = tx, ty, tz
  1541. args['tileformat'] = self.tileext
  1542. if 'tilesize' not in args:
  1543. args['tilesize'] = self.tilesize
  1544.  
  1545. if 'minlodpixels' not in args:
  1546. args['minlodpixels'] = int( args['tilesize'] / 2 ) # / 2.56) # default 128
  1547. if 'maxlodpixels' not in args:
  1548. args['maxlodpixels'] = int( args['tilesize'] * 8 ) # 1.7) # default 2048 (used to be -1)
  1549. if children == []:
  1550. args['maxlodpixels'] = -1
  1551.  
  1552. if tx==None:
  1553. tilekml = False
  1554. args['title'] = self.options.title
  1555. else:
  1556. tilekml = True
  1557. args['title'] = "%d/%d/%d.kml" % (tz, tx, ty)
  1558. args['south'], args['west'], args['north'], args['east'] = self.tileswne(tx, ty, tz)
  1559.  
  1560. if tx == 0:
  1561. args['drawOrder'] = 2 * tz + 1
  1562. elif tx != None:
  1563. args['drawOrder'] = 2 * tz
  1564. else:
  1565. args['drawOrder'] = 0
  1566.  
  1567. url = self.options.url
  1568. if not url:
  1569. if tilekml:
  1570. url = "../../"
  1571. else:
  1572. url = ""
  1573.  
  1574. s = """<?xml version="1.0" encoding="utf-8"?>
  1575. <kml xmlns="http://earth.google.com/kml/2.1">
  1576. <Document>
  1577. <Name>%(title)s</Name>
  1578. <Description></Description>
  1579. <Style>
  1580. <ListStyle id="hideChildren">
  1581. <listItemType>checkHideChildren</listItemType>
  1582. </ListStyle>
  1583. </Style>""" % args
  1584. if tilekml:
  1585. s += """
  1586. <Region>
  1587. <Lod>
  1588. <minLodPixels>%(minlodpixels)d</minLodPixels>
  1589. <maxLodPixels>%(maxlodpixels)d</maxLodPixels>
  1590. </Lod>
  1591. <LatLonAltBox>
  1592. <north>%(north).14f</north>
  1593. <south>%(south).14f</south>
  1594. <east>%(east).14f</east>
  1595. <west>%(west).14f</west>
  1596. </LatLonAltBox>
  1597. </Region>
  1598. <GroundOverlay>
  1599. <drawOrder>%(drawOrder)d</drawOrder>
  1600. <Icon>
  1601. <href>%(ty)d.%(tileformat)s</href>
  1602. </Icon>
  1603. <LatLonBox>
  1604. <north>%(north).14f</north>
  1605. <south>%(south).14f</south>
  1606. <east>%(east).14f</east>
  1607. <west>%(west).14f</west>
  1608. </LatLonBox>
  1609. </GroundOverlay>
  1610. """ % args
  1611.  
  1612. for cx, cy, cz in children:
  1613. csouth, cwest, cnorth, ceast = self.tileswne(cx, cy, cz)
  1614. s += """
  1615. <NetworkLink>
  1616. <name>%d/%d/%d.%s</name>
  1617. <Region>
  1618. <Lod>
  1619. <minLodPixels>%d</minLodPixels>
  1620. <maxLodPixels>-1</maxLodPixels>
  1621. </Lod>
  1622. <LatLonAltBox>
  1623. <north>%.14f</north>
  1624. <south>%.14f</south>
  1625. <east>%.14f</east>
  1626. <west>%.14f</west>
  1627. </LatLonAltBox>
  1628. </Region>
  1629. <Link>
  1630. <href>%s%d/%d/%d.kml</href>
  1631. <viewRefreshMode>onRegion</viewRefreshMode>
  1632. <viewFormat/>
  1633. </Link>
  1634. </NetworkLink>
  1635. """ % (cz, cx, cy, args['tileformat'], args['minlodpixels'], cnorth, csouth, ceast, cwest, url, cz, cx, cy)
  1636.  
  1637. s += """ </Document>
  1638. </kml>
  1639. """
  1640. return s
  1641.  
  1642. # -------------------------------------------------------------------------
  1643. def generate_googlemaps(self):
  1644. """
  1645. Template for googlemaps.html implementing Overlay of tiles for 'mercator' profile.
  1646. It returns filled string. Expected variables:
  1647. title, googlemapskey, north, south, east, west, minzoom, maxzoom, tilesize, tileformat, publishurl
  1648. """
  1649. args = {}
  1650. args['title'] = self.options.title
  1651. args['googlemapskey'] = self.options.googlekey
  1652. args['south'], args['west'], args['north'], args['east'] = self.swne
  1653. args['minzoom'] = self.tminz
  1654. args['maxzoom'] = self.tmaxz
  1655. args['tilesize'] = self.tilesize
  1656. args['tileformat'] = self.tileext
  1657. args['publishurl'] = self.options.url
  1658. args['copyright'] = self.options.copyright
  1659.  
  1660. s = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  1661. <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
  1662. <head>
  1663. <title>%(title)s</title>
  1664. <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  1665. <meta http-equiv='imagetoolbar' content='no'/>
  1666. <style type="text/css"> v\:* {behavior:url(#default#VML);}
  1667. html, body { overflow: hidden; padding: 0; height: 100%%; width: 100%%; font-family: 'Lucida Grande',Geneva,Arial,Verdana,sans-serif; }
  1668. body { margin: 10px; background: #fff; }
  1669. h1 { margin: 0; padding: 6px; border:0; font-size: 20pt; }
  1670. #header { height: 43px; padding: 0; background-color: #eee; border: 1px solid #888; }
  1671. #subheader { height: 12px; text-align: right; font-size: 10px; color: #555;}
  1672. #map { height: 95%%; border: 1px solid #888; }
  1673. </style>
  1674. <script src='http://maps.google.com/maps?file=api&amp;v=2&amp;key=%(googlemapskey)s' type='text/javascript'></script>
  1675. <script type="text/javascript">
  1676. //<![CDATA[
  1677.  
  1678. /*
  1679. * Constants for given map
  1680. * TODO: read it from tilemapresource.xml
  1681. */
  1682.  
  1683. var mapBounds = new GLatLngBounds(new GLatLng(%(south)s, %(west)s), new GLatLng(%(north)s, %(east)s));
  1684. var mapMinZoom = %(minzoom)s;
  1685. var mapMaxZoom = %(maxzoom)s;
  1686.  
  1687. var opacity = 0.75;
  1688. var map;
  1689. var hybridOverlay;
  1690.  
  1691. /*
  1692. * Create a Custom Opacity GControl
  1693. * http://www.maptiler.org/google-maps-overlay-opacity-control/
  1694. */
  1695.  
  1696. var CTransparencyLENGTH = 58;
  1697. // maximum width that the knob can move (slide width minus knob width)
  1698.  
  1699. function CTransparencyControl( overlay ) {
  1700. this.overlay = overlay;
  1701. this.opacity = overlay.getTileLayer().getOpacity();
  1702. }
  1703. CTransparencyControl.prototype = new GControl();
  1704.  
  1705. // This function positions the slider to match the specified opacity
  1706. CTransparencyControl.prototype.setSlider = function(pos) {
  1707. var left = Math.round((CTransparencyLENGTH*pos));
  1708. this.slide.left = left;
  1709. this.knob.style.left = left+"px";
  1710. this.knob.style.top = "0px";
  1711. }
  1712.  
  1713. // This function reads the slider and sets the overlay opacity level
  1714. CTransparencyControl.prototype.setOpacity = function() {
  1715. // set the global variable
  1716. opacity = this.slide.left/CTransparencyLENGTH;
  1717. this.map.clearOverlays();
  1718. this.map.addOverlay(this.overlay, { zPriority: 0 });
  1719. if (this.map.getCurrentMapType() == G_HYBRID_MAP) {
  1720. this.map.addOverlay(hybridOverlay);
  1721. }
  1722. }
  1723.  
  1724. // This gets called by the API when addControl(new CTransparencyControl())
  1725. CTransparencyControl.prototype.initialize = function(map) {
  1726. var that=this;
  1727. this.map = map;
  1728.  
  1729. // Is this MSIE, if so we need to use AlphaImageLoader
  1730. var agent = navigator.userAgent.toLowerCase();
  1731. if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){this.ie = true} else {this.ie = false}
  1732.  
  1733. // create the background graphic as a <div> containing an image
  1734. var container = document.createElement("div");
  1735. container.style.width="70px";
  1736. container.style.height="21px";
  1737.  
  1738. // Handle transparent PNG files in MSIE
  1739. if (this.ie) {
  1740. var loader = "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://www.maptiler.org/img/opacity-slider.png', sizingMethod='crop');";
  1741. container.innerHTML = '<div style="height:21px; width:70px; ' +loader+ '" ></div>';
  1742. } else {
  1743. container.innerHTML = '<div style="height:21px; width:70px; background-image: url(http://www.maptiler.org/img/opacity-slider.png)" ></div>';
  1744. }
  1745.  
  1746. // create the knob as a GDraggableObject
  1747. // Handle transparent PNG files in MSIE
  1748. if (this.ie) {
  1749. var loader = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://www.maptiler.org/img/opacity-slider.png', sizingMethod='crop');";
  1750. this.knob = document.createElement("div");
  1751. this.knob.style.height="21px";
  1752. this.knob.style.width="13px";
  1753. this.knob.style.overflow="hidden";
  1754. this.knob_img = document.createElement("div");
  1755. this.knob_img.style.height="21px";
  1756. this.knob_img.style.width="83px";
  1757. this.knob_img.style.filter=loader;
  1758. this.knob_img.style.position="relative";
  1759. this.knob_img.style.left="-70px";
  1760. this.knob.appendChild(this.knob_img);
  1761. } else {
  1762. this.knob = document.createElement("div");
  1763. this.knob.style.height="21px";
  1764. this.knob.style.width="13px";
  1765. this.knob.style.backgroundImage="url(http://www.maptiler.org/img/opacity-slider.png)";
  1766. this.knob.style.backgroundPosition="-70px 0px";
  1767. }
  1768. container.appendChild(this.knob);
  1769. this.slide=new GDraggableObject(this.knob, {container:container});
  1770. this.slide.setDraggableCursor('pointer');
  1771. this.slide.setDraggingCursor('pointer');
  1772. this.container = container;
  1773.  
  1774. // attach the control to the map
  1775. map.getContainer().appendChild(container);
  1776.  
  1777. // init slider
  1778. this.setSlider(this.opacity);
  1779.  
  1780. // Listen for the slider being moved and set the opacity
  1781. GEvent.addListener(this.slide, "dragend", function() {that.setOpacity()});
  1782. //GEvent.addListener(this.container, "click", function( x, y ) { alert(x, y) });
  1783.  
  1784. return container;
  1785. }
  1786.  
  1787. // Set the default position for the control
  1788. CTransparencyControl.prototype.getDefaultPosition = function() {
  1789. return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 47));
  1790. }
  1791.  
  1792. /*
  1793. * Full-screen Window Resize
  1794. */
  1795.  
  1796. function getWindowHeight() {
  1797. if (self.innerHeight) return self.innerHeight;
  1798. if (document.documentElement && document.documentElement.clientHeight)
  1799. return document.documentElement.clientHeight;
  1800. if (document.body) return document.body.clientHeight;
  1801. return 0;
  1802. }
  1803.  
  1804. function getWindowWidth() {
  1805. if (self.innerWidth) return self.innerWidth;
  1806. if (document.documentElement && document.documentElement.clientWidth)
  1807. return document.documentElement.clientWidth;
  1808. if (document.body) return document.body.clientWidth;
  1809. return 0;
  1810. }
  1811.  
  1812. function resize() {
  1813. var map = document.getElementById("map");
  1814. var header = document.getElementById("header");
  1815. var subheader = document.getElementById("subheader");
  1816. map.style.height = (getWindowHeight()-80) + "px";
  1817. map.style.width = (getWindowWidth()-20) + "px";
  1818. header.style.width = (getWindowWidth()-20) + "px";
  1819. subheader.style.width = (getWindowWidth()-20) + "px";
  1820. // map.checkResize();
  1821. }
  1822.  
  1823.  
  1824. /*
  1825. * Main load function:
  1826. */
  1827.  
  1828. function load() {
  1829.  
  1830. if (GBrowserIsCompatible()) {
  1831.  
  1832. // Bug in the Google Maps: Copyright for Overlay is not correctly displayed
  1833. var gcr = GMapType.prototype.getCopyrights;
  1834. GMapType.prototype.getCopyrights = function(bounds,zoom) {
  1835. return ["%(copyright)s"].concat(gcr.call(this,bounds,zoom));
  1836. }
  1837.  
  1838. map = new GMap2( document.getElementById("map"), { backgroundColor: '#fff' } );
  1839.  
  1840. map.addMapType(G_PHYSICAL_MAP);
  1841. map.setMapType(G_PHYSICAL_MAP);
  1842.  
  1843. map.setCenter( mapBounds.getCenter(), map.getBoundsZoomLevel( mapBounds ));
  1844.  
  1845. hybridOverlay = new GTileLayerOverlay( G_HYBRID_MAP.getTileLayers()[1] );
  1846. GEvent.addListener(map, "maptypechanged", function() {
  1847. if (map.getCurrentMapType() == G_HYBRID_MAP) {
  1848. map.addOverlay(hybridOverlay);
  1849. } else {
  1850. map.removeOverlay(hybridOverlay);
  1851. }
  1852. } );
  1853.  
  1854. var tilelayer = new GTileLayer(GCopyrightCollection(''), mapMinZoom, mapMaxZoom);
  1855. var mercator = new GMercatorProjection(mapMaxZoom+1);
  1856. tilelayer.getTileUrl = function(tile,zoom) {
  1857. if ((zoom < mapMinZoom) || (zoom > mapMaxZoom)) {
  1858. return "http://www.maptiler.org/img/none.png";
  1859. }
  1860. var ymax = 1 << zoom;
  1861. var y = ymax - tile.y -1;
  1862. var tileBounds = new GLatLngBounds(
  1863. mercator.fromPixelToLatLng( new GPoint( (tile.x)*256, (tile.y+1)*256 ) , zoom ),
  1864. mercator.fromPixelToLatLng( new GPoint( (tile.x+1)*256, (tile.y)*256 ) , zoom )
  1865. );
  1866. if (mapBounds.intersects(tileBounds)) {
  1867. return zoom+"/"+tile.x+"/"+y+".png";
  1868. } else {
  1869. return "http://www.maptiler.org/img/none.png";
  1870. }
  1871. }
  1872. // IE 7-: support for PNG alpha channel
  1873. // Unfortunately, the opacity for whole overlay is then not changeable, either or...
  1874. tilelayer.isPng = function() { return true;};
  1875. tilelayer.getOpacity = function() { return opacity; }
  1876.  
  1877. overlay = new GTileLayerOverlay( tilelayer );
  1878. map.addOverlay(overlay);
  1879.  
  1880. map.addControl(new GLargeMapControl());
  1881. map.addControl(new GHierarchicalMapTypeControl());
  1882. map.addControl(new CTransparencyControl( overlay ));
  1883. """ % args
  1884. if self.kml:
  1885. s += """
  1886. map.addMapType(G_SATELLITE_3D_MAP);
  1887. map.getEarthInstance(getEarthInstanceCB);
  1888. """
  1889. s += """
  1890.  
  1891. map.enableContinuousZoom();
  1892. map.enableScrollWheelZoom();
  1893.  
  1894. map.setMapType(G_HYBRID_MAP);
  1895. }
  1896. resize();
  1897. }
  1898. """
  1899. if self.kml:
  1900. s += """
  1901. function getEarthInstanceCB(object) {
  1902. var ge = object;
  1903.  
  1904. if (ge) {
  1905. var url = document.location.toString();
  1906. url = url.substr(0,url.lastIndexOf('/'))+'/doc.kml';
  1907. var link = ge.createLink("");
  1908. if ("%(publishurl)s") { link.setHref("%(publishurl)s/doc.kml") }
  1909. else { link.setHref(url) };
  1910. var networkLink = ge.createNetworkLink("");
  1911. networkLink.setName("TMS Map Overlay");
  1912. networkLink.setFlyToView(true);
  1913. networkLink.setLink(link);
  1914. ge.getFeatures().appendChild(networkLink);
  1915. } else {
  1916. // alert("You should open a KML in Google Earth");
  1917. // add div with the link to generated KML... - maybe JavaScript redirect to the URL of KML?
  1918. }
  1919. }
  1920. """ % args
  1921. s += """
  1922. onresize=function(){ resize(); };
  1923.  
  1924. //]]>
  1925. </script>
  1926. </head>
  1927. <body onload="load()">
  1928. <div id="header"><h1>%(title)s</h1></div>
  1929. <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>
  1930. <!-- PLEASE, LET THIS NOTE ABOUT AUTHOR AND PROJECT SOMEWHERE ON YOUR WEBSITE, OR AT LEAST IN THE COMMENT IN HTML. THANK YOU -->
  1931. </div>
  1932. <div id="map"></div>
  1933. </body>
  1934. </html>
  1935. """ % args
  1936.  
  1937. return s
  1938.  
  1939.  
  1940. # -------------------------------------------------------------------------
  1941. def generate_openlayers( self ):
  1942. """
  1943. Template for openlayers.html implementing overlay of available Spherical Mercator layers.
  1944.  
  1945. It returns filled string. Expected variables:
  1946. title, googlemapskey, yahooappid, north, south, east, west, minzoom, maxzoom, tilesize, tileformat, publishurl
  1947. """
  1948.  
  1949. args = {}
  1950. args['title'] = self.options.title
  1951. args['googlemapskey'] = self.options.googlekey
  1952. args['yahooappid'] = self.options.yahookey
  1953. args['south'], args['west'], args['north'], args['east'] = self.swne
  1954. args['minzoom'] = self.tminz
  1955. args['maxzoom'] = self.tmaxz
  1956. args['tilesize'] = self.tilesize
  1957. args['tileformat'] = self.tileext
  1958. args['publishurl'] = self.options.url
  1959. args['copyright'] = self.options.copyright
  1960. if self.options.profile == 'raster':
  1961. args['rasterzoomlevels'] = self.tmaxz+1
  1962. args['rastermaxresolution'] = 2**(self.nativezoom) * self.out_gt[1]
  1963.  
  1964. s = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  1965. <html xmlns="http://www.w3.org/1999/xhtml"
  1966. <head>
  1967. <title>%(title)s</title>
  1968. <meta http-equiv='imagetoolbar' content='no'/>
  1969. <style type="text/css"> v\:* {behavior:url(#default#VML);}
  1970. html, body { overflow: hidden; padding: 0; height: 100%%; width: 100%%; font-family: 'Lucida Grande',Geneva,Arial,Verdana,sans-serif; }
  1971. body { margin: 10px; background: #fff; }
  1972. h1 { margin: 0; padding: 6px; border:0; font-size: 20pt; }
  1973. #header { height: 43px; padding: 0; background-color: #eee; border: 1px solid #888; }
  1974. #subheader { height: 12px; text-align: right; font-size: 10px; color: #555;}
  1975. #map { height: 95%%; border: 1px solid #888; }
  1976. </style>""" % args
  1977.  
  1978. if self.options.profile == 'mercator':
  1979. s += """
  1980. <script src='http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1'></script>
  1981. <script src='http://maps.google.com/maps?file=api&amp;v=2&amp;key=%(googlemapskey)s' type='text/javascript'></script>
  1982. <script src="http://api.maps.yahoo.com/ajaxymap?v=3.0&amp;appid=%(yahooappid)s"></script>""" % args
  1983.  
  1984. s += """
  1985. <script src="http://www.openlayers.org/api/2.7/OpenLayers.js" type="text/javascript"></script>
  1986. <script type="text/javascript">
  1987. var map;
  1988. var mapBounds = new OpenLayers.Bounds( %(west)s, %(south)s, %(east)s, %(north)s);
  1989. var mapMinZoom = %(minzoom)s;
  1990. var mapMaxZoom = %(maxzoom)s;
  1991.  
  1992. // avoid pink tiles
  1993. OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
  1994. OpenLayers.Util.onImageLoadErrorColor = "transparent";
  1995.  
  1996. function init(){""" % args
  1997.  
  1998. if self.options.profile == 'mercator':
  1999. s += """
  2000. var options = {
  2001. controls: [],
  2002. projection: new OpenLayers.Projection("EPSG:900913"),
  2003. displayProjection: new OpenLayers.Projection("EPSG:4326"),
  2004. units: "m",
  2005. maxResolution: 156543.0339,
  2006. maxExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508, 20037508.34)
  2007. };
  2008. map = new OpenLayers.Map('map', options);
  2009.  
  2010. // create Google Mercator layers
  2011. var gmap = new OpenLayers.Layer.Google("Google Streets",
  2012. { sphericalMercator: true, numZoomLevels: 20} );
  2013. var gsat = new OpenLayers.Layer.Google("Google Satellite",
  2014. {type: G_SATELLITE_MAP, sphericalMercator: true, numZoomLevels: 20} );
  2015. var ghyb = new OpenLayers.Layer.Google("Google Hybrid",
  2016. {type: G_HYBRID_MAP, sphericalMercator: true, numZoomLevels: 20});
  2017. var gter = new OpenLayers.Layer.Google("Google Terrain",
  2018. {type: G_PHYSICAL_MAP, sphericalMercator: true, numZoomLevels: 20 });
  2019.  
  2020. // create Virtual Earth layers
  2021. OpenLayers.Layer.VirtualEarth.prototype.MAX_ZOOM_LEVEL=19;
  2022. OpenLayers.Layer.VirtualEarth.prototype.RESOLUTIONS=OpenLayers.Layer.Google.prototype.RESOLUTIONS
  2023. var veroad = new OpenLayers.Layer.VirtualEarth("Virtual Earth Roads",
  2024. {'type': VEMapStyle.Road, 'sphericalMercator': true, numZoomLevels: 20});
  2025. var veaer = new OpenLayers.Layer.VirtualEarth("Virtual Earth Aerial",
  2026. {'type': VEMapStyle.Aerial, 'sphericalMercator': true, numZoomLevels: 20 });
  2027. var vehyb = new OpenLayers.Layer.VirtualEarth("Virtual Earth Hybrid",
  2028. {'type': VEMapStyle.Hybrid, 'sphericalMercator': true});
  2029.  
  2030. // create Yahoo layer
  2031. var yahoo = new OpenLayers.Layer.Yahoo("Yahoo Street",
  2032. {'sphericalMercator': true});
  2033. var yahoosat = new OpenLayers.Layer.Yahoo("Yahoo Satellite",
  2034. {'type': YAHOO_MAP_SAT, 'sphericalMercator': true});
  2035. var yahoohyb = new OpenLayers.Layer.Yahoo("Yahoo Hybrid",
  2036. {'type': YAHOO_MAP_HYB, 'sphericalMercator': true});
  2037.  
  2038. // create OSM/OAM layer
  2039. var osm = new OpenLayers.Layer.TMS( "OpenStreetMap",
  2040. "http://tile.openstreetmap.org/",
  2041. { type: 'png', getURL: osm_getTileURL, displayOutsideMaxExtent: true, attribution: '<a href="http://www.openstreetmap.org/">OpenStreetMap</a>'} );
  2042. var oam = new OpenLayers.Layer.TMS( "OpenAerialMap",
  2043. "http://tile.openaerialmap.org/tiles/1.0.0/openaerialmap-900913/",
  2044. { type: 'png', getURL: osm_getTileURL } );
  2045.  
  2046. // create TMS Overlay layer
  2047. var tmsoverlay = new OpenLayers.Layer.TMS( "TMS Overlay", "",
  2048. { // url: '', serviceVersion: '.', layername: '.',
  2049. type: 'png', getURL: overlay_getTileURL, alpha: true,
  2050. isBaseLayer: false
  2051. });
  2052. if (OpenLayers.Util.alphaHack() == false) { tmsoverlay.setOpacity(0.7); }
  2053.  
  2054. map.addLayers([gmap, gsat, ghyb, gter, veroad, veaer, vehyb,
  2055. yahoo, yahoosat, yahoohyb, osm, oam,
  2056. tmsoverlay]);
  2057.  
  2058. var switcherControl = new OpenLayers.Control.LayerSwitcher();
  2059. map.addControl(switcherControl);
  2060. switcherControl.maximizeControl();
  2061.  
  2062. map.zoomToExtent( mapBounds.transform(map.displayProjection, map.projection ) );
  2063. """ % args
  2064.  
  2065. elif self.options.profile == 'geodetic':
  2066. s += """
  2067. var options = {
  2068. controls: [],
  2069. projection: new OpenLayers.Projection("EPSG:4326"),
  2070. maxResolution: 0.703125,
  2071. maxExtent: new OpenLayers.Bounds(-180, -90, 180, 90)
  2072. };
  2073. map = new OpenLayers.Map('map', options);
  2074.  
  2075. layer = new OpenLayers.Layer.WMS( "Blue Marble",
  2076. "http://labs.metacarta.com/wms-c/Basic.py?", {layers: 'satellite' } );
  2077. map.addLayer(layer);
  2078. wms = new OpenLayers.Layer.WMS( "VMap0",
  2079. "http://labs.metacarta.com/wms-c/Basic.py?", {layers: 'basic', format: 'image/png' } );
  2080. map.addLayer(wms);
  2081.  
  2082. var tmsoverlay = new OpenLayers.Layer.TMS( "TMS Overlay", "",
  2083. {
  2084. serviceVersion: '.', layername: '.', alpha: true,
  2085. type: 'png', getURL: overlay_getTileURL,
  2086. isBaseLayer: false
  2087. });
  2088. map.addLayer(tmsoverlay);
  2089. if (OpenLayers.Util.alphaHack() == false) { tmsoverlay.setOpacity(0.7); }
  2090.  
  2091. var switcherControl = new OpenLayers.Control.LayerSwitcher();
  2092. map.addControl(switcherControl);
  2093. switcherControl.maximizeControl();
  2094.  
  2095. map.zoomToExtent( mapBounds );
  2096. """
  2097.  
  2098. elif self.options.profile == 'raster':
  2099. s += """
  2100. var options = {
  2101. controls: [],
  2102. maxExtent: new OpenLayers.Bounds( %(west)s, %(south)s, %(east)s, %(north)s ),
  2103. maxResolution: %(rastermaxresolution)f,
  2104. numZoomLevels: %(rasterzoomlevels)d
  2105. };
  2106. map = new OpenLayers.Map('map', options);
  2107.  
  2108. var layer = new OpenLayers.Layer.TMS( "TMS Layer","",
  2109. { url: '', serviceVersion: '.', layername: '.', alpha: true,
  2110. type: 'png', getURL: overlay_getTileURL
  2111. });
  2112. map.addLayer(layer);
  2113. map.zoomToExtent( mapBounds );
  2114. """ % args
  2115.  
  2116.  
  2117. s += """
  2118. map.addControl(new OpenLayers.Control.PanZoomBar());
  2119. map.addControl(new OpenLayers.Control.MousePosition());
  2120. map.addControl(new OpenLayers.Control.MouseDefaults());
  2121. map.addControl(new OpenLayers.Control.KeyboardDefaults());
  2122. }
  2123. """ % args
  2124.  
  2125. if self.options.profile == 'mercator':
  2126. s += """
  2127. function osm_getTileURL(bounds) {
  2128. var res = this.map.getResolution();
  2129. var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
  2130. var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
  2131. var z = this.map.getZoom();
  2132. var limit = Math.pow(2, z);
  2133.  
  2134. if (y < 0 || y >= limit) {
  2135. return "http://www.maptiler.org/img/none.png";
  2136. } else {
  2137. x = ((x %% limit) + limit) %% limit;
  2138. return this.url + z + "/" + x + "/" + y + "." + this.type;
  2139. }
  2140. }
  2141.  
  2142. function overlay_getTileURL(bounds) {
  2143. var res = this.map.getResolution();
  2144. var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
  2145. var y = Math.round((bounds.bottom - this.tileOrigin.lat) / (res * this.tileSize.h));
  2146. var z = this.map.getZoom();
  2147. if (this.map.baseLayer.name == 'Virtual Earth Roads' || this.map.baseLayer.name == 'Virtual Earth Aerial' || this.map.baseLayer.name == 'Virtual Earth Hybrid') {
  2148. z = z + 1;
  2149. }
  2150. if (mapBounds.intersectsBounds( bounds ) && z >= mapMinZoom && z <= mapMaxZoom ) {
  2151. //console.log( this.url + z + "/" + x + "/" + y + "." + this.type);
  2152. return this.url + z + "/" + x + "/" + y + "." + this.type;
  2153. } else {
  2154. return "http://www.maptiler.org/img/none.png";
  2155. }
  2156. }
  2157. """ % args
  2158.  
  2159. elif self.options.profile == 'geodetic':
  2160. s += """
  2161. function overlay_getTileURL(bounds) {
  2162. bounds = this.adjustBounds(bounds);
  2163. var res = this.map.getResolution();
  2164. var x = Math.round((bounds.left - this.tileOrigin.lon) / (res * this.tileSize.w));
  2165. var y = Math.round((bounds.bottom - this.tileOrigin.lat) / (res * this.tileSize.h));
  2166. var z = this.map.getZoom();
  2167. var path = this.serviceVersion + "/" + this.layername + "/" + z + "/" + x + "/" + y + "." + this.type;
  2168. var url = this.url;
  2169. if (mapBounds.intersectsBounds( bounds ) && z >= mapMinZoom && z <= mapMaxZoom) {
  2170. // console.log( this.url + z + "/" + x + "/" + y + "." + this.type);
  2171. return this.url + z + "/" + x + "/" + y + "." + this.type;
  2172. } else {
  2173. return "http://www.maptiler.org/img/none.png";
  2174. }
  2175. }
  2176. """ % args
  2177.  
  2178. elif self.options.profile == 'raster':
  2179. s += """
  2180. function overlay_getTileURL(bounds) {
  2181. var res = this.map.getResolution();
  2182. var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
  2183. var y = Math.round((bounds.bottom - this.maxExtent.bottom) / (res * this.tileSize.h));
  2184. var z = this.map.getZoom();
  2185. if (x >= 0 && y >= 0) {
  2186. return this.url + z + "/" + x + "/" + y + "." + this.type;
  2187. } else {
  2188. return "http://www.maptiler.org/img/none.png";
  2189. }
  2190. }
  2191. """ % args
  2192.  
  2193. s += """
  2194. function getWindowHeight() {
  2195. if (self.innerHeight) return self.innerHeight;
  2196. if (document.documentElement && document.documentElement.clientHeight)
  2197. return document.documentElement.clientHeight;
  2198. if (document.body) return document.body.clientHeight;
  2199. return 0;
  2200. }
  2201.  
  2202. function getWindowWidth() {
  2203. if (self.innerWidth) return self.innerWidth;
  2204. if (document.documentElement && document.documentElement.clientWidth)
  2205. return document.documentElement.clientWidth;
  2206. if (document.body) return document.body.clientWidth;
  2207. return 0;
  2208. }
  2209.  
  2210. function resize() {
  2211. var map = document.getElementById("map");
  2212. var header = document.getElementById("header");
  2213. var subheader = document.getElementById("subheader");
  2214. map.style.height = (getWindowHeight()-80) + "px";
  2215. map.style.width = (getWindowWidth()-20) + "px";
  2216. header.style.width = (getWindowWidth()-20) + "px";
  2217. subheader.style.width = (getWindowWidth()-20) + "px";
  2218. if (map.updateSize) { map.updateSize(); };
  2219. }
  2220.  
  2221. onresize=function(){ resize(); };
  2222.  
  2223. </script>
  2224. </head>
  2225. <body onload="init()">
  2226. <div id="header"><h1>%(title)s</h1></div>
  2227. <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>
  2228. <!-- PLEASE, LET THIS NOTE ABOUT AUTHOR AND PROJECT SOMEWHERE ON YOUR WEBSITE, OR AT LEAST IN THE COMMENT IN HTML. THANK YOU -->
  2229. </div>
  2230. <div id="map"></div>
  2231. <script type="text/javascript" >resize()</script>
  2232. </body>
  2233. </html>""" % args
  2234.  
  2235. return s
  2236.  
  2237. # =============================================================================
  2238. # =============================================================================
  2239. # =============================================================================
  2240.  
  2241. def worker_metadata(argv):
  2242. gdal2tiles = GDAL2Tiles( argv[1:] )
  2243. gdal2tiles.open_input()
  2244. gdal2tiles.generate_metadata()
  2245.  
  2246. def worker_base_tiles(argv, cpu):
  2247. gdal2tiles = GDAL2Tiles( argv[1:] )
  2248. gdal2tiles.open_input()
  2249. gdal2tiles.generate_base_tiles(cpu)
  2250.  
  2251. def worker_overview_tiles(argv, cpu, tz):
  2252. gdal2tiles = GDAL2Tiles( argv[1:] )
  2253. gdal2tiles.open_input()
  2254. gdal2tiles.generate_overview_tiles(cpu, tz)
  2255.  
  2256. if __name__=='__main__':
  2257. argv = gdal.GeneralCmdLineProcessor( sys.argv )
  2258. if argv:
  2259. gdal2tiles = GDAL2Tiles( argv[1:] ) # handle command line options
  2260.  
  2261. p = multiprocessing.Process(target=worker_metadata, args=[argv])
  2262. p.start()
  2263. p.join()
  2264.  
  2265. pool = multiprocessing.Pool()
  2266. processed_tiles = 0
  2267. print("Generating Base Tiles:")
  2268. for cpu in range(gdal2tiles.options.processes):
  2269. pool.apply_async(worker_base_tiles, [argv, cpu])
  2270. pool.close()
  2271. while len(multiprocessing.active_children()) != 0:
  2272. try:
  2273. total = queue.get(timeout=1)
  2274. processed_tiles += 1
  2275. gdal.TermProgress_nocb(processed_tiles / float(total))
  2276. sys.stdout.flush()
  2277. except:
  2278. pass
  2279. pool.join()
  2280.  
  2281. processed_tiles = 0
  2282. print("Generating Overview Tiles:")
  2283. for tz in range(gdal2tiles.tmaxz-1, gdal2tiles.tminz-1, -1):
  2284. pool = multiprocessing.Pool()
  2285. for cpu in range(gdal2tiles.options.processes):
  2286. pool.apply_async(worker_overview_tiles, [argv, cpu, tz])
  2287. pool.close()
  2288. while len(multiprocessing.active_children()) != 0:
  2289. try:
  2290. total = queue.get(timeout=1)
  2291. processed_tiles += 1
  2292. gdal.TermProgress_nocb(processed_tiles / float(total))
  2293. sys.stdout.flush()
  2294. except:
  2295. pass
  2296. pool.join()
  2297.  
  2298.  
  2299. #############
  2300. # vim:noet
  2301. #############
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement