/maptiler/gdal2tiles.py

http://maptiler.googlecode.com/ · Python · 1721 lines · 1354 code · 143 blank · 224 comment · 148 complexity · dad90d89734825ffc1fb817f32aab633 MD5 · raw file

  1. #!/usr/bin/env python
  2. #******************************************************************************
  3. # $Id: gdal2tiles.py 15748 2008-11-17 16:30:54Z klokan $
  4. #
  5. # Project: Google Summer of Code 2007, 2008 (http://code.google.com/soc/)
  6. # Support: BRGM (http://www.brgm.fr)
  7. # Purpose: Convert a raster into TMS (Tile Map Service) tiles in a directory.
  8. # - generate Google Earth metadata (KML SuperOverlay)
  9. # - generate simple HTML viewer based on Google Maps and OpenLayers
  10. # - support of global tiles (Spherical Mercator) for compatibility
  11. # with interactive web maps a la Google Maps
  12. # Author: Klokan Petr Pridal, klokan at klokan dot cz
  13. # Web: http://www.klokan.cz/projects/gdal2tiles/
  14. # GUI: http://www.maptiler.org/
  15. #
  16. ###############################################################################
  17. # Copyright (c) 2008, Klokan Petr Pridal
  18. #
  19. # Permission is hereby granted, free of charge, to any person obtaining a
  20. # copy of this software and associated documentation files (the "Software"),
  21. # to deal in the Software without restriction, including without limitation
  22. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  23. # and/or sell copies of the Software, and to permit persons to whom the
  24. # Software is furnished to do so, subject to the following conditions:
  25. #
  26. # The above copyright notice and this permission notice shall be included
  27. # in all copies or substantial portions of the Software.
  28. #
  29. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  30. # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  31. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  32. # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  33. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  34. # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  35. # DEALINGS IN THE SOFTWARE.
  36. #******************************************************************************
  37. from osgeo import gdal
  38. from osgeo import osr
  39. import sys
  40. import os
  41. import math
  42. try:
  43. from PIL import Image
  44. import numpy
  45. import osgeo.gdal_array as gdalarray
  46. except:
  47. # 'antialias' resampling is not available
  48. pass
  49. __version__ = "$Id: gdal2tiles.py 15748 2008-11-17 16:30:54Z klokan $"
  50. resampling_list = ('average','near','bilinear','cubic','cubicspline','lanczos','antialias')
  51. tile_formats_list = ('png', 'jpeg', 'hybrid')
  52. profile_list = ('mercator','geodetic','raster','gearth') #,'zoomify')
  53. webviewer_list = ('all','google','openlayers','none')
  54. format_extension = {
  55. "PNG" : "png",
  56. "JPEG" : "jpg"
  57. }
  58. format_mime = {
  59. "PNG" : "image/png",
  60. "JPEG" : "image/jpeg"
  61. }
  62. # =============================================================================
  63. # =============================================================================
  64. # =============================================================================
  65. __doc__globalmaptiles = """
  66. globalmaptiles.py
  67. Global Map Tiles as defined in Tile Map Service (TMS) Profiles
  68. ==============================================================
  69. Functions necessary for generation of global tiles used on the web.
  70. It contains classes implementing coordinate conversions for:
  71. - GlobalMercator (based on EPSG:900913 = EPSG:3785)
  72. for Google Maps, Yahoo Maps, Microsoft Maps compatible tiles
  73. - GlobalGeodetic (based on EPSG:4326)
  74. for OpenLayers Base Map and Google Earth compatible tiles
  75. More info at:
  76. http://wiki.osgeo.org/wiki/Tile_Map_Service_Specification
  77. http://wiki.osgeo.org/wiki/WMS_Tiling_Client_Recommendation
  78. http://msdn.microsoft.com/en-us/library/bb259689.aspx
  79. http://code.google.com/apis/maps/documentation/overlays.html#Google_Maps_Coordinates
  80. Created by Klokan Petr Pridal on 2008-07-03.
  81. Google Summer of Code 2008, project GDAL2Tiles for OSGEO.
  82. In case you use this class in your product, translate it to another language
  83. or find it usefull for your project please let me know.
  84. My email: klokan at klokan dot cz.
  85. I would like to know where it was used.
  86. Class is available under the open-source GDAL license (www.gdal.org).
  87. """
  88. import math
  89. MAXZOOMLEVEL = 32
  90. class GlobalMercator(object):
  91. """
  92. TMS Global Mercator Profile
  93. ---------------------------
  94. Functions necessary for generation of tiles in Spherical Mercator projection,
  95. EPSG:900913 (EPSG:gOOglE, Google Maps Global Mercator), EPSG:3785, OSGEO:41001.
  96. Such tiles are compatible with Google Maps, Microsoft Virtual Earth, Yahoo Maps,
  97. UK Ordnance Survey OpenSpace API, ...
  98. and you can overlay them on top of base maps of those web mapping applications.
  99. Pixel and tile coordinates are in TMS notation (origin [0,0] in bottom-left).
  100. What coordinate conversions do we need for TMS Global Mercator tiles::
  101. LatLon <-> Meters <-> Pixels <-> Tile
  102. WGS84 coordinates Spherical Mercator Pixels in pyramid Tiles in pyramid
  103. lat/lon XY in metres XY pixels Z zoom XYZ from TMS
  104. EPSG:4326 EPSG:900913
  105. .----. --------- -- TMS
  106. / \ <-> | | <-> /----/ <-> Google
  107. \ / | | /--------/ QuadTree
  108. ----- --------- /------------/
  109. KML, public WebMapService Web Clients TileMapService
  110. What is the coordinate extent of Earth in EPSG:900913?
  111. [-20037508.342789244, -20037508.342789244, 20037508.342789244, 20037508.342789244]
  112. Constant 20037508.342789244 comes from the circumference of the Earth in meters,
  113. which is 40 thousand kilometers, the coordinate origin is in the middle of extent.
  114. In fact you can calculate the constant as: 2 * math.pi * 6378137 / 2.0
  115. $ echo 180 85 | gdaltransform -s_srs EPSG:4326 -t_srs EPSG:900913
  116. Polar areas with abs(latitude) bigger then 85.05112878 are clipped off.
  117. What are zoom level constants (pixels/meter) for pyramid with EPSG:900913?
  118. whole region is on top of pyramid (zoom=0) covered by 256x256 pixels tile,
  119. every lower zoom level resolution is always divided by two
  120. initialResolution = 20037508.342789244 * 2 / 256 = 156543.03392804062
  121. What is the difference between TMS and Google Maps/QuadTree tile name convention?
  122. The tile raster itself is the same (equal extent, projection, pixel size),
  123. there is just different identification of the same raster tile.
  124. Tiles in TMS are counted from [0,0] in the bottom-left corner, id is XYZ.
  125. Google placed the origin [0,0] to the top-left corner, reference is XYZ.
  126. Microsoft is referencing tiles by a QuadTree name, defined on the website:
  127. http://msdn2.microsoft.com/en-us/library/bb259689.aspx
  128. The lat/lon coordinates are using WGS84 datum, yeh?
  129. Yes, all lat/lon we are mentioning should use WGS84 Geodetic Datum.
  130. Well, the web clients like Google Maps are projecting those coordinates by
  131. Spherical Mercator, so in fact lat/lon coordinates on sphere are treated as if
  132. the were on the WGS84 ellipsoid.
  133. From MSDN documentation:
  134. To simplify the calculations, we use the spherical form of projection, not
  135. the ellipsoidal form. Since the projection is used only for map display,
  136. and not for displaying numeric coordinates, we don't need the extra precision
  137. of an ellipsoidal projection. The spherical projection causes approximately
  138. 0.33 percent scale distortion in the Y direction, which is not visually noticable.
  139. How do I create a raster in EPSG:900913 and convert coordinates with PROJ.4?
  140. You can use standard GIS tools like gdalwarp, cs2cs or gdaltransform.
  141. All of the tools supports -t_srs 'epsg:900913'.
  142. For other GIS programs check the exact definition of the projection:
  143. More info at http://spatialreference.org/ref/user/google-projection/
  144. The same projection is degined as EPSG:3785. WKT definition is in the official
  145. EPSG database.
  146. Proj4 Text:
  147. +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0
  148. +k=1.0 +units=m +nadgrids=@null +no_defs
  149. Human readable WKT format of EPGS:900913:
  150. PROJCS["Google Maps Global Mercator",
  151. GEOGCS["WGS 84",
  152. DATUM["WGS_1984",
  153. SPHEROID["WGS 84",6378137,298.2572235630016,
  154. AUTHORITY["EPSG","7030"]],
  155. AUTHORITY["EPSG","6326"]],
  156. PRIMEM["Greenwich",0],
  157. UNIT["degree",0.0174532925199433],
  158. AUTHORITY["EPSG","4326"]],
  159. PROJECTION["Mercator_1SP"],
  160. PARAMETER["central_meridian",0],
  161. PARAMETER["scale_factor",1],
  162. PARAMETER["false_easting",0],
  163. PARAMETER["false_northing",0],
  164. UNIT["metre",1,
  165. AUTHORITY["EPSG","9001"]]]
  166. """
  167. def __init__(self, tileSize=256):
  168. "Initialize the TMS Global Mercator pyramid"
  169. self.tileSize = tileSize
  170. self.initialResolution = 2 * math.pi * 6378137 / self.tileSize
  171. # 156543.03392804062 for tileSize 256 pixels
  172. self.originShift = 2 * math.pi * 6378137 / 2.0
  173. # 20037508.342789244
  174. def LatLonToMeters(self, lat, lon ):
  175. "Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:900913"
  176. mx = lon * self.originShift / 180.0
  177. my = math.log( math.tan((90 + lat) * math.pi / 360.0 )) / (math.pi / 180.0)
  178. my = my * self.originShift / 180.0
  179. return mx, my
  180. def MetersToLatLon(self, mx, my ):
  181. "Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 Datum"
  182. lon = (mx / self.originShift) * 180.0
  183. lat = (my / self.originShift) * 180.0
  184. lat = 180 / math.pi * (2 * math.atan( math.exp( lat * math.pi / 180.0)) - math.pi / 2.0)
  185. return lat, lon
  186. def PixelsToMeters(self, px, py, zoom):
  187. "Converts pixel coordinates in given zoom level of pyramid to EPSG:900913"
  188. res = self.Resolution( zoom )
  189. mx = px * res - self.originShift
  190. my = py * res - self.originShift
  191. return mx, my
  192. def MetersToPixels(self, mx, my, zoom):
  193. "Converts EPSG:900913 to pyramid pixel coordinates in given zoom level"
  194. res = self.Resolution( zoom )
  195. px = (mx + self.originShift) / res
  196. py = (my + self.originShift) / res
  197. return px, py
  198. def PixelsToTile(self, px, py):
  199. "Returns a tile covering region in given pixel coordinates"
  200. tx = int( math.ceil( px / float(self.tileSize) ) - 1 )
  201. ty = int( math.ceil( py / float(self.tileSize) ) - 1 )
  202. return tx, ty
  203. def PixelsToRaster(self, px, py, zoom):
  204. "Move the origin of pixel coordinates to top-left corner"
  205. mapSize = self.tileSize << zoom
  206. return px, mapSize - py
  207. def MetersToTile(self, mx, my, zoom):
  208. "Returns tile for given mercator coordinates"
  209. px, py = self.MetersToPixels( mx, my, zoom)
  210. return self.PixelsToTile( px, py)
  211. def TileBounds(self, tx, ty, zoom):
  212. "Returns bounds of the given tile in EPSG:900913 coordinates"
  213. minx, miny = self.PixelsToMeters( tx*self.tileSize, ty*self.tileSize, zoom )
  214. maxx, maxy = self.PixelsToMeters( (tx+1)*self.tileSize, (ty+1)*self.tileSize, zoom )
  215. return ( minx, miny, maxx, maxy )
  216. def TileLatLonBounds(self, tx, ty, zoom ):
  217. "Returns bounds of the given tile in latutude/longitude using WGS84 datum"
  218. bounds = self.TileBounds( tx, ty, zoom)
  219. minLat, minLon = self.MetersToLatLon(bounds[0], bounds[1])
  220. maxLat, maxLon = self.MetersToLatLon(bounds[2], bounds[3])
  221. return ( minLat, minLon, maxLat, maxLon )
  222. def Resolution(self, zoom ):
  223. "Resolution (meters/pixel) for given zoom level (measured at Equator)"
  224. # return (2 * math.pi * 6378137) / (self.tileSize * 2**zoom)
  225. return self.initialResolution / (2**zoom)
  226. def ZoomForPixelSize(self, pixelSize ):
  227. "Maximal scaledown zoom of the pyramid closest to the pixelSize."
  228. for i in range(MAXZOOMLEVEL):
  229. if pixelSize > self.Resolution(i):
  230. if i!=0:
  231. return i-1
  232. else:
  233. return 0 # We don't want to scale up
  234. def GoogleTile(self, tx, ty, zoom):
  235. "Converts TMS tile coordinates to Google Tile coordinates"
  236. # coordinate origin is moved from bottom-left to top-left corner of the extent
  237. return tx, (2**zoom - 1) - ty
  238. def QuadTree(self, tx, ty, zoom ):
  239. "Converts TMS tile coordinates to Microsoft QuadTree"
  240. quadKey = ""
  241. ty = (2**zoom - 1) - ty
  242. for i in range(zoom, 0, -1):
  243. digit = 0
  244. mask = 1 << (i-1)
  245. if (tx & mask) != 0:
  246. digit += 1
  247. if (ty & mask) != 0:
  248. digit += 2
  249. quadKey += str(digit)
  250. return quadKey
  251. #---------------------
  252. class GlobalGeodetic(object):
  253. """
  254. TMS Global Geodetic Profile
  255. ---------------------------
  256. Functions necessary for generation of global tiles in Plate Carre projection,
  257. EPSG:4326, "unprojected profile".
  258. Such tiles are compatible with Google Earth (as any other EPSG:4326 rasters)
  259. and you can overlay the tiles on top of OpenLayers base map.
  260. Pixel and tile coordinates are in TMS notation (origin [0,0] in bottom-left).
  261. What coordinate conversions do we need for TMS Global Geodetic tiles?
  262. Global Geodetic tiles are using geodetic coordinates (latitude,longitude)
  263. directly as planar coordinates XY (it is also called Unprojected or Plate
  264. Carre). We need only scaling to pixel pyramid and cutting to tiles.
  265. Pyramid has on top level two tiles, so it is not square but rectangle.
  266. Area [-180,-90,180,90] is scaled to 512x256 pixels.
  267. TMS has coordinate origin (for pixels and tiles) in bottom-left corner.
  268. Rasters are in EPSG:4326 and therefore are compatible with Google Earth.
  269. LatLon <-> Pixels <-> Tiles
  270. WGS84 coordinates Pixels in pyramid Tiles in pyramid
  271. lat/lon XY pixels Z zoom XYZ from TMS
  272. EPSG:4326
  273. .----. ----
  274. / \ <-> /--------/ <-> TMS
  275. \ / /--------------/
  276. ----- /--------------------/
  277. WMS, KML Web Clients, Google Earth TileMapService
  278. """
  279. def __init__(self, tileSize = 256):
  280. self.tileSize = tileSize
  281. def LatLonToPixels(self, lat, lon, zoom):
  282. "Converts lat/lon to pixel coordinates in given zoom of the EPSG:4326 pyramid"
  283. res = 180.0 / self.tileSize / 2**zoom
  284. px = (180 + lat) / res
  285. py = (90 + lon) / res
  286. return px, py
  287. def PixelsToTile(self, px, py):
  288. "Returns coordinates of the tile covering region in pixel coordinates"
  289. tx = int( math.ceil( px / float(self.tileSize) ) - 1 )
  290. ty = int( math.ceil( py / float(self.tileSize) ) - 1 )
  291. return tx, ty
  292. def LatLonToTile(self, lat, lon, zoom):
  293. "Returns the tile for zoom which covers given lat/lon coordinates"
  294. px, py = self.LatLonToPixels( lat, lon, zoom)
  295. return self.PixelsToTile(px,py)
  296. def Resolution(self, zoom ):
  297. "Resolution (arc/pixel) for given zoom level (measured at Equator)"
  298. return 180.0 / self.tileSize / 2**zoom
  299. #return 180 / float( 1 << (8+zoom) )
  300. def ZoomForPixelSize(self, pixelSize ):
  301. "Maximal scaledown zoom of the pyramid closest to the pixelSize."
  302. for i in range(MAXZOOMLEVEL):
  303. if pixelSize > self.Resolution(i):
  304. if i!=0:
  305. return i-1
  306. else:
  307. return 0 # We don't want to scale up
  308. def TileBounds(self, tx, ty, zoom):
  309. "Returns bounds of the given tile"
  310. res = 180.0 / self.tileSize / 2**zoom
  311. return (
  312. tx*self.tileSize*res - 180,
  313. ty*self.tileSize*res - 90,
  314. (tx+1)*self.tileSize*res - 180,
  315. (ty+1)*self.tileSize*res - 90
  316. )
  317. def TileLatLonBounds(self, tx, ty, zoom):
  318. "Returns bounds of the given tile in the SWNE form"
  319. b = self.TileBounds(tx, ty, zoom)
  320. return (b[1],b[0],b[3],b[2])
  321. #---------------------
  322. # TODO: Finish Zoomify implemtentation!!!
  323. class Zoomify(object):
  324. """
  325. Tiles compatible with the Zoomify viewer
  326. ----------------------------------------
  327. """
  328. def __init__(self, width, height, tilesize = 256, tileformat='jpg'):
  329. """Initialization of the Zoomify tile tree"""
  330. self.tilesize = tilesize
  331. self.tileformat = tileformat
  332. imagesize = (width, height)
  333. tiles = ( math.ceil( width / tilesize ), math.ceil( height / tilesize ) )
  334. # Size (in tiles) for each tier of pyramid.
  335. self.tierSizeInTiles = []
  336. self.tierSizeInTiles.push( tiles )
  337. # Image size in pixels for each pyramid tierself
  338. self.tierImageSize = []
  339. self.tierImageSize.append( imagesize );
  340. while (imagesize[0] > tilesize or imageSize[1] > tilesize ):
  341. imagesize = (math.floor( imagesize[0] / 2 ), math.floor( imagesize[1] / 2) )
  342. tiles = ( math.ceil( imagesize[0] / tilesize ), math.ceil( imagesize[1] / tilesize ) )
  343. self.tierSizeInTiles.append( tiles )
  344. self.tierImageSize.append( imagesize )
  345. self.tierSizeInTiles.reverse()
  346. self.tierImageSize.reverse()
  347. # Depth of the Zoomify pyramid, number of tiers (zoom levels)
  348. self.numberOfTiers = len(self.tierSizeInTiles)
  349. # Number of tiles up to the given tier of pyramid.
  350. self.tileCountUpToTier = []
  351. self.tileCountUpToTier[0] = 0
  352. for i in range(1, self.numberOfTiers+1):
  353. self.tileCountUpToTier.append(
  354. self.tierSizeInTiles[i-1][0] * self.tierSizeInTiles[i-1][1] + self.tileCountUpToTier[i-1]
  355. )
  356. def tilefilename(self, x, y, z):
  357. """Returns filename for tile with given coordinates"""
  358. tileIndex = x + y * self.tierSizeInTiles[z][0] + self.tileCountUpToTier[z]
  359. return os.path.join("TileGroup%.0f" % math.floor( tileIndex / 256 ),
  360. "%s-%s-%s.%s" % ( z, x, y, self.tileformat))
  361. # =============================================================================
  362. # =============================================================================
  363. # =============================================================================
  364. class GDAL2Tiles(object):
  365. # -------------------------------------------------------------------------
  366. def process(self):
  367. """The main processing function, runs all the main steps of processing"""
  368. # Opening and preprocessing of the input file
  369. self.open_input()
  370. # Generation of main metadata files and HTML viewers
  371. self.generate_metadata()
  372. # Generation of the lowest tiles
  373. self.generate_base_tiles()
  374. # Generation of the overview tiles (higher in the pyramid)
  375. self.generate_overview_tiles()
  376. # -------------------------------------------------------------------------
  377. def error(self, msg, details = "" ):
  378. """Print an error message and stop the processing"""
  379. if details:
  380. self.parser.error(msg + "\n\n" + details)
  381. else:
  382. self.parser.error(msg)
  383. # -------------------------------------------------------------------------
  384. def progressbar(self, complete = 0.0):
  385. """Print progressbar for float value 0..1"""
  386. gdal.TermProgress_nocb(complete)
  387. # -------------------------------------------------------------------------
  388. def stop(self):
  389. """Stop the rendering immediately"""
  390. self.stopped = True
  391. # -------------------------------------------------------------------------
  392. def __init__(self, arguments ):
  393. """Constructor function - initialization"""
  394. self.stopped = False
  395. self.input = None
  396. self.output = None
  397. # Tile format
  398. self.tilesize = 256
  399. # Should we read bigger window of the input raster and scale it down?
  400. # Note: Modified leter by open_input()
  401. # Not for 'near' resampling
  402. # Not for Wavelet based drivers (JPEG2000, ECW, MrSID)
  403. # Not for 'raster' profile
  404. self.scaledquery = True
  405. # How big should be query window be for scaling down
  406. # Later on reset according the chosen resampling algorightm
  407. self.querysize = 4 * self.tilesize
  408. # Should we use Read on the input file for generating overview tiles?
  409. # Note: Modified later by open_input()
  410. # Otherwise the overview tiles are generated from existing underlying tiles
  411. self.overviewquery = False
  412. # RUN THE ARGUMENT PARSER:
  413. self.optparse_init()
  414. self.options, self.args = self.parser.parse_args(args=arguments)
  415. if not self.args:
  416. self.error("No input file specified")
  417. # POSTPROCESSING OF PARSED ARGUMENTS:
  418. # Workaround for old versions of GDAL
  419. try:
  420. if (self.options.verbose and self.options.resampling == 'near') or gdal.TermProgress_nocb:
  421. pass
  422. except:
  423. self.error("This version of GDAL is not supported. Please upgrade to 1.6+.")
  424. #,"You can try run crippled version of gdal2tiles with parameters: -v -r 'near'")
  425. # Is output directory the last argument?
  426. # Test output directory, if it doesn't exist
  427. if os.path.isdir(self.args[-1]) or ( len(self.args) > 1 and not os.path.exists(self.args[-1])):
  428. self.output = self.args[-1]
  429. self.args = self.args[:-1]
  430. # More files on the input not directly supported yet
  431. if (len(self.args) > 1):
  432. self.error("Processing of several input files is not supported.",
  433. """Please first use a tool like gdal_vrtmerge.py or gdal_merge.py on the files:
  434. gdal_vrtmerge.py -o merged.vrt %s""" % " ".join(self.args))
  435. # TODO: Call functions from gdal_vrtmerge.py directly
  436. self.input = self.args[0]
  437. # Default values for not given options
  438. if not self.output:
  439. # Directory with input filename without extension in actual directory
  440. self.output = os.path.splitext(os.path.basename( self.input ))[0]
  441. if not self.options.title:
  442. self.options.title = os.path.basename( self.input )
  443. if self.options.url and not self.options.url.endswith('/'):
  444. self.options.url += '/'
  445. if self.options.url:
  446. self.options.url += os.path.basename( self.output ) + '/'
  447. # Supported options
  448. if self.options.resampling == 'average':
  449. try:
  450. if gdal.RegenerateOverview:
  451. pass
  452. except:
  453. self.error("'average' resampling algorithm is not available.", "Please use -r 'near' argument or upgrade to newer version of GDAL.")
  454. elif self.options.resampling == 'antialias':
  455. try:
  456. if numpy:
  457. pass
  458. except:
  459. self.error("'antialias' resampling algorithm is not available.", "Install PIL (Python Imaging Library) and numpy.")
  460. elif self.options.resampling == 'near':
  461. self.querysize = self.tilesize
  462. elif self.options.resampling == 'bilinear':
  463. self.querysize = self.tilesize * 2
  464. # Tile format.
  465. if self.options.tile_format is None:
  466. if self.options.profile == 'gearth':
  467. self.options.tile_format = 'hybrid'
  468. else:
  469. self.options.tile_format = 'png'
  470. # Webviewer default depends on tile format.
  471. if self.options.webviewer is None:
  472. if self.options.tile_format == 'hybrid':
  473. self.options.webviewer = 'none'
  474. else:
  475. self.options.webviewer = 'all'
  476. # We don't support webviewers with hybrid trees yet.
  477. elif self.options.tile_format == 'hybrid' and self.options.webviewer != 'none':
  478. print ("WARNING: hybrid tile format is incompatible with webviewers you selected (%s), " +
  479. "so they will not be created.") % self.options.webviewer
  480. self.options.webviewer = "none"
  481. # User specified zoom levels
  482. self.tminz = None
  483. self.tmaxz = None
  484. if self.options.zoom:
  485. minmax = self.options.zoom.split('-',1)
  486. minmax.extend([''])
  487. min, max = minmax[:2]
  488. self.tminz = int(min)
  489. if max:
  490. self.tmaxz = int(max)
  491. else:
  492. self.tmaxz = int(min)
  493. # KML generation
  494. self.kml = self.options.kml
  495. if self.options.kml_depth:
  496. self.kml_depth = int(self.options.kml_depth)
  497. assert self.kml_depth > 0
  498. else:
  499. if self.options.profile == 'gearth':
  500. self.kml_depth = 3
  501. else:
  502. self.kml_depth = 1
  503. # Output the results
  504. if self.options.verbose:
  505. print "Options:", self.options
  506. print "Input:", self.input
  507. print "Output:", self.output
  508. print "Cache: %s MB" % (gdal.GetCacheMax() / 1024 / 1024)
  509. print
  510. # -------------------------------------------------------------------------
  511. def optparse_init(self):
  512. """Prepare the option parser for input (argv)"""
  513. from optparse import OptionParser, OptionGroup
  514. usage = "Usage: %prog [options] input_file(s) [output]"
  515. p = OptionParser(usage, version="%prog "+ __version__)
  516. p.add_option("-p", "--profile", dest='profile', type='choice', choices=profile_list,
  517. help="Tile cutting profile (%s) - default 'mercator' (Google Maps compatible)" % ",".join(profile_list))
  518. p.add_option("-r", "--resampling", dest="resampling", type='choice', choices=resampling_list,
  519. help="Resampling method (%s) - default 'average'" % ",".join(resampling_list))
  520. p.add_option("-f", "--tile-format", dest="tile_format", type='choice', choices=tile_formats_list,
  521. help="Image format of generated tiles (%s) - default 'png'" % ",".join(tile_formats_list))
  522. p.add_option('-s', '--s_srs', dest="s_srs", metavar="SRS",
  523. help="The spatial reference system used for the source input data")
  524. p.add_option('-z', '--zoom', dest="zoom",
  525. help="Zoom levels to render (format:'2-5' or '10').")
  526. p.add_option('-e', '--resume', dest="resume", action="store_true",
  527. help="Resume mode. Generate only missing files.")
  528. p.add_option('-a', '--srcnodata', dest="srcnodata", metavar="NODATA",
  529. help="NODATA transparency value to assign to the input data")
  530. p.add_option("-v", "--verbose",
  531. action="store_true", dest="verbose",
  532. help="Print status messages to stdout")
  533. # KML options
  534. g = OptionGroup(p, "KML (Google Earth) options", "Options for generated Google Earth SuperOverlay metadata")
  535. g.add_option("-k", "--force-kml", dest='kml', action="store_true",
  536. help="Generate KML for Google Earth - default for 'geodetic' profile and 'raster' in EPSG:4326. For a dataset with different projection use with caution!")
  537. g.add_option("-n", "--no-kml", dest='kml', action="store_false",
  538. help="Avoid automatic generation of KML files for EPSG:4326")
  539. g.add_option("-u", "--url", dest='url',
  540. help="URL address where the generated tiles are going to be published")
  541. g.add_option('-d', '--kml-depth', dest="kml_depth",
  542. help="How many levels to store before linking, default 1.")
  543. p.add_option_group(g)
  544. # HTML options
  545. g = OptionGroup(p, "Web viewer options", "Options for generated HTML viewers a la Google Maps")
  546. g.add_option("-w", "--webviewer", dest='webviewer', type='choice', choices=webviewer_list,
  547. help="Web viewer to generate (%s) - default 'all'" % ",".join(webviewer_list))
  548. g.add_option("-t", "--title", dest='title',
  549. help="Title of the map")
  550. g.add_option("-c", "--copyright", dest='copyright',
  551. help="Copyright for the map")
  552. g.add_option("-g", "--googlekey", dest='googlekey',
  553. help="Google Maps API key from http://code.google.com/apis/maps/signup.html")
  554. g.add_option("-y", "--yahookey", dest='yahookey',
  555. help="Yahoo Application ID from http://developer.yahoo.com/wsregapp/")
  556. p.add_option_group(g)
  557. # TODO: MapFile + TileIndexes per zoom level for efficient MapServer WMS
  558. #g = OptionGroup(p, "WMS MapServer metadata", "Options for generated mapfile and tileindexes for MapServer")
  559. #g.add_option("-i", "--tileindex", dest='wms', action="store_true"
  560. # help="Generate tileindex and mapfile for MapServer (WMS)")
  561. # p.add_option_group(g)
  562. p.set_defaults(verbose=False, profile="mercator", kml=False, url='',
  563. copyright='', resampling='average', resume=False,
  564. googlekey='INSERT_YOUR_KEY_HERE', yahookey='INSERT_YOUR_YAHOO_APP_ID_HERE')
  565. self.parser = p
  566. # -------------------------------------------------------------------------
  567. def open_input(self):
  568. """Initialization of the input raster, reprojection if necessary"""
  569. gdal.SetConfigOption("GDAL_PAM_ENABLED", "NO")
  570. gdal.AllRegister()
  571. # Open the input file
  572. if self.input:
  573. self.in_ds = gdal.Open(self.input, gdal.GA_ReadOnly)
  574. else:
  575. raise Exception("No input file was specified")
  576. if self.options.verbose:
  577. print "Input file:", "( %sP x %sL - %s bands)" % (self.in_ds.RasterXSize, self.in_ds.RasterYSize, self.in_ds.RasterCount)
  578. if not self.in_ds:
  579. # Note: GDAL prints the ERROR message too
  580. self.error("It is not possible to open the input file '%s'." % self.input )
  581. # Read metadata from the input file
  582. if self.in_ds.RasterCount == 0:
  583. self.error( "Input file '%s' has no raster band" % self.input )
  584. if self.in_ds.GetRasterBand(1).GetRasterColorTable():
  585. # TODO: Process directly paletted dataset by generating VRT in memory
  586. self.error( "Please convert this file to RGB/RGBA and run gdal2tiles on the result.",
  587. """From paletted file you can create RGBA file (temp.vrt) by:
  588. gdal_translate -of vrt -expand rgba %s temp.vrt
  589. then run:
  590. gdal2tiles temp.vrt""" % self.input )
  591. # Get NODATA value
  592. # User supplied values overwrite everything else.
  593. if self.options.srcnodata:
  594. nds = map( float, self.options.srcnodata.split(','))
  595. if len(nds) < self.in_ds.RasterCount:
  596. self.in_nodata = (nds * self.in_ds.RasterCount)[:self.in_ds.RasterCount]
  597. else:
  598. self.in_nodata = nds
  599. else:
  600. # If the source dataset has NODATA, use it.
  601. self.in_nodata = []
  602. for i in range(1, self.in_ds.RasterCount+1):
  603. if self.in_ds.GetRasterBand(i).GetNoDataValue() != None:
  604. self.in_nodata.append( self.in_ds.GetRasterBand(i).GetNoDataValue() )
  605. # If it does not and we are producing JPEG, make NODATA white.
  606. if len(self.in_nodata) == 0 and self.options.tile_format == "jpeg":
  607. if self.in_ds.RasterCount in (1,3):
  608. self.in_nodata = [255] * self.in_ds.RasterCount
  609. elif self.in_ds.RasterCount == 4:
  610. self.in_nodata = [255,255,255,0]
  611. if self.options.verbose:
  612. print "NODATA: %s" % self.in_nodata
  613. #
  614. # Here we should have RGBA input dataset opened in self.in_ds
  615. #
  616. if self.options.verbose:
  617. print "Preprocessed file:", "( %sP x %sL - %s bands)" % (self.in_ds.RasterXSize, self.in_ds.RasterYSize, self.in_ds.RasterCount)
  618. # Spatial Reference System of the input raster
  619. self.in_srs = None
  620. if self.options.s_srs:
  621. self.in_srs = osr.SpatialReference()
  622. self.in_srs.SetFromUserInput(self.options.s_srs)
  623. self.in_srs_wkt = self.in_srs.ExportToWkt()
  624. else:
  625. self.in_srs_wkt = self.in_ds.GetProjection()
  626. if not self.in_srs_wkt and self.in_ds.GetGCPCount() != 0:
  627. self.in_srs_wkt = self.in_ds.GetGCPProjection()
  628. if self.in_srs_wkt:
  629. self.in_srs = osr.SpatialReference()
  630. self.in_srs.ImportFromWkt(self.in_srs_wkt)
  631. #elif self.options.profile != 'raster':
  632. # 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.")
  633. # Spatial Reference System of tiles
  634. self.out_srs = osr.SpatialReference()
  635. if self.options.profile == 'mercator':
  636. self.out_srs.ImportFromEPSG(900913)
  637. elif self.options.profile in ('geodetic', 'gearth'):
  638. self.out_srs.ImportFromEPSG(4326)
  639. else:
  640. self.out_srs = self.in_srs
  641. # Are the reference systems the same? Reproject if necessary.
  642. self.out_ds = None
  643. if self.options.profile in ('mercator', 'geodetic', 'gearth'):
  644. if (self.in_ds.GetGeoTransform() == (0.0, 1.0, 0.0, 0.0, 0.0, 1.0)) and (self.in_ds.GetGCPCount() == 0):
  645. self.error("There is no georeference - neither affine transformation (worldfile) nor GCPs. You can generate only 'raster' profile tiles.",
  646. "Either gdal2tiles with parameter -p 'raster' or use another GIS software for georeference e.g. gdal_transform -gcp / -a_ullr / -a_srs")
  647. if self.in_srs:
  648. if (self.in_srs.ExportToProj4() != self.out_srs.ExportToProj4()) or (self.in_ds.GetGCPCount() != 0):
  649. # Generation of VRT dataset in tile projection, default 'nearest neighbour' warping
  650. self.out_ds = gdal.AutoCreateWarpedVRT( self.in_ds, self.in_srs_wkt, self.out_srs.ExportToWkt() )
  651. # TODO: HIGH PRIORITY: Correction of AutoCreateWarpedVRT according the max zoomlevel for correct direct warping!!!
  652. if self.options.verbose:
  653. print "Warping of the raster by AutoCreateWarpedVRT (result saved into 'tiles.vrt')"
  654. self.out_ds.GetDriver().CreateCopy("tiles.vrt", self.out_ds)
  655. # Note: self.in_srs and self.in_srs_wkt contain still the non-warped reference system!!!
  656. # Correction of AutoCreateWarpedVRT for NODATA values
  657. if self.in_nodata != []:
  658. import tempfile
  659. tempfilename = tempfile.mktemp('-gdal2tiles.vrt')
  660. self.out_ds.GetDriver().CreateCopy(tempfilename, self.out_ds)
  661. # open as a text file
  662. s = open(tempfilename).read()
  663. # Add the warping options
  664. s = s.replace("""<GDALWarpOptions>""","""<GDALWarpOptions>
  665. <Option name="INIT_DEST">NO_DATA</Option>
  666. <Option name="UNIFIED_SRC_NODATA">YES</Option>""")
  667. # replace BandMapping tag for NODATA bands....
  668. for i in range(len(self.in_nodata)):
  669. s = s.replace("""<BandMapping src="%i" dst="%i"/>""" % ((i+1),(i+1)),"""<BandMapping src="%i" dst="%i">
  670. <SrcNoDataReal>%i</SrcNoDataReal>
  671. <SrcNoDataImag>0</SrcNoDataImag>
  672. <DstNoDataReal>%i</DstNoDataReal>
  673. <DstNoDataImag>0</DstNoDataImag>
  674. </BandMapping>""" % ((i+1), (i+1), self.in_nodata[i], self.in_nodata[i])) # Or rewrite to white by: , 255 ))
  675. # save the corrected VRT
  676. open(tempfilename,"w").write(s)
  677. # open by GDAL as self.out_ds
  678. self.out_ds = gdal.Open(tempfilename) #, gdal.GA_ReadOnly)
  679. # delete the temporary file
  680. os.unlink(tempfilename)
  681. # set NODATA_VALUE metadata
  682. self.out_ds.SetMetadataItem('NODATA_VALUES','%s' % " ".join(str(int(f)) for f in self.in_nodata))
  683. # '%i %i %i' % (self.in_nodata[0],self.in_nodata[1],self.in_nodata[2]))
  684. if self.options.verbose:
  685. print "Modified warping result saved into 'tiles1.vrt'"
  686. open("tiles1.vrt","w").write(s)
  687. # -----------------------------------
  688. # Correction of AutoCreateWarpedVRT for Mono (1 band) and RGB (3 bands) files without NODATA:
  689. # equivalent of gdalwarp -dstalpha
  690. if self.in_nodata == [] and self.out_ds.RasterCount in [1,3]:
  691. import tempfile
  692. tempfilename = tempfile.mktemp('-gdal2tiles.vrt')
  693. self.out_ds.GetDriver().CreateCopy(tempfilename, self.out_ds)
  694. # open as a text file
  695. s = open(tempfilename).read()
  696. # Add the warping options
  697. s = s.replace("""<BlockXSize>""","""<VRTRasterBand dataType="Byte" band="%i" subClass="VRTWarpedRasterBand">
  698. <ColorInterp>Alpha</ColorInterp>
  699. </VRTRasterBand>
  700. <BlockXSize>""" % (self.out_ds.RasterCount + 1))
  701. s = s.replace("""</GDALWarpOptions>""", """<DstAlphaBand>%i</DstAlphaBand>
  702. </GDALWarpOptions>""" % (self.out_ds.RasterCount + 1))
  703. s = s.replace("""</WorkingDataType>""", """</WorkingDataType>
  704. <Option name="INIT_DEST">0</Option>""")
  705. # save the corrected VRT
  706. open(tempfilename,"w").write(s)
  707. # open by GDAL as self.out_ds
  708. self.out_ds = gdal.Open(tempfilename) #, gdal.GA_ReadOnly)
  709. # delete the temporary file
  710. os.unlink(tempfilename)
  711. if self.options.verbose:
  712. print "Modified -dstalpha warping result saved into 'tiles1.vrt'"
  713. open("tiles1.vrt","w").write(s)
  714. s = '''
  715. '''
  716. else:
  717. self.error("Input file has unknown SRS.", "Use --s_srs ESPG:xyz (or similar) to provide source reference system." )
  718. if self.out_ds and self.options.verbose:
  719. print "Projected file:", "tiles.vrt", "( %sP x %sL - %s bands)" % (self.out_ds.RasterXSize, self.out_ds.RasterYSize, self.out_ds.RasterCount)
  720. if not self.out_ds:
  721. self.out_ds = self.in_ds
  722. #
  723. # Here we should have a raster (out_ds) in the correct Spatial Reference system
  724. #
  725. # KML test
  726. self.isepsg4326 = False
  727. srs4326 = osr.SpatialReference()
  728. srs4326.ImportFromEPSG(4326)
  729. if self.out_srs and srs4326.ExportToProj4() == self.out_srs.ExportToProj4():
  730. self.kml = True
  731. self.isepsg4326 = True
  732. if self.options.verbose:
  733. print "KML autotest OK!"
  734. # Instantiate image output.
  735. self.image_output = ImageOutput(self.options.tile_format, self.out_ds, self.tilesize,
  736. self.options.resampling, self.in_nodata, self.output)
  737. # Read the georeference
  738. self.out_gt = self.out_ds.GetGeoTransform()
  739. #originX, originY = self.out_gt[0], self.out_gt[3]
  740. #pixelSize = self.out_gt[1] # = self.out_gt[5]
  741. # Test the size of the pixel
  742. # MAPTILER - COMMENTED
  743. #if self.out_gt[1] != (-1 * self.out_gt[5]) and self.options.profile != 'raster':
  744. # TODO: Process corectly coordinates with are have swichted Y axis (display in OpenLayers too)
  745. #self.error("Size of the pixel in the output differ for X and Y axes.")
  746. # Report error in case rotation/skew is in geotransform (possible only in 'raster' profile)
  747. if (self.out_gt[2], self.out_gt[4]) != (0,0):
  748. self.error("Georeference of the raster contains rotation or skew. Such raster is not supported. Please use gdalwarp first.")
  749. # TODO: Do the warping in this case automaticaly
  750. #
  751. # Here we expect: pixel is square, no rotation on the raster
  752. #
  753. # Output Bounds - coordinates in the output SRS
  754. self.ominx = self.out_gt[0]
  755. self.omaxx = self.out_gt[0]+self.out_ds.RasterXSize*self.out_gt[1]
  756. self.omaxy = self.out_gt[3]
  757. self.ominy = self.out_gt[3]-self.out_ds.RasterYSize*self.out_gt[1]
  758. # Note: maybe round(x, 14) to avoid the gdal_translate behaviour, when 0 becomes -1e-15
  759. if self.options.verbose:
  760. print "Bounds (output srs):", round(self.ominx, 13), self.ominy, self.omaxx, self.omaxy
  761. #
  762. # Calculating ranges for tiles in different zoom levels
  763. #
  764. if self.options.profile == 'mercator':
  765. self.mercator = GlobalMercator() # from globalmaptiles.py
  766. # Function which generates SWNE in LatLong for given tile
  767. self.tileswne = self.mercator.TileLatLonBounds
  768. # Generate table with min max tile coordinates for all zoomlevels
  769. self.tminmax = range(0,32)
  770. for tz in range(0, 32):
  771. tminx, tminy = self.mercator.MetersToTile( self.ominx, self.ominy, tz )
  772. tmaxx, tmaxy = self.mercator.MetersToTile( self.omaxx, self.omaxy, tz )
  773. # crop tiles extending world limits (+-180,+-90)
  774. tminx, tminy = max(0, tminx), max(0, tminy)
  775. tmaxx, tmaxy = min(2**tz-1, tmaxx), min(2**tz-1, tmaxy)
  776. self.tminmax[tz] = (tminx, tminy, tmaxx, tmaxy)
  777. # TODO: Maps crossing 180E (Alaska?)
  778. # Get the minimal zoom level (map covers area equivalent to one tile)
  779. if self.tminz == None:
  780. self.tminz = self.mercator.ZoomForPixelSize( self.out_gt[1] * max( self.out_ds.RasterXSize, self.out_ds.RasterYSize) / float(self.tilesize) )
  781. # Get the maximal zoom level (closest possible zoom level up on the resolution of raster)
  782. if self.tmaxz == None:
  783. self.tmaxz = self.mercator.ZoomForPixelSize( self.out_gt[1] )
  784. if self.options.verbose:
  785. print "Bounds (latlong):", self.mercator.MetersToLatLon( self.ominx, self.ominy), self.mercator.MetersToLatLon( self.omaxx, self.omaxy)
  786. print 'MinZoomLevel:', self.tminz
  787. print "MaxZoomLevel:", self.tmaxz, "(", self.mercator.Resolution( self.tmaxz ),")"
  788. if self.options.profile == 'geodetic':
  789. self.geodetic = GlobalGeodetic() # from globalmaptiles.py
  790. # Function which generates SWNE in LatLong for given tile
  791. self.tileswne = self.geodetic.TileLatLonBounds
  792. # Generate table with min max tile coordinates for all zoomlevels
  793. self.tminmax = range(0,32)
  794. for tz in range(0, 32):
  795. tminx, tminy = self.geodetic.LatLonToTile( self.ominx, self.ominy, tz )
  796. tmaxx, tmaxy = self.geodetic.LatLonToTile( self.omaxx, self.omaxy, tz )
  797. # crop tiles extending world limits (+-180,+-90)
  798. tminx, tminy = max(0, tminx), max(0, tminy)
  799. tmaxx, tmaxy = min(2**(tz+1)-1, tmaxx), min(2**tz-1, tmaxy)
  800. self.tminmax[tz] = (tminx, tminy, tmaxx, tmaxy)
  801. # TODO: Maps crossing 180E (Alaska?)
  802. # Get the maximal zoom level (closest possible zoom level up on the resolution of raster)
  803. if self.tminz == None:
  804. self.tminz = self.geodetic.ZoomForPixelSize( self.out_gt[1] * max( self.out_ds.RasterXSize, self.out_ds.RasterYSize) / float(self.tilesize) )
  805. # Get the maximal zoom level (closest possible zoom level up on the resolution of raster)
  806. if self.tmaxz == None:
  807. self.tmaxz = self.geodetic.ZoomForPixelSize( self.out_gt[1] )
  808. if self.options.verbose:
  809. print "Bounds (latlong):", self.ominx, self.ominy, self.omaxx, self.omaxy
  810. if self.options.profile in ('raster', 'gearth'):
  811. log2 = lambda x: math.log10(x) / math.log10(2) # log2 (base 2 logarithm)
  812. self.nativezoom = int(max( math.ceil(log2(self.out_ds.RasterXSize/float(self.tilesize))),
  813. math.ceil(log2(self.out_ds.RasterYSize/float(self.tilesize)))))
  814. if self.options.verbose:
  815. print "Native zoom of the raster:", self.nativezoom
  816. # Get the minimal zoom level (whole raster in one tile)
  817. if self.tminz == None:
  818. self.tminz = 0
  819. # Get the maximal zoom level (native resolution of the raster)
  820. if self.tmaxz == None:
  821. self.tmaxz = self.nativezoom
  822. # Generate table with min max tile coordinates for all zoomlevels
  823. self.tminmax = range(0, self.tmaxz+1)
  824. self.tsize = range(0, self.tmaxz+1)
  825. for tz in range(0, self.tmaxz+1):
  826. tsize = 2.0**(self.nativezoom-tz)*self.tilesize
  827. tminx, tminy = 0, 0
  828. tmaxx = int(math.ceil( self.out_ds.RasterXSize / tsize )) - 1
  829. tmaxy = int(math.ceil( self.out_ds.RasterYSize / tsize )) - 1
  830. self.tsize[tz] = math.ceil(tsize)
  831. self.tminmax[tz] = (tminx, tminy, tmaxx, tmaxy)
  832. # Function which generates SWNE in LatLong for given tile
  833. if self.kml and self.in_srs_wkt:
  834. self.ct = osr.CoordinateTransformation(self.in_srs, srs4326)
  835. def rastertileswne(x,y,z):
  836. pixelsizex = (2**(self.tmaxz-z) * self.out_gt[1]) # X-pixel size in level
  837. pixelsizey = (2**(self.tmaxz-z) * self.out_gt[1]) # Y-pixel size in level (usually -1*pixelsizex)
  838. west = self.out_gt[0] + x*self.tilesize*pixelsizex
  839. east = west + self.tilesize*pixelsizex
  840. south = self.ominy + y*self.tilesize*pixelsizex
  841. north = south + self.tilesize*pixelsizex
  842. if not self.isepsg4326:
  843. # Transformation to EPSG:4326 (WGS84 datum)
  844. west, south = self.ct.TransformPoint(west, south)[:2]
  845. east, north = self.ct.TransformPoint(east, north)[:2]
  846. return south, west, north, east
  847. self.tileswne = rastertileswne
  848. else:
  849. self.tileswne = lambda x, y, z: (0,0,0,0)
  850. # -------------------------------------------------------------------------
  851. def generate_metadata(self):
  852. """Generation of main metadata files and HTML viewers (metadata related to particular tiles are generated during the tile processing)."""
  853. if not os.path.exists(self.output):
  854. os.makedirs(self.output)
  855. if self.options.profile == 'mercator':
  856. south, west = self.mercator.MetersToLatLon( self.ominx, self.ominy)
  857. north, east = self.mercator.MetersToLatLon( self.omaxx, self.omaxy)
  858. south, west = max(-85.05112878, south), max(-180.0, west)
  859. north, east = min(85.05112878, north), min(180.0, east)
  860. self.swne = (south, west, north, east)
  861. # Generate googlemaps.html
  862. if self.options.webviewer in ('all','google') and self.options.profile == 'mercator':
  863. if not self.options.resume or not os.path.exists(os.path.join(self.output, 'googlemaps.html')):
  864. f = open(os.path.join(self.output, 'googlemaps.html'), 'w')
  865. f.write( self.generate_googlemaps() )
  866. f.close()
  867. # Generate openlayers.html
  868. if self.options.webviewer in ('all','openlayers'):
  869. if not self.options.resume or not os.path.exists(os.path.join(self.output, 'openlayers.html')):
  870. f = open(os.path.join(self.output, 'openlayers.html'), 'w')
  871. f.write( self.generate_openlayers() )
  872. f.close()
  873. elif self.options.profile == 'geodetic':
  874. west, south = self.ominx, self.ominy
  875. east, north = self.omaxx, self.omaxy
  876. south, west = max(-90.0, south), max(-180.0, west)
  877. north, east = min(90.0, north), min(180.0, east)
  878. self.swne = (south, west, north, east)
  879. # Generate openlayers.html
  880. if self.options.webviewer in ('all','openlayers'):
  881. if not self.options.resume or not os.path.exists(os.path.join(self.output, 'openlayers.html')):
  882. f = open(os.path.join(self.output, 'openlayers.html'), 'w')
  883. f.write( self.generate_openlayers() )
  884. f.close()
  885. elif self.options.profile == 'raster':
  886. west, south = self.ominx, self.ominy
  887. east, north = self.omaxx, self.omaxy
  888. self.swne = (south, west, north, east)
  889. # Generate openlayers.html
  890. if self.options.webviewer in ('all','openlayers'):
  891. if not self.options.resume or not os.path.exists(os.path.join(self.output, 'openlayers.html')):
  892. f = open(os.path.join(self.output, 'openlayers.html'), 'w')
  893. f.write( self.generate_openlayers() )
  894. f.close()
  895. # Generate tilemapresource.xml.
  896. if (self.options.tile_format != 'hybrid' and self.options.profile != 'gearth'
  897. and (not self.options.resume or not os.path.exists(os.path.join(self.output, 'tilemapresource.xml')))):
  898. f = open(os.path.join(self.output, 'tilemapresource.xml'), 'w')
  899. f.write( self.generate_tilemapresource())
  900. f.close()
  901. # -------------------------------------------------------------------------
  902. def generate_base_tiles(self):
  903. """Generation of the base tiles (the lowest in the pyramid) directly from the input raster"""
  904. print "Generating Base Tiles:"
  905. if self.options.verbose:
  906. #mx, my = self.out_gt[0], self.out_gt[3] # OriginX, OriginY
  907. #px, py = self.mercator.MetersToPixels( mx, my, self.tmaxz)
  908. #print "Pixel coordinates:", px, py, (mx, my)
  909. print
  910. print "Tiles generated from the max zoom level:"
  911. print "----------------------------------------"
  912. print
  913. # Set the bounds
  914. tminx, tminy, tmaxx, tmaxy = self.tminmax[self.tmaxz]
  915. querysize = self.querysize
  916. # Just the center tile
  917. #tminx = tminx+ (tmaxx - tminx)/2
  918. #tminy = tminy+ (tmaxy - tminy)/2
  919. #tmaxx = tminx
  920. #tmaxy = tminy
  921. #print tminx, tminy, tmaxx, tmaxy
  922. tcount = (1+abs(tmaxx-tminx)) * (1+abs(tmaxy-tminy))
  923. #print tcount
  924. ti = 0
  925. ds = self.out_ds
  926. tz = self.tmaxz
  927. for ty in range(tmaxy, tminy-1, -1): #range(tminy, tmaxy+1):
  928. for tx in range(tminx, tmaxx+1):
  929. if self.stopped:
  930. break
  931. ti += 1
  932. #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)
  933. # Don't scale up by nearest neighbour, better change the querysize
  934. # to the native resolution (and return smaller query tile) for scaling
  935. if self.options.profile in ('mercator','geodetic'):
  936. if self.options.profile == 'mercator':
  937. # Tile bounds in EPSG:900913
  938. b = self.mercator.TileBounds(tx, ty, tz)
  939. elif self.options.profile == 'geodetic':
  940. b = self.geodetic.TileBounds(tx, ty, tz)
  941. rb, wb = self.geo_query( ds, b[0], b[3], b[2], b[1])
  942. nativesize = wb[0]+wb[2] # Pixel size in the raster covering query geo extent
  943. if self.options.verbose:
  944. print "\tNative Extent (querysize",nativesize,"): ", rb, wb
  945. querysize = self.querysize
  946. # Tile bounds in raster coordinates for ReadRaster query
  947. rb, wb = self.geo_query( ds, b[0], b[3], b[2], b[1], querysize=querysize)
  948. rx, ry, rxsize, rysize = rb
  949. wx, wy, wxsize, wysize = wb
  950. else: # 'raster' or 'gearth' profile:
  951. tsize = int(self.tsize[tz]) # tilesize in raster coordinates for actual zoom
  952. xsize = self.out_ds.RasterXSize # size of the raster in pixels
  953. ysize = self.out_ds.RasterYSize
  954. if tz >= self.nativezoom:
  955. querysize = self.tilesize # int(2**(self.nativezoom-tz) * self.tilesize)
  956. rx = (tx) * tsize
  957. rxsize = 0
  958. if tx == tmaxx:
  959. rxsize = xsize % tsize
  960. if rxsize == 0:
  961. rxsize = tsize
  962. rysize = 0
  963. if ty == tmaxy:
  964. rysize = ysize % tsize
  965. if rysize == 0:
  966. rysize = tsize
  967. ry = ysize - (ty * tsize) - rysize
  968. wx, wy = 0, 0
  969. wxsize, wysize = int(rxsize/float(tsize) * self.tilesize), int(rysize/float(tsize) * self.tilesize)
  970. if wysize != self.tilesize:
  971. wy = self.tilesize - wysize
  972. xyzzy = Xyzzy(querysize, rx, ry, rxsize, rysize, wx, wy, wxsize, wysize)
  973. if self.options.resume:
  974. exists = self.image_output.tile_exists(tx, ty, tz)
  975. if exists and self.options.verbose:
  976. print "Tile generation skiped because of --resume"
  977. else:
  978. exists = False
  979. if not exists:
  980. try:
  981. if self.options.verbose:
  982. print ti,'/',tcount
  983. print "\tReadRaster Extent: ", (rx, ry, rxsize, rysize), (wx, wy, wxsize, wysize)
  984. self.image_output.write_base_tile(tx, ty, tz, xyzzy)
  985. except ImageOutputException, e:
  986. self.error("'%d/%d/%d': %s" % (tz, tx, ty, e.message))
  987. if not self.options.verbose:
  988. self.progressbar( ti / float(tcount) )
  989. # -------------------------------------------------------------------------
  990. def generate_overview_tiles(self):
  991. """Generation of the overview tiles (higher in the pyramid) based on existing tiles"""
  992. print "Generating Overview Tiles:"
  993. # Usage of existing tiles: from 4 underlying tiles generate one as overview.
  994. tcount = 0
  995. for tz in range(self.tmaxz-1, self.tminz-1, -1):
  996. tminx, tminy, tmaxx, tmaxy = self.tminmax[tz]
  997. tcount += (1+abs(tmaxx-tminx)) * (1+abs(tmaxy-tminy))
  998. ti = 0
  999. # querysize = tilesize * 2
  1000. for tz in range(self.tmaxz-1, self.tminz-1, -1):
  1001. tminx, tminy, tmaxx, tmaxy = self.tminmax[tz]
  1002. for ty in range(tmaxy, tminy-1, -1): #range(tminy, tmaxy+1):
  1003. for tx in range(tminx, tmaxx+1):
  1004. if self.stopped:
  1005. break
  1006. ti += 1
  1007. if self.options.resume:
  1008. exists = self.image_output.tile_exists(tx, ty, tz)
  1009. if exists and self.options.verbose:
  1010. print "Tile generation skiped because of --resume"
  1011. else:
  1012. exists = False
  1013. if not exists:
  1014. try:
  1015. if self.options.verbose:
  1016. print ti,'/',tcount
  1017. 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)
  1018. self.image_output.write_overview_tile(tx, ty, tz)
  1019. except Exception, e:
  1020. self.error("'%d/%d/%d': %s" % (tz, tx, ty, e.message))
  1021. if not self.options.verbose:
  1022. self.progressbar( ti / float(tcount) )
  1023. if not self.kml:
  1024. return
  1025. # Generate KML based on which files were produced.
  1026. # Base level KML.
  1027. kml_tiles = {}
  1028. tz = self.tmaxz
  1029. tminx, tminy, tmaxx, tmaxy = self.tminmax[tz]
  1030. for ty in range(tminy, tmaxy+1):
  1031. for tx in range(tminx, tmaxx+1):
  1032. image_format = self.image_output.try_to_use_existing_tile(tx, ty, tz)
  1033. if image_format is None:
  1034. continue
  1035. d = self.get_kml_dict(tx, ty, tz, image_format)
  1036. if self.kml_depth == 1 or self.tmaxz == self.tminz:
  1037. self.write_kml_tile(tx, ty, tz, self.generate_node_kml(d, []))
  1038. kml_tiles[tx,ty,tz] = self.generate_link_kml(d)
  1039. else:
  1040. kml_tiles[tx,ty,tz] = self.generate_leaf_kml(d)
  1041. # Overviews KML.
  1042. for tz in range(self.tmaxz-1, self.tminz-1, -1):
  1043. tminx, tminy, tmaxx, tmaxy = self.tminmax[tz]
  1044. for ty in range(tminy, tmaxy+1):
  1045. for tx in range(tminx, tmaxx+1):
  1046. image_format = self.image_output.try_to_use_existing_tile(tx, ty, tz)
  1047. if image_format is None:
  1048. continue
  1049. d = self.get_kml_dict(tx, ty, tz, image_format)
  1050. children = [kml_tiles[x,y,tz+1]
  1051. for y in range(2*ty, 2*ty + 2)
  1052. for x in range(2*tx, 2*tx + 2)
  1053. if (x,y,tz+1) in kml_tiles]
  1054. node_kml = self.generate_node_kml(d, children)
  1055. if (self.tmaxz-tz + 1) % self.kml_depth == 0 or tz == self.tminz:
  1056. self.write_kml_tile(tx, ty, tz, node_kml)
  1057. kml_tiles[tx,ty,tz] = self.generate_link_kml(d)
  1058. else:
  1059. kml_tiles[tx,ty,tz] = node_kml
  1060. # Root KML.
  1061. tminx, tminy, tmaxx, tmaxy = self.tminmax[self.tminz]
  1062. children_kml = [kml_tiles[x,y,self.tminz]
  1063. for y in range(tminy, tmaxy+1)
  1064. for x in range(tminx, tmaxx+1)
  1065. if (x,y,self.tminz) in kml_tiles]
  1066. self.write_kml_file("doc.kml", self.options.title, "\n".join(children_kml))
  1067. # -------------------------------------------------------------------------
  1068. def geo_query(self, ds, ulx, uly, lrx, lry, querysize = 0):
  1069. """For given dataset and query in cartographic coordinates
  1070. returns parameters for ReadRaster() in raster coordinates and
  1071. x/y shifts (for border tiles). If the querysize is not given, the
  1072. extent is returned in the native resolution of dataset ds."""
  1073. geotran = ds.GetGeoTransform()
  1074. rx= int((ulx - geotran[0]) / geotran[1] + 0.001)
  1075. ry= int((uly - geotran[3]) / geotran[5] + 0.001)
  1076. rxsize= int((lrx - ulx) / geotran[1] + 0.5)
  1077. rysize= int((lry - uly) / geotran[5] + 0.5)
  1078. if not querysize:
  1079. wxsize, wysize = rxsize, rysize
  1080. else:
  1081. wxsize, wysize = querysize, querysize
  1082. # Coordinates should not go out of the bounds of the raster
  1083. wx = 0
  1084. if rx < 0:
  1085. rxshift = abs(rx)
  1086. wx = int( wxsize * (float(rxshift) / rxsize) )
  1087. wxsize = wxsize - wx
  1088. rxsize = rxsize - int( rxsize * (float(rxshift) / rxsize) )
  1089. rx = 0
  1090. if rx+rxsize > ds.RasterXSize:
  1091. wxsize = int( wxsize * (float(ds.RasterXSize - rx) / rxsize) )
  1092. rxsize = ds.RasterXSize - rx
  1093. wy = 0
  1094. if ry < 0:
  1095. ryshift = abs(ry)
  1096. wy = int( wysize * (float(ryshift) / rysize) )
  1097. wysize = wysize - wy
  1098. rysize = rysize - int( rysize * (float(ryshift) / rysize) )
  1099. ry = 0
  1100. if ry+rysize > ds.RasterYSize:
  1101. wysize = int( wysize * (float(ds.RasterYSize - ry) / rysize) )
  1102. rysize = ds.RasterYSize - ry
  1103. return (rx, ry, rxsize, rysize), (wx, wy, wxsize, wysize)
  1104. # -------------------------------------------------------------------------
  1105. def write_kml_tile(self, tx, ty, tz, kml):
  1106. filename = get_tile_filename(tx, ty, tz, "kml")
  1107. self.write_kml_file(filename, filename, kml)
  1108. def write_kml_file(self, filename, title, content):
  1109. f = open(os.path.join(self.output, filename), 'w')
  1110. f.write(self.generate_document_kml(title, content))
  1111. f.close()
  1112. def generate_node_kml(self, d, children):
  1113. """Return KML describing tile image and its children."""
  1114. return self.generate_leaf_kml(d, "\n".join(children))
  1115. def generate_leaf_kml(self, d, content=""):
  1116. """Return KML describing tile image and insert content."""
  1117. return ("""\
  1118. <Folder>
  1119. <Region>
  1120. <Lod>
  1121. <minLodPixels>%(minlodpixels)d</minLodPixels>
  1122. <maxLodPixels>%(maxlodpixels)d</maxLodPixels>
  1123. </Lod>
  1124. <LatLonAltBox>
  1125. <north>%(north).14f</north>
  1126. <south>%(south).14f</south>
  1127. <east>%(east).14f</east>
  1128. <west>%(west).14f</west>
  1129. </LatLonAltBox>
  1130. </Region>
  1131. <GroundOverlay>
  1132. <drawOrder>%(draw_order)d</drawOrder>
  1133. <Icon>
  1134. <href>%(image_url)s</href>
  1135. </Icon>
  1136. <LatLonBox>
  1137. <north>%(north).14f</north>
  1138. <south>%(south).14f</south>
  1139. <east>%(east).14f</east>
  1140. <west>%(west).14f</west>
  1141. </LatLonBox>
  1142. </GroundOverlay>""" % d
  1143. + """\
  1144. %s
  1145. </Folder>""" % content)
  1146. def generate_link_kml(self, d):
  1147. """Return KML linking to the tile."""
  1148. return """\
  1149. <NetworkLink>
  1150. <name>%(image_filename)s</name>
  1151. <Region>
  1152. <Lod>
  1153. <minLodPixels>%(minlodpixels)d</minLodPixels>
  1154. <maxLodPixels>-1</maxLodPixels>
  1155. </Lod>
  1156. <LatLonAltBox>
  1157. <north>%(north).14f</north>
  1158. <south>%(south).14f</south>
  1159. <east>%(east).14f</east>
  1160. <west>%(west).14f</west>
  1161. </LatLonAltBox>
  1162. </Region>
  1163. <Link>
  1164. <href>%(link_url)s</href>
  1165. <viewRefreshMode>onRegion</viewRefreshMode>
  1166. </Link>
  1167. </NetworkLink>""" % d
  1168. def generate_document_kml(self, title, content):
  1169. """Return full KML document with given title and content."""
  1170. return """\
  1171. <?xml version="1.0" encoding="utf-8"?>
  1172. <kml xmlns="http://earth.google.com/kml/2.1">
  1173. <Document>
  1174. <name>%s</name>
  1175. <description></description>
  1176. <Style>
  1177. <ListStyle id="hideChildren">
  1178. <listItemType>checkHideChildren</listItemType>
  1179. </ListStyle>
  1180. </Style>
  1181. %s
  1182. </Document>
  1183. </kml>""" % (title, content)
  1184. def get_kml_dict(self, tx, ty, tz, image_format):
  1185. """Return dictionary describing KML info about tile to be used in templates."""
  1186. d = {}
  1187. d["south"], d["west"], d["north"], d["east"] = self.tileswne(tx, ty, tz)
  1188. image_filename = get_tile_filename(tx, ty, tz, format_extension[image_format])
  1189. d["image_filename"] = image_filename
  1190. if not self.options.url:
  1191. d["image_url"] = "../../%s" % image_filename
  1192. else:
  1193. d["image_url"] = "%s%s" % (self.options.url, image_filename)
  1194. url = self.options.url
  1195. if not url:
  1196. # Top level KML is linked from `doc.kml' and it needs different path.
  1197. if tz == self.tminz:
  1198. url = ""
  1199. else:
  1200. url = "../../"
  1201. d["link_url"] = "%s%s" % (url, get_tile_filename(tx, ty, tz, "kml"))
  1202. d["minlodpixels"] = int(self.tilesize / 2)
  1203. d["maxlodpixels"] = -1 # int(self.tilesize * 8)
  1204. if tx == 0:
  1205. d["draw_order"] = 2 * tz + 1
  1206. else:
  1207. d["draw_order"] = 2 * tz
  1208. return d
  1209. # -------------------------------------------------------------------------
  1210. def generate_tilemapresource(self):
  1211. """
  1212. Template for tilemapresource.xml. Returns filled string. Expected variables:
  1213. title, north, south, east, west, isepsg4326, projection, publishurl,
  1214. zoompixels, tilesize, tileformat, profile
  1215. """
  1216. args = {}
  1217. args['title'] = self.options.title
  1218. args['south'], args['west'], args['north'], args['east'] = self.swne
  1219. args['tilesize'] = self.tilesize
  1220. args['tileformat'] = format_extension[self.image_output.format]
  1221. args['mime'] = format_mime[self.image_output.format]
  1222. args['publishurl'] = self.options.url
  1223. args['profile'] = self.options.profile
  1224. if self.options.profile == 'mercator':
  1225. args['srs'] = "EPSG:900913"
  1226. elif self.options.profile == 'geodetic':
  1227. args['srs'] = "EPSG:4326"
  1228. elif self.options.s_srs:
  1229. args['srs'] = self.options.s_srs
  1230. elif self.out_srs:
  1231. args['srs'] = self.out_srs.ExportToWkt()
  1232. else:
  1233. args['srs'] = ""
  1234. s = """<?xml version="1.0" encoding="utf-8"?>
  1235. <TileMap version="1.0.0" tilemapservice="http://tms.osgeo.org/1.0.0">
  1236. <Title>%(title)s</Title>
  1237. <Abstract></Abstract>
  1238. <SRS>%(srs)s</SRS>
  1239. <BoundingBox minx="%(south).14f" miny="%(west).14f" maxx="%(north).14f" maxy="%(east).14f"/>
  1240. <Origin x="%(south).14f" y="%(west).14f"/>
  1241. <TileFormat width="%(tilesize)d" height="%(tilesize)d" mime-type="%(mime)s" extension="%(tileformat)s"/>
  1242. <TileSets profile="%(profile)s">
  1243. """ % args
  1244. for z in range(self.tminz, self.tmaxz+1):
  1245. if self.options.profile == 'raster':
  1246. s += """ <TileSet href="%s%d" units-per-pixel="%.14f" order="%d"/>\n""" % (args['publishurl'], z, (2**(self.nativezoom-z) * self.out_gt[1]), z)
  1247. elif self.options.profile == 'mercator':
  1248. s += """ <TileSet href="%s%d" units-per-pixel="%.14f" order="%d"/>\n""" % (args['publishurl'], z, 156543.0339/2**z, z)
  1249. elif self.options.profile == 'geodetic':
  1250. s += """ <TileSet href="%s%d" units-per-pixel="%.14f" order="%d"/>\n""" % (args['publishurl'], z, 0.703125/2**z, z)
  1251. s += """ </TileSets>
  1252. </TileMap>
  1253. """
  1254. return s
  1255. # -------------------------------------------------------------------------
  1256. def generate_googlemaps(self):
  1257. """
  1258. Template for googlemaps.html implementing Overlay of tiles for 'mercator' profile.
  1259. It returns filled string. Expected variables:
  1260. title, googlemapskey, north, south, east, west, minzoom, maxzoom, tilesize, tileformat, publishurl
  1261. """
  1262. args = {}
  1263. args['title'] = self.options.title
  1264. args['googlemapskey'] = self.options.googlekey
  1265. args['south'], args['west'], args['north'], args['east'] = self.swne
  1266. args['minzoom'] = self.tminz
  1267. args['maxzoom'] = self.tmaxz
  1268. args['tilesize'] = self.tilesize
  1269. args['tileformat'] = format_extension[self.image_output.format]
  1270. args['publishurl'] = self.options.url
  1271. args['copyright'] = self.options.copyright
  1272. s = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  1273. <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
  1274. <head>
  1275. <title>%(title)s</title>
  1276. <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  1277. <meta http-equiv='imagetoolbar' content='no'/>
  1278. <style type="text/css"> v\:* {behavior:url(#default#VML);}
  1279. html, body { overflow: hidden; padding: 0; height: 100%%; width: 100%%; font-family: 'Lucida Grande',Geneva,Arial,Verdana,sans-serif; }
  1280. body { margin: 10px; background: #fff; }
  1281. h1 { margin: 0; padding: 6px; border:0; font-size: 20pt; }
  1282. #header { height: 43px; padding: 0; background-color: #eee; border: 1px solid #888; }
  1283. #subheader { height: 12px; text-align: right; font-size: 10px; color: #555;}
  1284. #map { height: 95%%; border: 1px solid #888; }
  1285. </style>
  1286. <script src='http://maps.google.com/maps?file=api&amp;v=2&amp;key=%(googlemapskey)s' type='text/javascript'></script>
  1287. <script type="text/javascript">
  1288. //<![CDATA[
  1289. /*
  1290. * Constants for given map
  1291. * TODO: read it from tilemapresource.xml
  1292. */
  1293. var mapBounds = new GLatLngBounds(new GLatLng(%(south)s, %(west)s), new GLatLng(%(north)s, %(east)s));
  1294. var mapMinZoom = %(minzoom)s;
  1295. var mapMaxZoom = %(maxzoom)s;
  1296. var opacity = 0.75;
  1297. var map;
  1298. var hybridOverlay;
  1299. /*
  1300. * Create a Custom Opacity GControl
  1301. * http://www.maptiler.org/google-maps-overlay-opacity-control/
  1302. */
  1303. var CTransparencyLENGTH = 58;
  1304. // maximum width that the knob can move (slide width minus knob width)
  1305. function CTransparencyControl( overlay ) {
  1306. this.overlay = overlay;
  1307. this.opacity = overlay.getTileLayer().getOpacity();
  1308. }
  1309. CTransparencyControl.prototype = new GControl();
  1310. // This function positions the slider to match the specified opacity
  1311. CTransparencyControl.prototype.setSlider = function(pos) {
  1312. var left = Math.round((CTransparencyLENGTH*pos));
  1313. this.slide.left = left;
  1314. this.knob.style.left = left+"px";
  1315. this.knob.style.top = "0px";
  1316. }
  1317. // This function reads the slider and sets the overlay opacity level
  1318. CTransparencyControl.prototype.setOpacity = function() {
  1319. // set the global variable
  1320. opacity = this.slide.left/CTransparencyLENGTH;
  1321. this.map.clearOverlays();
  1322. this.map.addOverlay(this.overlay, { zPriority: 0 });
  1323. if (this.map.getCurrentMapType() == G_HYBRID_MAP) {
  1324. this.map.addOverlay(hybridOverlay);
  1325. }
  1326. }
  1327. // This gets called by the API when addControl(new CTransparencyControl())
  1328. CTransparencyControl.prototype.initialize = function(map) {
  1329. var that=this;
  1330. this.map = map;
  1331. // Is this MSIE, if so we need to use AlphaImageLoader
  1332. var agent = navigator.userAgent.toLowerCase();
  1333. if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){this.ie = true} else {this.ie = false}
  1334. // create the background graphic as a <div> containing an image
  1335. var container = document.createElement("div");
  1336. container.style.width="70px";
  1337. container.style.height="21px";
  1338. // Handle transparent PNG files in MSIE
  1339. if (this.ie) {
  1340. var loader = "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://www.maptiler.org/img/opacity-slider.png', sizingMethod='crop');";
  1341. container.innerHTML = '<div style="height:21px; width:70px; ' +loader+ '" ></div>';
  1342. } else {
  1343. container.innerHTML = '<div style="height:21px; width:70px; background-image: url(http://www.maptiler.org/img/opacity-slider.png)" ></div>';
  1344. }
  1345. // create the knob as a GDraggableObject
  1346. // Handle transparent PNG files in MSIE
  1347. if (this.ie) {
  1348. var loader = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://www.maptiler.org/img/opacity-slider.png', sizingMethod='crop');";
  1349. this.knob = document.createElement("div");
  1350. this.knob.style.height="21px";
  1351. this.knob.style.width="13px";
  1352. this.knob.style.overflow="hidden";
  1353. this.knob_img = document.createElement("div");
  1354. this.knob_img.style.height="21px";
  1355. this.knob_img.style.width="83px";
  1356. this.knob_img.style.filter=loader;
  1357. this.knob_img.style.position="relative";
  1358. this.knob_img.style.left="-70px";
  1359. this.knob.appendChild(this.knob_img);
  1360. } else {
  1361. this.knob = document.createElement("div");
  1362. this.knob.style.height="21px";
  1363. this.knob.style.width="13px";
  1364. this.knob.style.backgroundImage="url(http://www.maptiler.org/img/opacity-slider.png)";
  1365. this.knob.style.backgroundPosition="-70px 0px";
  1366. }
  1367. container.appendChild(this.knob);
  1368. this.slide=new GDraggableObject(this.knob, {container:container});
  1369. this.slide.setDraggableCursor('pointer');
  1370. this.slide.setDraggingCursor('pointer');
  1371. this.container = container;
  1372. // attach the control to the map
  1373. map.getContainer().appendChild(container);
  1374. // init slider
  1375. this.setSlider(this.opacity);
  1376. // Listen for the slider being moved and set the opacity
  1377. GEvent.addListener(this.slide, "dragend", function() {that.setOpacity()});
  1378. //GEvent.addListener(this.container, "click", function( x, y ) { alert(x, y) });
  1379. return container;
  1380. }
  1381. // Set the default position for the control
  1382. CTransparencyControl.prototype.getDefaultPosition = function() {
  1383. return new