| [9f5877d] | 1 | #!/usr/bin/python3
|
|---|
| 2 | # -*- coding: utf-8 -*-
|
|---|
| 3 | # ******************************************************************************
|
|---|
| [b72d9c4] | 4 | # $Id: gdal2tiles.py fae3a65f16af509cf9e0dd16cd16858d8e49eb25 2019-03-12 15:23:57 -0700 Kevin Mehall $
|
|---|
| [9f5877d] | 5 | #
|
|---|
| 6 | # Project: Google Summer of Code 2007, 2008 (http://code.google.com/soc/)
|
|---|
| 7 | # Support: BRGM (http://www.brgm.fr)
|
|---|
| 8 | # Purpose: Convert a raster into TMS (Tile Map Service) tiles in a directory.
|
|---|
| 9 | # - generate Google Earth metadata (KML SuperOverlay)
|
|---|
| 10 | # - generate simple HTML viewer based on Google Maps and OpenLayers
|
|---|
| 11 | # - support of global tiles (Spherical Mercator) for compatibility
|
|---|
| 12 | # with interactive web maps a la Google Maps
|
|---|
| 13 | # Author: Klokan Petr Pridal, klokan at klokan dot cz
|
|---|
| 14 | # Web: http://www.klokan.cz/projects/gdal2tiles/
|
|---|
| 15 | # GUI: http://www.maptiler.org/
|
|---|
| 16 | #
|
|---|
| 17 | ###############################################################################
|
|---|
| 18 | # Copyright (c) 2008, Klokan Petr Pridal
|
|---|
| 19 | # Copyright (c) 2010-2013, Even Rouault <even dot rouault at mines-paris dot org>
|
|---|
| 20 | #
|
|---|
| 21 | # Permission is hereby granted, free of charge, to any person obtaining a
|
|---|
| 22 | # copy of this software and associated documentation files (the "Software"),
|
|---|
| 23 | # to deal in the Software without restriction, including without limitation
|
|---|
| 24 | # the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|---|
| 25 | # and/or sell copies of the Software, and to permit persons to whom the
|
|---|
| 26 | # Software is furnished to do so, subject to the following conditions:
|
|---|
| 27 | #
|
|---|
| 28 | # The above copyright notice and this permission notice shall be included
|
|---|
| 29 | # in all copies or substantial portions of the Software.
|
|---|
| 30 | #
|
|---|
| 31 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|---|
| 32 | # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|---|
| 33 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
|---|
| 34 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|---|
| 35 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|---|
| 36 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|---|
| 37 | # DEALINGS IN THE SOFTWARE.
|
|---|
| 38 | # ******************************************************************************
|
|---|
| 39 |
|
|---|
| 40 | from __future__ import print_function, division
|
|---|
| 41 |
|
|---|
| 42 | import math
|
|---|
| [b72d9c4] | 43 | from multiprocessing import Pipe, Pool, Process, Manager
|
|---|
| [9f5877d] | 44 | import os
|
|---|
| 45 | import tempfile
|
|---|
| 46 | import threading
|
|---|
| 47 | import shutil
|
|---|
| 48 | import sys
|
|---|
| 49 | from uuid import uuid4
|
|---|
| 50 | from xml.etree import ElementTree
|
|---|
| 51 |
|
|---|
| 52 | from osgeo import gdal
|
|---|
| 53 | from osgeo import osr
|
|---|
| 54 |
|
|---|
| 55 | try:
|
|---|
| 56 | from PIL import Image
|
|---|
| 57 | import numpy
|
|---|
| 58 | import osgeo.gdal_array as gdalarray
|
|---|
| 59 | numpy_available = True
|
|---|
| 60 | except ImportError:
|
|---|
| 61 | # 'antialias' resampling is not available
|
|---|
| 62 | numpy_available = False
|
|---|
| 63 |
|
|---|
| [b72d9c4] | 64 | __version__ = "$Id: gdal2tiles.py fae3a65f16af509cf9e0dd16cd16858d8e49eb25 2019-03-12 15:23:57 -0700 Kevin Mehall $"
|
|---|
| [9f5877d] | 65 |
|
|---|
| 66 | resampling_list = ('average', 'near', 'bilinear', 'cubic', 'cubicspline', 'lanczos', 'antialias')
|
|---|
| 67 | profile_list = ('mercator', 'geodetic', 'raster')
|
|---|
| 68 | webviewer_list = ('all', 'google', 'openlayers', 'leaflet', 'none')
|
|---|
| 69 |
|
|---|
| 70 | threadLocal = threading.local()
|
|---|
| 71 |
|
|---|
| 72 | # =============================================================================
|
|---|
| 73 | # =============================================================================
|
|---|
| 74 | # =============================================================================
|
|---|
| 75 |
|
|---|
| 76 | __doc__globalmaptiles = """
|
|---|
| 77 | globalmaptiles.py
|
|---|
| 78 |
|
|---|
| 79 | Global Map Tiles as defined in Tile Map Service (TMS) Profiles
|
|---|
| 80 | ==============================================================
|
|---|
| 81 |
|
|---|
| 82 | Functions necessary for generation of global tiles used on the web.
|
|---|
| 83 | It contains classes implementing coordinate conversions for:
|
|---|
| 84 |
|
|---|
| 85 | - GlobalMercator (based on EPSG:3857)
|
|---|
| 86 | for Google Maps, Yahoo Maps, Bing Maps compatible tiles
|
|---|
| 87 | - GlobalGeodetic (based on EPSG:4326)
|
|---|
| 88 | for OpenLayers Base Map and Google Earth compatible tiles
|
|---|
| 89 |
|
|---|
| 90 | More info at:
|
|---|
| 91 |
|
|---|
| 92 | http://wiki.osgeo.org/wiki/Tile_Map_Service_Specification
|
|---|
| 93 | http://wiki.osgeo.org/wiki/WMS_Tiling_Client_Recommendation
|
|---|
| 94 | http://msdn.microsoft.com/en-us/library/bb259689.aspx
|
|---|
| 95 | http://code.google.com/apis/maps/documentation/overlays.html#Google_Maps_Coordinates
|
|---|
| 96 |
|
|---|
| 97 | Created by Klokan Petr Pridal on 2008-07-03.
|
|---|
| 98 | Google Summer of Code 2008, project GDAL2Tiles for OSGEO.
|
|---|
| 99 |
|
|---|
| 100 | In case you use this class in your product, translate it to another language
|
|---|
| 101 | or find it useful for your project please let me know.
|
|---|
| 102 | My email: klokan at klokan dot cz.
|
|---|
| 103 | I would like to know where it was used.
|
|---|
| 104 |
|
|---|
| 105 | Class is available under the open-source GDAL license (www.gdal.org).
|
|---|
| 106 | """
|
|---|
| 107 |
|
|---|
| 108 | MAXZOOMLEVEL = 32
|
|---|
| 109 |
|
|---|
| 110 |
|
|---|
| 111 | class GlobalMercator(object):
|
|---|
| 112 | r"""
|
|---|
| 113 | TMS Global Mercator Profile
|
|---|
| 114 | ---------------------------
|
|---|
| 115 |
|
|---|
| 116 | Functions necessary for generation of tiles in Spherical Mercator projection,
|
|---|
| 117 | EPSG:3857.
|
|---|
| 118 |
|
|---|
| 119 | Such tiles are compatible with Google Maps, Bing Maps, Yahoo Maps,
|
|---|
| 120 | UK Ordnance Survey OpenSpace API, ...
|
|---|
| 121 | and you can overlay them on top of base maps of those web mapping applications.
|
|---|
| 122 |
|
|---|
| 123 | Pixel and tile coordinates are in TMS notation (origin [0,0] in bottom-left).
|
|---|
| 124 |
|
|---|
| 125 | What coordinate conversions do we need for TMS Global Mercator tiles::
|
|---|
| 126 |
|
|---|
| 127 | LatLon <-> Meters <-> Pixels <-> Tile
|
|---|
| 128 |
|
|---|
| 129 | WGS84 coordinates Spherical Mercator Pixels in pyramid Tiles in pyramid
|
|---|
| 130 | lat/lon XY in meters XY pixels Z zoom XYZ from TMS
|
|---|
| 131 | EPSG:4326 EPSG:387
|
|---|
| 132 | .----. --------- -- TMS
|
|---|
| 133 | / \ <-> | | <-> /----/ <-> Google
|
|---|
| 134 | \ / | | /--------/ QuadTree
|
|---|
| 135 | ----- --------- /------------/
|
|---|
| 136 | KML, public WebMapService Web Clients TileMapService
|
|---|
| 137 |
|
|---|
| 138 | What is the coordinate extent of Earth in EPSG:3857?
|
|---|
| 139 |
|
|---|
| 140 | [-20037508.342789244, -20037508.342789244, 20037508.342789244, 20037508.342789244]
|
|---|
| 141 | Constant 20037508.342789244 comes from the circumference of the Earth in meters,
|
|---|
| 142 | which is 40 thousand kilometers, the coordinate origin is in the middle of extent.
|
|---|
| 143 | In fact you can calculate the constant as: 2 * math.pi * 6378137 / 2.0
|
|---|
| 144 | $ echo 180 85 | gdaltransform -s_srs EPSG:4326 -t_srs EPSG:3857
|
|---|
| 145 | Polar areas with abs(latitude) bigger then 85.05112878 are clipped off.
|
|---|
| 146 |
|
|---|
| 147 | What are zoom level constants (pixels/meter) for pyramid with EPSG:3857?
|
|---|
| 148 |
|
|---|
| 149 | whole region is on top of pyramid (zoom=0) covered by 256x256 pixels tile,
|
|---|
| 150 | every lower zoom level resolution is always divided by two
|
|---|
| 151 | initialResolution = 20037508.342789244 * 2 / 256 = 156543.03392804062
|
|---|
| 152 |
|
|---|
| 153 | What is the difference between TMS and Google Maps/QuadTree tile name convention?
|
|---|
| 154 |
|
|---|
| 155 | The tile raster itself is the same (equal extent, projection, pixel size),
|
|---|
| 156 | there is just different identification of the same raster tile.
|
|---|
| 157 | Tiles in TMS are counted from [0,0] in the bottom-left corner, id is XYZ.
|
|---|
| 158 | Google placed the origin [0,0] to the top-left corner, reference is XYZ.
|
|---|
| 159 | Microsoft is referencing tiles by a QuadTree name, defined on the website:
|
|---|
| 160 | http://msdn2.microsoft.com/en-us/library/bb259689.aspx
|
|---|
| 161 |
|
|---|
| 162 | The lat/lon coordinates are using WGS84 datum, yes?
|
|---|
| 163 |
|
|---|
| 164 | Yes, all lat/lon we are mentioning should use WGS84 Geodetic Datum.
|
|---|
| 165 | Well, the web clients like Google Maps are projecting those coordinates by
|
|---|
| 166 | Spherical Mercator, so in fact lat/lon coordinates on sphere are treated as if
|
|---|
| 167 | the were on the WGS84 ellipsoid.
|
|---|
| 168 |
|
|---|
| 169 | From MSDN documentation:
|
|---|
| 170 | To simplify the calculations, we use the spherical form of projection, not
|
|---|
| 171 | the ellipsoidal form. Since the projection is used only for map display,
|
|---|
| 172 | and not for displaying numeric coordinates, we don't need the extra precision
|
|---|
| 173 | of an ellipsoidal projection. The spherical projection causes approximately
|
|---|
| 174 | 0.33 percent scale distortion in the Y direction, which is not visually
|
|---|
| 175 | noticeable.
|
|---|
| 176 |
|
|---|
| 177 | How do I create a raster in EPSG:3857 and convert coordinates with PROJ.4?
|
|---|
| 178 |
|
|---|
| 179 | You can use standard GIS tools like gdalwarp, cs2cs or gdaltransform.
|
|---|
| 180 | All of the tools supports -t_srs 'epsg:3857'.
|
|---|
| 181 |
|
|---|
| 182 | For other GIS programs check the exact definition of the projection:
|
|---|
| 183 | More info at http://spatialreference.org/ref/user/google-projection/
|
|---|
| 184 | The same projection is designated as EPSG:3857. WKT definition is in the
|
|---|
| 185 | official EPSG database.
|
|---|
| 186 |
|
|---|
| 187 | Proj4 Text:
|
|---|
| 188 | +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0
|
|---|
| 189 | +k=1.0 +units=m +nadgrids=@null +no_defs
|
|---|
| 190 |
|
|---|
| 191 | Human readable WKT format of EPSG:3857:
|
|---|
| 192 | PROJCS["Google Maps Global Mercator",
|
|---|
| 193 | GEOGCS["WGS 84",
|
|---|
| 194 | DATUM["WGS_1984",
|
|---|
| 195 | SPHEROID["WGS 84",6378137,298.257223563,
|
|---|
| 196 | AUTHORITY["EPSG","7030"]],
|
|---|
| 197 | AUTHORITY["EPSG","6326"]],
|
|---|
| 198 | PRIMEM["Greenwich",0],
|
|---|
| 199 | UNIT["degree",0.0174532925199433],
|
|---|
| 200 | AUTHORITY["EPSG","4326"]],
|
|---|
| 201 | PROJECTION["Mercator_1SP"],
|
|---|
| 202 | PARAMETER["central_meridian",0],
|
|---|
| 203 | PARAMETER["scale_factor",1],
|
|---|
| 204 | PARAMETER["false_easting",0],
|
|---|
| 205 | PARAMETER["false_northing",0],
|
|---|
| 206 | UNIT["metre",1,
|
|---|
| 207 | AUTHORITY["EPSG","9001"]]]
|
|---|
| 208 | """
|
|---|
| 209 |
|
|---|
| 210 | def __init__(self, tile_size=256):
|
|---|
| 211 | "Initialize the TMS Global Mercator pyramid"
|
|---|
| 212 | self.tile_size = tile_size
|
|---|
| 213 | self.initialResolution = 2 * math.pi * 6378137 / self.tile_size
|
|---|
| 214 | # 156543.03392804062 for tile_size 256 pixels
|
|---|
| 215 | self.originShift = 2 * math.pi * 6378137 / 2.0
|
|---|
| 216 | # 20037508.342789244
|
|---|
| 217 |
|
|---|
| 218 | def LatLonToMeters(self, lat, lon):
|
|---|
| 219 | "Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:3857"
|
|---|
| 220 |
|
|---|
| 221 | mx = lon * self.originShift / 180.0
|
|---|
| 222 | my = math.log(math.tan((90 + lat) * math.pi / 360.0)) / (math.pi / 180.0)
|
|---|
| 223 |
|
|---|
| 224 | my = my * self.originShift / 180.0
|
|---|
| 225 | return mx, my
|
|---|
| 226 |
|
|---|
| 227 | def MetersToLatLon(self, mx, my):
|
|---|
| 228 | "Converts XY point from Spherical Mercator EPSG:3857 to lat/lon in WGS84 Datum"
|
|---|
| 229 |
|
|---|
| 230 | lon = (mx / self.originShift) * 180.0
|
|---|
| 231 | lat = (my / self.originShift) * 180.0
|
|---|
| 232 |
|
|---|
| 233 | lat = 180 / math.pi * (2 * math.atan(math.exp(lat * math.pi / 180.0)) - math.pi / 2.0)
|
|---|
| 234 | return lat, lon
|
|---|
| 235 |
|
|---|
| 236 | def PixelsToMeters(self, px, py, zoom):
|
|---|
| 237 | "Converts pixel coordinates in given zoom level of pyramid to EPSG:3857"
|
|---|
| 238 |
|
|---|
| 239 | res = self.Resolution(zoom)
|
|---|
| 240 | mx = px * res - self.originShift
|
|---|
| 241 | my = py * res - self.originShift
|
|---|
| 242 | return mx, my
|
|---|
| 243 |
|
|---|
| 244 | def MetersToPixels(self, mx, my, zoom):
|
|---|
| 245 | "Converts EPSG:3857 to pyramid pixel coordinates in given zoom level"
|
|---|
| 246 |
|
|---|
| 247 | res = self.Resolution(zoom)
|
|---|
| 248 | px = (mx + self.originShift) / res
|
|---|
| 249 | py = (my + self.originShift) / res
|
|---|
| 250 | return px, py
|
|---|
| 251 |
|
|---|
| 252 | def PixelsToTile(self, px, py):
|
|---|
| 253 | "Returns a tile covering region in given pixel coordinates"
|
|---|
| 254 |
|
|---|
| 255 | tx = int(math.ceil(px / float(self.tile_size)) - 1)
|
|---|
| 256 | ty = int(math.ceil(py / float(self.tile_size)) - 1)
|
|---|
| 257 | return tx, ty
|
|---|
| 258 |
|
|---|
| 259 | def PixelsToRaster(self, px, py, zoom):
|
|---|
| 260 | "Move the origin of pixel coordinates to top-left corner"
|
|---|
| 261 |
|
|---|
| 262 | mapSize = self.tile_size << zoom
|
|---|
| 263 | return px, mapSize - py
|
|---|
| 264 |
|
|---|
| 265 | def MetersToTile(self, mx, my, zoom):
|
|---|
| 266 | "Returns tile for given mercator coordinates"
|
|---|
| 267 |
|
|---|
| 268 | px, py = self.MetersToPixels(mx, my, zoom)
|
|---|
| 269 | return self.PixelsToTile(px, py)
|
|---|
| 270 |
|
|---|
| 271 | def TileBounds(self, tx, ty, zoom):
|
|---|
| 272 | "Returns bounds of the given tile in EPSG:3857 coordinates"
|
|---|
| 273 |
|
|---|
| 274 | minx, miny = self.PixelsToMeters(tx * self.tile_size, ty * self.tile_size, zoom)
|
|---|
| 275 | maxx, maxy = self.PixelsToMeters((tx + 1) * self.tile_size, (ty + 1) * self.tile_size, zoom)
|
|---|
| 276 | return (minx, miny, maxx, maxy)
|
|---|
| 277 |
|
|---|
| 278 | def TileLatLonBounds(self, tx, ty, zoom):
|
|---|
| 279 | "Returns bounds of the given tile in latitude/longitude using WGS84 datum"
|
|---|
| 280 |
|
|---|
| 281 | bounds = self.TileBounds(tx, ty, zoom)
|
|---|
| 282 | minLat, minLon = self.MetersToLatLon(bounds[0], bounds[1])
|
|---|
| 283 | maxLat, maxLon = self.MetersToLatLon(bounds[2], bounds[3])
|
|---|
| 284 |
|
|---|
| 285 | return (minLat, minLon, maxLat, maxLon)
|
|---|
| 286 |
|
|---|
| 287 | def Resolution(self, zoom):
|
|---|
| 288 | "Resolution (meters/pixel) for given zoom level (measured at Equator)"
|
|---|
| 289 |
|
|---|
| 290 | # return (2 * math.pi * 6378137) / (self.tile_size * 2**zoom)
|
|---|
| 291 | return self.initialResolution / (2**zoom)
|
|---|
| 292 |
|
|---|
| 293 | def ZoomForPixelSize(self, pixelSize):
|
|---|
| 294 | "Maximal scaledown zoom of the pyramid closest to the pixelSize."
|
|---|
| 295 |
|
|---|
| 296 | for i in range(MAXZOOMLEVEL):
|
|---|
| 297 | if pixelSize > self.Resolution(i):
|
|---|
| 298 | return max(0, i - 1) # We don't want to scale up
|
|---|
| 299 | return MAXZOOMLEVEL - 1
|
|---|
| 300 |
|
|---|
| 301 | def GoogleTile(self, tx, ty, zoom):
|
|---|
| 302 | "Converts TMS tile coordinates to Google Tile coordinates"
|
|---|
| 303 |
|
|---|
| 304 | # coordinate origin is moved from bottom-left to top-left corner of the extent
|
|---|
| 305 | return tx, (2**zoom - 1) - ty
|
|---|
| 306 |
|
|---|
| 307 | def QuadTree(self, tx, ty, zoom):
|
|---|
| 308 | "Converts TMS tile coordinates to Microsoft QuadTree"
|
|---|
| 309 |
|
|---|
| 310 | quadKey = ""
|
|---|
| 311 | ty = (2**zoom - 1) - ty
|
|---|
| 312 | for i in range(zoom, 0, -1):
|
|---|
| 313 | digit = 0
|
|---|
| 314 | mask = 1 << (i - 1)
|
|---|
| 315 | if (tx & mask) != 0:
|
|---|
| 316 | digit += 1
|
|---|
| 317 | if (ty & mask) != 0:
|
|---|
| 318 | digit += 2
|
|---|
| 319 | quadKey += str(digit)
|
|---|
| 320 |
|
|---|
| 321 | return quadKey
|
|---|
| 322 |
|
|---|
| 323 |
|
|---|
| 324 | class GlobalGeodetic(object):
|
|---|
| 325 | r"""
|
|---|
| 326 | TMS Global Geodetic Profile
|
|---|
| 327 | ---------------------------
|
|---|
| 328 |
|
|---|
| 329 | Functions necessary for generation of global tiles in Plate Carre projection,
|
|---|
| 330 | EPSG:4326, "unprojected profile".
|
|---|
| 331 |
|
|---|
| 332 | Such tiles are compatible with Google Earth (as any other EPSG:4326 rasters)
|
|---|
| 333 | and you can overlay the tiles on top of OpenLayers base map.
|
|---|
| 334 |
|
|---|
| 335 | Pixel and tile coordinates are in TMS notation (origin [0,0] in bottom-left).
|
|---|
| 336 |
|
|---|
| 337 | What coordinate conversions do we need for TMS Global Geodetic tiles?
|
|---|
| 338 |
|
|---|
| 339 | Global Geodetic tiles are using geodetic coordinates (latitude,longitude)
|
|---|
| 340 | directly as planar coordinates XY (it is also called Unprojected or Plate
|
|---|
| 341 | Carre). We need only scaling to pixel pyramid and cutting to tiles.
|
|---|
| 342 | Pyramid has on top level two tiles, so it is not square but rectangle.
|
|---|
| 343 | Area [-180,-90,180,90] is scaled to 512x256 pixels.
|
|---|
| 344 | TMS has coordinate origin (for pixels and tiles) in bottom-left corner.
|
|---|
| 345 | Rasters are in EPSG:4326 and therefore are compatible with Google Earth.
|
|---|
| 346 |
|
|---|
| 347 | LatLon <-> Pixels <-> Tiles
|
|---|
| 348 |
|
|---|
| 349 | WGS84 coordinates Pixels in pyramid Tiles in pyramid
|
|---|
| 350 | lat/lon XY pixels Z zoom XYZ from TMS
|
|---|
| 351 | EPSG:4326
|
|---|
| 352 | .----. ----
|
|---|
| 353 | / \ <-> /--------/ <-> TMS
|
|---|
| 354 | \ / /--------------/
|
|---|
| 355 | ----- /--------------------/
|
|---|
| 356 | WMS, KML Web Clients, Google Earth TileMapService
|
|---|
| 357 | """
|
|---|
| 358 |
|
|---|
| 359 | def __init__(self, tmscompatible, tile_size=256):
|
|---|
| 360 | self.tile_size = tile_size
|
|---|
| 361 | if tmscompatible is not None:
|
|---|
| 362 | # Defaults the resolution factor to 0.703125 (2 tiles @ level 0)
|
|---|
| 363 | # Adhers to OSGeo TMS spec
|
|---|
| 364 | # http://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic
|
|---|
| 365 | self.resFact = 180.0 / self.tile_size
|
|---|
| 366 | else:
|
|---|
| 367 | # Defaults the resolution factor to 1.40625 (1 tile @ level 0)
|
|---|
| 368 | # Adheres OpenLayers, MapProxy, etc default resolution for WMTS
|
|---|
| 369 | self.resFact = 360.0 / self.tile_size
|
|---|
| 370 |
|
|---|
| 371 | def LonLatToPixels(self, lon, lat, zoom):
|
|---|
| 372 | "Converts lon/lat to pixel coordinates in given zoom of the EPSG:4326 pyramid"
|
|---|
| 373 |
|
|---|
| 374 | res = self.resFact / 2**zoom
|
|---|
| 375 | px = (180 + lon) / res
|
|---|
| 376 | py = (90 + lat) / res
|
|---|
| 377 | return px, py
|
|---|
| 378 |
|
|---|
| 379 | def PixelsToTile(self, px, py):
|
|---|
| 380 | "Returns coordinates of the tile covering region in pixel coordinates"
|
|---|
| 381 |
|
|---|
| 382 | tx = int(math.ceil(px / float(self.tile_size)) - 1)
|
|---|
| 383 | ty = int(math.ceil(py / float(self.tile_size)) - 1)
|
|---|
| 384 | return tx, ty
|
|---|
| 385 |
|
|---|
| 386 | def LonLatToTile(self, lon, lat, zoom):
|
|---|
| 387 | "Returns the tile for zoom which covers given lon/lat coordinates"
|
|---|
| 388 |
|
|---|
| 389 | px, py = self.LonLatToPixels(lon, lat, zoom)
|
|---|
| 390 | return self.PixelsToTile(px, py)
|
|---|
| 391 |
|
|---|
| 392 | def Resolution(self, zoom):
|
|---|
| 393 | "Resolution (arc/pixel) for given zoom level (measured at Equator)"
|
|---|
| 394 |
|
|---|
| 395 | return self.resFact / 2**zoom
|
|---|
| 396 |
|
|---|
| 397 | def ZoomForPixelSize(self, pixelSize):
|
|---|
| 398 | "Maximal scaledown zoom of the pyramid closest to the pixelSize."
|
|---|
| 399 |
|
|---|
| 400 | for i in range(MAXZOOMLEVEL):
|
|---|
| 401 | if pixelSize > self.Resolution(i):
|
|---|
| 402 | return max(0, i - 1) # We don't want to scale up
|
|---|
| 403 | return MAXZOOMLEVEL - 1
|
|---|
| 404 |
|
|---|
| 405 | def TileBounds(self, tx, ty, zoom):
|
|---|
| 406 | "Returns bounds of the given tile"
|
|---|
| 407 | res = self.resFact / 2**zoom
|
|---|
| 408 | return (
|
|---|
| 409 | tx * self.tile_size * res - 180,
|
|---|
| 410 | ty * self.tile_size * res - 90,
|
|---|
| 411 | (tx + 1) * self.tile_size * res - 180,
|
|---|
| 412 | (ty + 1) * self.tile_size * res - 90
|
|---|
| 413 | )
|
|---|
| 414 |
|
|---|
| 415 | def TileLatLonBounds(self, tx, ty, zoom):
|
|---|
| 416 | "Returns bounds of the given tile in the SWNE form"
|
|---|
| 417 | b = self.TileBounds(tx, ty, zoom)
|
|---|
| 418 | return (b[1], b[0], b[3], b[2])
|
|---|
| 419 |
|
|---|
| 420 |
|
|---|
| 421 | class Zoomify(object):
|
|---|
| 422 | """
|
|---|
| 423 | Tiles compatible with the Zoomify viewer
|
|---|
| 424 | ----------------------------------------
|
|---|
| 425 | """
|
|---|
| 426 |
|
|---|
| 427 | def __init__(self, width, height, tile_size=256, tileformat='jpg'):
|
|---|
| 428 | """Initialization of the Zoomify tile tree"""
|
|---|
| 429 |
|
|---|
| 430 | self.tile_size = tile_size
|
|---|
| 431 | self.tileformat = tileformat
|
|---|
| 432 | imagesize = (width, height)
|
|---|
| 433 | tiles = (math.ceil(width / tile_size), math.ceil(height / tile_size))
|
|---|
| 434 |
|
|---|
| 435 | # Size (in tiles) for each tier of pyramid.
|
|---|
| 436 | self.tierSizeInTiles = []
|
|---|
| 437 | self.tierSizeInTiles.append(tiles)
|
|---|
| 438 |
|
|---|
| 439 | # Image size in pixels for each pyramid tierself
|
|---|
| 440 | self.tierImageSize = []
|
|---|
| 441 | self.tierImageSize.append(imagesize)
|
|---|
| 442 |
|
|---|
| 443 | while (imagesize[0] > tile_size or imagesize[1] > tile_size):
|
|---|
| 444 | imagesize = (math.floor(imagesize[0] / 2), math.floor(imagesize[1] / 2))
|
|---|
| 445 | tiles = (math.ceil(imagesize[0] / tile_size), math.ceil(imagesize[1] / tile_size))
|
|---|
| 446 | self.tierSizeInTiles.append(tiles)
|
|---|
| 447 | self.tierImageSize.append(imagesize)
|
|---|
| 448 |
|
|---|
| 449 | self.tierSizeInTiles.reverse()
|
|---|
| 450 | self.tierImageSize.reverse()
|
|---|
| 451 |
|
|---|
| 452 | # Depth of the Zoomify pyramid, number of tiers (zoom levels)
|
|---|
| 453 | self.numberOfTiers = len(self.tierSizeInTiles)
|
|---|
| 454 |
|
|---|
| 455 | # Number of tiles up to the given tier of pyramid.
|
|---|
| 456 | self.tileCountUpToTier = []
|
|---|
| 457 | self.tileCountUpToTier[0] = 0
|
|---|
| 458 | for i in range(1, self.numberOfTiers + 1):
|
|---|
| 459 | self.tileCountUpToTier.append(
|
|---|
| 460 | self.tierSizeInTiles[i - 1][0] * self.tierSizeInTiles[i - 1][1] +
|
|---|
| 461 | self.tileCountUpToTier[i - 1]
|
|---|
| 462 | )
|
|---|
| 463 |
|
|---|
| 464 | def tilefilename(self, x, y, z):
|
|---|
| 465 | """Returns filename for tile with given coordinates"""
|
|---|
| 466 |
|
|---|
| 467 | tileIndex = x + y * self.tierSizeInTiles[z][0] + self.tileCountUpToTier[z]
|
|---|
| 468 | return os.path.join("TileGroup%.0f" % math.floor(tileIndex / 256),
|
|---|
| 469 | "%s-%s-%s.%s" % (z, x, y, self.tileformat))
|
|---|
| 470 |
|
|---|
| 471 |
|
|---|
| 472 | class GDALError(Exception):
|
|---|
| 473 | pass
|
|---|
| 474 |
|
|---|
| 475 |
|
|---|
| 476 | def exit_with_error(message, details=""):
|
|---|
| 477 | # Message printing and exit code kept from the way it worked using the OptionParser (in case
|
|---|
| 478 | # someone parses the error output)
|
|---|
| 479 | sys.stderr.write("Usage: gdal2tiles.py [options] input_file [output]\n\n")
|
|---|
| 480 | sys.stderr.write("gdal2tiles.py: error: %s\n" % message)
|
|---|
| 481 | if details:
|
|---|
| 482 | sys.stderr.write("\n\n%s\n" % details)
|
|---|
| 483 |
|
|---|
| 484 | sys.exit(2)
|
|---|
| 485 |
|
|---|
| 486 |
|
|---|
| 487 | def generate_kml(tx, ty, tz, tileext, tile_size, tileswne, options, children=None, **args):
|
|---|
| 488 | """
|
|---|
| 489 | Template for the KML. Returns filled string.
|
|---|
| 490 | """
|
|---|
| 491 | if not children:
|
|---|
| 492 | children = []
|
|---|
| 493 |
|
|---|
| 494 | args['tx'], args['ty'], args['tz'] = tx, ty, tz
|
|---|
| 495 | args['tileformat'] = tileext
|
|---|
| 496 | if 'tile_size' not in args:
|
|---|
| 497 | args['tile_size'] = tile_size
|
|---|
| 498 |
|
|---|
| 499 | if 'minlodpixels' not in args:
|
|---|
| 500 | args['minlodpixels'] = int(args['tile_size'] / 2)
|
|---|
| 501 | if 'maxlodpixels' not in args:
|
|---|
| 502 | args['maxlodpixels'] = int(args['tile_size'] * 8)
|
|---|
| 503 | if children == []:
|
|---|
| 504 | args['maxlodpixels'] = -1
|
|---|
| 505 |
|
|---|
| 506 | if tx is None:
|
|---|
| 507 | tilekml = False
|
|---|
| 508 | args['title'] = options.title
|
|---|
| 509 | else:
|
|---|
| 510 | tilekml = True
|
|---|
| 511 | args['title'] = "%d/%d/%d.kml" % (tz, tx, ty)
|
|---|
| 512 | args['south'], args['west'], args['north'], args['east'] = tileswne(tx, ty, tz)
|
|---|
| 513 |
|
|---|
| 514 | if tx == 0:
|
|---|
| 515 | args['drawOrder'] = 2 * tz + 1
|
|---|
| 516 | elif tx is not None:
|
|---|
| 517 | args['drawOrder'] = 2 * tz
|
|---|
| 518 | else:
|
|---|
| 519 | args['drawOrder'] = 0
|
|---|
| 520 |
|
|---|
| 521 | url = options.url
|
|---|
| 522 | if not url:
|
|---|
| 523 | if tilekml:
|
|---|
| 524 | url = "../../"
|
|---|
| 525 | else:
|
|---|
| 526 | url = ""
|
|---|
| 527 |
|
|---|
| 528 | s = """<?xml version="1.0" encoding="utf-8"?>
|
|---|
| 529 | <kml xmlns="http://www.opengis.net/kml/2.2">
|
|---|
| 530 | <Document>
|
|---|
| 531 | <name>%(title)s</name>
|
|---|
| 532 | <description></description>
|
|---|
| 533 | <Style>
|
|---|
| 534 | <ListStyle id="hideChildren">
|
|---|
| 535 | <listItemType>checkHideChildren</listItemType>
|
|---|
| 536 | </ListStyle>
|
|---|
| 537 | </Style>""" % args
|
|---|
| 538 | if tilekml:
|
|---|
| 539 | s += """
|
|---|
| 540 | <Region>
|
|---|
| 541 | <LatLonAltBox>
|
|---|
| 542 | <north>%(north).14f</north>
|
|---|
| 543 | <south>%(south).14f</south>
|
|---|
| 544 | <east>%(east).14f</east>
|
|---|
| 545 | <west>%(west).14f</west>
|
|---|
| 546 | </LatLonAltBox>
|
|---|
| 547 | <Lod>
|
|---|
| 548 | <minLodPixels>%(minlodpixels)d</minLodPixels>
|
|---|
| 549 | <maxLodPixels>%(maxlodpixels)d</maxLodPixels>
|
|---|
| 550 | </Lod>
|
|---|
| 551 | </Region>
|
|---|
| 552 | <GroundOverlay>
|
|---|
| 553 | <drawOrder>%(drawOrder)d</drawOrder>
|
|---|
| 554 | <Icon>
|
|---|
| 555 | <href>%(ty)d.%(tileformat)s</href>
|
|---|
| 556 | </Icon>
|
|---|
| 557 | <LatLonBox>
|
|---|
| 558 | <north>%(north).14f</north>
|
|---|
| 559 | <south>%(south).14f</south>
|
|---|
| 560 | <east>%(east).14f</east>
|
|---|
| 561 | <west>%(west).14f</west>
|
|---|
| 562 | </LatLonBox>
|
|---|
| 563 | </GroundOverlay>
|
|---|
| 564 | """ % args
|
|---|
| 565 |
|
|---|
| 566 | for cx, cy, cz in children:
|
|---|
| 567 | csouth, cwest, cnorth, ceast = tileswne(cx, cy, cz)
|
|---|
| 568 | s += """
|
|---|
| 569 | <NetworkLink>
|
|---|
| 570 | <name>%d/%d/%d.%s</name>
|
|---|
| 571 | <Region>
|
|---|
| 572 | <LatLonAltBox>
|
|---|
| 573 | <north>%.14f</north>
|
|---|
| 574 | <south>%.14f</south>
|
|---|
| 575 | <east>%.14f</east>
|
|---|
| 576 | <west>%.14f</west>
|
|---|
| 577 | </LatLonAltBox>
|
|---|
| 578 | <Lod>
|
|---|
| 579 | <minLodPixels>%d</minLodPixels>
|
|---|
| 580 | <maxLodPixels>-1</maxLodPixels>
|
|---|
| 581 | </Lod>
|
|---|
| 582 | </Region>
|
|---|
| 583 | <Link>
|
|---|
| 584 | <href>%s%d/%d/%d.kml</href>
|
|---|
| 585 | <viewRefreshMode>onRegion</viewRefreshMode>
|
|---|
| 586 | <viewFormat/>
|
|---|
| 587 | </Link>
|
|---|
| 588 | </NetworkLink>
|
|---|
| 589 | """ % (cz, cx, cy, args['tileformat'], cnorth, csouth, ceast, cwest,
|
|---|
| 590 | args['minlodpixels'], url, cz, cx, cy)
|
|---|
| 591 |
|
|---|
| 592 | s += """ </Document>
|
|---|
| 593 | </kml>
|
|---|
| 594 | """
|
|---|
| 595 | return s
|
|---|
| 596 |
|
|---|
| 597 |
|
|---|
| 598 | def scale_query_to_tile(dsquery, dstile, tiledriver, options, tilefilename=''):
|
|---|
| 599 | """Scales down query dataset to the tile dataset"""
|
|---|
| 600 |
|
|---|
| 601 | querysize = dsquery.RasterXSize
|
|---|
| 602 | tile_size = dstile.RasterXSize
|
|---|
| 603 | tilebands = dstile.RasterCount
|
|---|
| 604 |
|
|---|
| 605 | if options.resampling == 'average':
|
|---|
| 606 |
|
|---|
| 607 | # Function: gdal.RegenerateOverview()
|
|---|
| 608 | for i in range(1, tilebands + 1):
|
|---|
| 609 | # Black border around NODATA
|
|---|
| 610 | res = gdal.RegenerateOverview(dsquery.GetRasterBand(i), dstile.GetRasterBand(i),
|
|---|
| 611 | 'average')
|
|---|
| 612 | if res != 0:
|
|---|
| 613 | exit_with_error("RegenerateOverview() failed on %s, error %d" % (
|
|---|
| 614 | tilefilename, res))
|
|---|
| 615 |
|
|---|
| 616 | elif options.resampling == 'antialias' and numpy_available:
|
|---|
| 617 |
|
|---|
| 618 | # Scaling by PIL (Python Imaging Library) - improved Lanczos
|
|---|
| 619 | array = numpy.zeros((querysize, querysize, tilebands), numpy.uint8)
|
|---|
| 620 | for i in range(tilebands):
|
|---|
| 621 | array[:, :, i] = gdalarray.BandReadAsArray(dsquery.GetRasterBand(i + 1),
|
|---|
| 622 | 0, 0, querysize, querysize)
|
|---|
| 623 | im = Image.fromarray(array, 'RGBA') # Always four bands
|
|---|
| 624 | im1 = im.resize((tile_size, tile_size), Image.ANTIALIAS)
|
|---|
| 625 | if os.path.exists(tilefilename):
|
|---|
| 626 | im0 = Image.open(tilefilename)
|
|---|
| 627 | im1 = Image.composite(im1, im0, im1)
|
|---|
| 628 | im1.save(tilefilename, tiledriver)
|
|---|
| 629 |
|
|---|
| 630 | else:
|
|---|
| 631 |
|
|---|
| 632 | if options.resampling == 'near':
|
|---|
| 633 | gdal_resampling = gdal.GRA_NearestNeighbour
|
|---|
| 634 |
|
|---|
| 635 | elif options.resampling == 'bilinear':
|
|---|
| 636 | gdal_resampling = gdal.GRA_Bilinear
|
|---|
| 637 |
|
|---|
| 638 | elif options.resampling == 'cubic':
|
|---|
| 639 | gdal_resampling = gdal.GRA_Cubic
|
|---|
| 640 |
|
|---|
| 641 | elif options.resampling == 'cubicspline':
|
|---|
| 642 | gdal_resampling = gdal.GRA_CubicSpline
|
|---|
| 643 |
|
|---|
| 644 | elif options.resampling == 'lanczos':
|
|---|
| 645 | gdal_resampling = gdal.GRA_Lanczos
|
|---|
| 646 |
|
|---|
| 647 | # Other algorithms are implemented by gdal.ReprojectImage().
|
|---|
| 648 | dsquery.SetGeoTransform((0.0, tile_size / float(querysize), 0.0, 0.0, 0.0,
|
|---|
| 649 | tile_size / float(querysize)))
|
|---|
| 650 | dstile.SetGeoTransform((0.0, 1.0, 0.0, 0.0, 0.0, 1.0))
|
|---|
| 651 |
|
|---|
| 652 | res = gdal.ReprojectImage(dsquery, dstile, None, None, gdal_resampling)
|
|---|
| 653 | if res != 0:
|
|---|
| 654 | exit_with_error("ReprojectImage() failed on %s, error %d" % (tilefilename, res))
|
|---|
| 655 |
|
|---|
| 656 |
|
|---|
| 657 | def setup_no_data_values(input_dataset, options):
|
|---|
| 658 | """
|
|---|
| 659 | Extract the NODATA values from the dataset or use the passed arguments as override if any
|
|---|
| 660 | """
|
|---|
| 661 | in_nodata = []
|
|---|
| 662 | if options.srcnodata:
|
|---|
| 663 | nds = list(map(float, options.srcnodata.split(',')))
|
|---|
| 664 | if len(nds) < input_dataset.RasterCount:
|
|---|
| 665 | in_nodata = (nds * input_dataset.RasterCount)[:input_dataset.RasterCount]
|
|---|
| 666 | else:
|
|---|
| 667 | in_nodata = nds
|
|---|
| 668 | else:
|
|---|
| 669 | for i in range(1, input_dataset.RasterCount + 1):
|
|---|
| 670 | raster_no_data = input_dataset.GetRasterBand(i).GetNoDataValue()
|
|---|
| 671 | if raster_no_data is not None:
|
|---|
| 672 | in_nodata.append(raster_no_data)
|
|---|
| 673 |
|
|---|
| 674 | if options.verbose:
|
|---|
| 675 | print("NODATA: %s" % in_nodata)
|
|---|
| 676 |
|
|---|
| 677 | return in_nodata
|
|---|
| 678 |
|
|---|
| 679 |
|
|---|
| 680 | def setup_input_srs(input_dataset, options):
|
|---|
| 681 | """
|
|---|
| 682 | Determines and returns the Input Spatial Reference System (SRS) as an osr object and as a
|
|---|
| 683 | WKT representation
|
|---|
| 684 |
|
|---|
| 685 | Uses in priority the one passed in the command line arguments. If None, tries to extract them
|
|---|
| 686 | from the input dataset
|
|---|
| 687 | """
|
|---|
| 688 |
|
|---|
| 689 | input_srs = None
|
|---|
| 690 | input_srs_wkt = None
|
|---|
| 691 |
|
|---|
| 692 | if options.s_srs:
|
|---|
| 693 | input_srs = osr.SpatialReference()
|
|---|
| 694 | input_srs.SetFromUserInput(options.s_srs)
|
|---|
| 695 | input_srs_wkt = input_srs.ExportToWkt()
|
|---|
| 696 | else:
|
|---|
| 697 | input_srs_wkt = input_dataset.GetProjection()
|
|---|
| 698 | if not input_srs_wkt and input_dataset.GetGCPCount() != 0:
|
|---|
| 699 | input_srs_wkt = input_dataset.GetGCPProjection()
|
|---|
| 700 | if input_srs_wkt:
|
|---|
| 701 | input_srs = osr.SpatialReference()
|
|---|
| 702 | input_srs.ImportFromWkt(input_srs_wkt)
|
|---|
| 703 |
|
|---|
| 704 | return input_srs, input_srs_wkt
|
|---|
| 705 |
|
|---|
| 706 |
|
|---|
| 707 | def setup_output_srs(input_srs, options):
|
|---|
| 708 | """
|
|---|
| 709 | Setup the desired SRS (based on options)
|
|---|
| 710 | """
|
|---|
| 711 | output_srs = osr.SpatialReference()
|
|---|
| 712 |
|
|---|
| 713 | if options.profile == 'mercator':
|
|---|
| 714 | output_srs.ImportFromEPSG(3857)
|
|---|
| 715 | elif options.profile == 'geodetic':
|
|---|
| 716 | output_srs.ImportFromEPSG(4326)
|
|---|
| 717 | else:
|
|---|
| 718 | output_srs = input_srs
|
|---|
| 719 |
|
|---|
| 720 | return output_srs
|
|---|
| 721 |
|
|---|
| 722 |
|
|---|
| 723 | def has_georeference(dataset):
|
|---|
| 724 | return (dataset.GetGeoTransform() != (0.0, 1.0, 0.0, 0.0, 0.0, 1.0) or
|
|---|
| 725 | dataset.GetGCPCount() != 0)
|
|---|
| 726 |
|
|---|
| 727 |
|
|---|
| 728 | def reproject_dataset(from_dataset, from_srs, to_srs, options=None):
|
|---|
| 729 | """
|
|---|
| 730 | Returns the input dataset in the expected "destination" SRS.
|
|---|
| 731 | If the dataset is already in the correct SRS, returns it unmodified
|
|---|
| 732 | """
|
|---|
| 733 | if not from_srs or not to_srs:
|
|---|
| 734 | raise GDALError("from and to SRS must be defined to reproject the dataset")
|
|---|
| 735 |
|
|---|
| 736 | if (from_srs.ExportToProj4() != to_srs.ExportToProj4()) or (from_dataset.GetGCPCount() != 0):
|
|---|
| 737 | to_dataset = gdal.AutoCreateWarpedVRT(from_dataset,
|
|---|
| 738 | from_srs.ExportToWkt(), to_srs.ExportToWkt())
|
|---|
| 739 |
|
|---|
| 740 | if options and options.verbose:
|
|---|
| 741 | print("Warping of the raster by AutoCreateWarpedVRT (result saved into 'tiles.vrt')")
|
|---|
| 742 | to_dataset.GetDriver().CreateCopy("tiles.vrt", to_dataset)
|
|---|
| 743 |
|
|---|
| 744 | return to_dataset
|
|---|
| 745 | else:
|
|---|
| 746 | return from_dataset
|
|---|
| 747 |
|
|---|
| 748 |
|
|---|
| 749 | def add_gdal_warp_options_to_string(vrt_string, warp_options):
|
|---|
| 750 | if not warp_options:
|
|---|
| 751 | return vrt_string
|
|---|
| 752 |
|
|---|
| 753 | vrt_root = ElementTree.fromstring(vrt_string)
|
|---|
| 754 | options = vrt_root.find("GDALWarpOptions")
|
|---|
| 755 |
|
|---|
| 756 | if options is None:
|
|---|
| 757 | return vrt_string
|
|---|
| 758 |
|
|---|
| 759 | for key, value in warp_options.items():
|
|---|
| 760 | tb = ElementTree.TreeBuilder()
|
|---|
| 761 | tb.start("Option", {"name": key})
|
|---|
| 762 | tb.data(value)
|
|---|
| 763 | tb.end("Option")
|
|---|
| 764 | elem = tb.close()
|
|---|
| 765 | options.insert(0, elem)
|
|---|
| 766 |
|
|---|
| 767 | return ElementTree.tostring(vrt_root).decode()
|
|---|
| 768 |
|
|---|
| 769 |
|
|---|
| 770 | def update_no_data_values(warped_vrt_dataset, nodata_values, options=None):
|
|---|
| 771 | """
|
|---|
| 772 | Takes an array of NODATA values and forces them on the WarpedVRT file dataset passed
|
|---|
| 773 | """
|
|---|
| 774 | # TODO: gbataille - Seems that I forgot tests there
|
|---|
| 775 | assert nodata_values != []
|
|---|
| 776 |
|
|---|
| 777 | vrt_string = warped_vrt_dataset.GetMetadata("xml:VRT")[0]
|
|---|
| 778 |
|
|---|
| 779 | vrt_string = add_gdal_warp_options_to_string(
|
|---|
| 780 | vrt_string, {"INIT_DEST": "NO_DATA", "UNIFIED_SRC_NODATA": "YES"})
|
|---|
| 781 |
|
|---|
| 782 | # TODO: gbataille - check the need for this replacement. Seems to work without
|
|---|
| 783 | # # replace BandMapping tag for NODATA bands....
|
|---|
| 784 | # for i in range(len(nodata_values)):
|
|---|
| 785 | # s = s.replace(
|
|---|
| 786 | # '<BandMapping src="%i" dst="%i"/>' % ((i+1), (i+1)),
|
|---|
| 787 | # """
|
|---|
| 788 | # <BandMapping src="%i" dst="%i">
|
|---|
| 789 | # <SrcNoDataReal>%i</SrcNoDataReal>
|
|---|
| 790 | # <SrcNoDataImag>0</SrcNoDataImag>
|
|---|
| 791 | # <DstNoDataReal>%i</DstNoDataReal>
|
|---|
| 792 | # <DstNoDataImag>0</DstNoDataImag>
|
|---|
| 793 | # </BandMapping>
|
|---|
| 794 | # """ % ((i+1), (i+1), nodata_values[i], nodata_values[i]))
|
|---|
| 795 |
|
|---|
| 796 | corrected_dataset = gdal.Open(vrt_string)
|
|---|
| 797 |
|
|---|
| 798 | # set NODATA_VALUE metadata
|
|---|
| 799 | corrected_dataset.SetMetadataItem(
|
|---|
| 800 | 'NODATA_VALUES', ' '.join([str(i) for i in nodata_values]))
|
|---|
| 801 |
|
|---|
| 802 | if options and options.verbose:
|
|---|
| 803 | print("Modified warping result saved into 'tiles1.vrt'")
|
|---|
| 804 |
|
|---|
| 805 | with open("tiles1.vrt", "w") as f:
|
|---|
| 806 | f.write(corrected_dataset.GetMetadata("xml:VRT")[0])
|
|---|
| 807 |
|
|---|
| 808 | return corrected_dataset
|
|---|
| 809 |
|
|---|
| 810 |
|
|---|
| 811 | def add_alpha_band_to_string_vrt(vrt_string):
|
|---|
| 812 | # TODO: gbataille - Old code speak of this being equivalent to gdalwarp -dstalpha
|
|---|
| 813 | # To be checked
|
|---|
| 814 |
|
|---|
| 815 | vrt_root = ElementTree.fromstring(vrt_string)
|
|---|
| 816 |
|
|---|
| 817 | index = 0
|
|---|
| 818 | nb_bands = 0
|
|---|
| 819 | for subelem in list(vrt_root):
|
|---|
| 820 | if subelem.tag == "VRTRasterBand":
|
|---|
| 821 | nb_bands += 1
|
|---|
| 822 | color_node = subelem.find("./ColorInterp")
|
|---|
| 823 | if color_node is not None and color_node.text == "Alpha":
|
|---|
| 824 | raise Exception("Alpha band already present")
|
|---|
| 825 | else:
|
|---|
| 826 | if nb_bands:
|
|---|
| 827 | # This means that we are one element after the Band definitions
|
|---|
| 828 | break
|
|---|
| 829 |
|
|---|
| 830 | index += 1
|
|---|
| 831 |
|
|---|
| 832 | tb = ElementTree.TreeBuilder()
|
|---|
| 833 | tb.start("VRTRasterBand",
|
|---|
| 834 | {'dataType': "Byte", "band": str(nb_bands + 1), "subClass": "VRTWarpedRasterBand"})
|
|---|
| 835 | tb.start("ColorInterp", {})
|
|---|
| 836 | tb.data("Alpha")
|
|---|
| 837 | tb.end("ColorInterp")
|
|---|
| 838 | tb.end("VRTRasterBand")
|
|---|
| 839 | elem = tb.close()
|
|---|
| 840 |
|
|---|
| 841 | vrt_root.insert(index, elem)
|
|---|
| 842 |
|
|---|
| 843 | warp_options = vrt_root.find(".//GDALWarpOptions")
|
|---|
| 844 | tb = ElementTree.TreeBuilder()
|
|---|
| 845 | tb.start("DstAlphaBand", {})
|
|---|
| 846 | tb.data(str(nb_bands + 1))
|
|---|
| 847 | tb.end("DstAlphaBand")
|
|---|
| 848 | elem = tb.close()
|
|---|
| 849 | warp_options.append(elem)
|
|---|
| 850 |
|
|---|
| 851 | # TODO: gbataille - this is a GDALWarpOptions. Why put it in a specific place?
|
|---|
| 852 | tb = ElementTree.TreeBuilder()
|
|---|
| 853 | tb.start("Option", {"name": "INIT_DEST"})
|
|---|
| 854 | tb.data("0")
|
|---|
| 855 | tb.end("Option")
|
|---|
| 856 | elem = tb.close()
|
|---|
| 857 | warp_options.append(elem)
|
|---|
| 858 |
|
|---|
| 859 | return ElementTree.tostring(vrt_root).decode()
|
|---|
| 860 |
|
|---|
| 861 |
|
|---|
| 862 | def update_alpha_value_for_non_alpha_inputs(warped_vrt_dataset, options=None):
|
|---|
| 863 | """
|
|---|
| 864 | Handles dataset with 1 or 3 bands, i.e. without alpha channel, in the case the nodata value has
|
|---|
| 865 | not been forced by options
|
|---|
| 866 | """
|
|---|
| 867 | if warped_vrt_dataset.RasterCount in [1, 3]:
|
|---|
| 868 |
|
|---|
| 869 | vrt_string = warped_vrt_dataset.GetMetadata("xml:VRT")[0]
|
|---|
| 870 |
|
|---|
| 871 | vrt_string = add_alpha_band_to_string_vrt(vrt_string)
|
|---|
| 872 |
|
|---|
| 873 | warped_vrt_dataset = gdal.Open(vrt_string)
|
|---|
| 874 |
|
|---|
| 875 | if options and options.verbose:
|
|---|
| 876 | print("Modified -dstalpha warping result saved into 'tiles1.vrt'")
|
|---|
| 877 |
|
|---|
| 878 | with open("tiles1.vrt", "w") as f:
|
|---|
| 879 | f.write(warped_vrt_dataset.GetMetadata("xml:VRT")[0])
|
|---|
| 880 |
|
|---|
| 881 | return warped_vrt_dataset
|
|---|
| 882 |
|
|---|
| 883 |
|
|---|
| 884 | def nb_data_bands(dataset):
|
|---|
| 885 | """
|
|---|
| 886 | Return the number of data (non-alpha) bands of a gdal dataset
|
|---|
| 887 | """
|
|---|
| 888 | alphaband = dataset.GetRasterBand(1).GetMaskBand()
|
|---|
| 889 | if ((alphaband.GetMaskFlags() & gdal.GMF_ALPHA) or
|
|---|
| 890 | dataset.RasterCount == 4 or
|
|---|
| 891 | dataset.RasterCount == 2):
|
|---|
| 892 | return dataset.RasterCount - 1
|
|---|
| 893 | return dataset.RasterCount
|
|---|
| 894 |
|
|---|
| [b72d9c4] | 895 | def create_base_tile(tile_job_info, tile_detail, queue=None):
|
|---|
| [9f5877d] | 896 |
|
|---|
| 897 | dataBandsCount = tile_job_info.nb_data_bands
|
|---|
| 898 | output = tile_job_info.output_file_path
|
|---|
| 899 | tileext = tile_job_info.tile_extension
|
|---|
| 900 | tile_size = tile_job_info.tile_size
|
|---|
| 901 | options = tile_job_info.options
|
|---|
| 902 |
|
|---|
| 903 | tilebands = dataBandsCount + 1
|
|---|
| 904 |
|
|---|
| 905 | cached_ds = getattr(threadLocal, 'cached_ds', None)
|
|---|
| 906 | if cached_ds and cached_ds.GetDescription() == tile_job_info.src_file:
|
|---|
| 907 | ds = cached_ds
|
|---|
| 908 | else:
|
|---|
| 909 | ds = gdal.Open(tile_job_info.src_file, gdal.GA_ReadOnly)
|
|---|
| 910 | threadLocal.cached_ds = ds
|
|---|
| 911 |
|
|---|
| 912 | mem_drv = gdal.GetDriverByName('MEM')
|
|---|
| 913 | out_drv = gdal.GetDriverByName(tile_job_info.tile_driver)
|
|---|
| 914 | alphaband = ds.GetRasterBand(1).GetMaskBand()
|
|---|
| 915 |
|
|---|
| 916 | tx = tile_detail.tx
|
|---|
| 917 | ty = tile_detail.ty
|
|---|
| 918 | tz = tile_detail.tz
|
|---|
| 919 | rx = tile_detail.rx
|
|---|
| 920 | ry = tile_detail.ry
|
|---|
| 921 | rxsize = tile_detail.rxsize
|
|---|
| 922 | rysize = tile_detail.rysize
|
|---|
| 923 | wx = tile_detail.wx
|
|---|
| 924 | wy = tile_detail.wy
|
|---|
| 925 | wxsize = tile_detail.wxsize
|
|---|
| 926 | wysize = tile_detail.wysize
|
|---|
| 927 | querysize = tile_detail.querysize
|
|---|
| 928 |
|
|---|
| 929 | # Tile dataset in memory
|
|---|
| 930 | tilefilename = os.path.join(
|
|---|
| 931 | output, str(tz), str(tx), "%s.%s" % (ty, tileext))
|
|---|
| 932 | dstile = mem_drv.Create('', tile_size, tile_size, tilebands)
|
|---|
| 933 |
|
|---|
| 934 | data = alpha = None
|
|---|
| 935 |
|
|---|
| 936 | if options.verbose:
|
|---|
| 937 | print("\tReadRaster Extent: ",
|
|---|
| 938 | (rx, ry, rxsize, rysize), (wx, wy, wxsize, wysize))
|
|---|
| 939 |
|
|---|
| 940 | # Query is in 'nearest neighbour' but can be bigger in then the tile_size
|
|---|
| 941 | # We scale down the query to the tile_size by supplied algorithm.
|
|---|
| 942 |
|
|---|
| 943 | if rxsize != 0 and rysize != 0 and wxsize != 0 and wysize != 0:
|
|---|
| 944 | alpha = alphaband.ReadRaster(rx, ry, rxsize, rysize, wxsize, wysize)
|
|---|
| 945 |
|
|---|
| 946 | # Detect totally transparent tile and skip its creation
|
|---|
| 947 | if tile_job_info.exclude_transparent and len(alpha) == alpha.count('\x00'.encode('ascii')):
|
|---|
| 948 | return
|
|---|
| 949 |
|
|---|
| 950 | data = ds.ReadRaster(rx, ry, rxsize, rysize, wxsize, wysize,
|
|---|
| 951 | band_list=list(range(1, dataBandsCount + 1)))
|
|---|
| 952 |
|
|---|
| 953 | # The tile in memory is a transparent file by default. Write pixel values into it if
|
|---|
| 954 | # any
|
|---|
| 955 | if data:
|
|---|
| 956 | if tile_size == querysize:
|
|---|
| 957 | # Use the ReadRaster result directly in tiles ('nearest neighbour' query)
|
|---|
| 958 | dstile.WriteRaster(wx, wy, wxsize, wysize, data,
|
|---|
| 959 | band_list=list(range(1, dataBandsCount + 1)))
|
|---|
| 960 | dstile.WriteRaster(wx, wy, wxsize, wysize, alpha, band_list=[tilebands])
|
|---|
| 961 |
|
|---|
| 962 | # Note: For source drivers based on WaveLet compression (JPEG2000, ECW,
|
|---|
| 963 | # MrSID) the ReadRaster function returns high-quality raster (not ugly
|
|---|
| 964 | # nearest neighbour)
|
|---|
| 965 | # TODO: Use directly 'near' for WaveLet files
|
|---|
| 966 | else:
|
|---|
| 967 | # Big ReadRaster query in memory scaled to the tile_size - all but 'near'
|
|---|
| 968 | # algo
|
|---|
| 969 | dsquery = mem_drv.Create('', querysize, querysize, tilebands)
|
|---|
| 970 | # TODO: fill the null value in case a tile without alpha is produced (now
|
|---|
| 971 | # only png tiles are supported)
|
|---|
| 972 | dsquery.WriteRaster(wx, wy, wxsize, wysize, data,
|
|---|
| 973 | band_list=list(range(1, dataBandsCount + 1)))
|
|---|
| 974 | dsquery.WriteRaster(wx, wy, wxsize, wysize, alpha, band_list=[tilebands])
|
|---|
| 975 |
|
|---|
| 976 | scale_query_to_tile(dsquery, dstile, tile_job_info.tile_driver, options,
|
|---|
| 977 | tilefilename=tilefilename)
|
|---|
| 978 | del dsquery
|
|---|
| 979 |
|
|---|
| 980 | del data
|
|---|
| 981 |
|
|---|
| 982 | if options.resampling != 'antialias':
|
|---|
| 983 | # Write a copy of tile to png/jpg
|
|---|
| 984 | out_drv.CreateCopy(tilefilename, dstile, strict=0)
|
|---|
| 985 |
|
|---|
| 986 | del dstile
|
|---|
| 987 |
|
|---|
| 988 | # Create a KML file for this tile.
|
|---|
| 989 | if tile_job_info.kml:
|
|---|
| 990 | kmlfilename = os.path.join(output, str(tz), str(tx), '%d.kml' % ty)
|
|---|
| 991 | if not options.resume or not os.path.exists(kmlfilename):
|
|---|
| 992 | with open(kmlfilename, 'wb') as f:
|
|---|
| 993 | f.write(generate_kml(
|
|---|
| 994 | tx, ty, tz, tile_job_info.tile_extension, tile_job_info.tile_size,
|
|---|
| 995 | get_tile_swne(tile_job_info, options), tile_job_info.options
|
|---|
| 996 | ).encode('utf-8'))
|
|---|
| 997 |
|
|---|
| [b72d9c4] | 998 | if queue:
|
|---|
| 999 | queue.put("tile %s %s %s" % (tx, ty, tz))
|
|---|
| [9f5877d] | 1000 |
|
|---|
| 1001 |
|
|---|
| 1002 | def create_overview_tiles(tile_job_info, output_folder, options):
|
|---|
| 1003 | """Generation of the overview tiles (higher in the pyramid) based on existing tiles"""
|
|---|
| 1004 | mem_driver = gdal.GetDriverByName('MEM')
|
|---|
| 1005 | tile_driver = tile_job_info.tile_driver
|
|---|
| 1006 | out_driver = gdal.GetDriverByName(tile_driver)
|
|---|
| 1007 |
|
|---|
| 1008 | tilebands = tile_job_info.nb_data_bands + 1
|
|---|
| 1009 |
|
|---|
| 1010 | # Usage of existing tiles: from 4 underlying tiles generate one as overview.
|
|---|
| 1011 |
|
|---|
| 1012 | tcount = 0
|
|---|
| 1013 | for tz in range(tile_job_info.tmaxz - 1, tile_job_info.tminz - 1, -1):
|
|---|
| 1014 | tminx, tminy, tmaxx, tmaxy = tile_job_info.tminmax[tz]
|
|---|
| 1015 | tcount += (1 + abs(tmaxx - tminx)) * (1 + abs(tmaxy - tminy))
|
|---|
| 1016 |
|
|---|
| 1017 | ti = 0
|
|---|
| 1018 |
|
|---|
| 1019 | if tcount == 0:
|
|---|
| 1020 | return
|
|---|
| 1021 |
|
|---|
| 1022 | if not options.quiet:
|
|---|
| 1023 | print("Generating Overview Tiles:")
|
|---|
| 1024 |
|
|---|
| 1025 | progress_bar = ProgressBar(tcount)
|
|---|
| 1026 | progress_bar.start()
|
|---|
| 1027 |
|
|---|
| 1028 | for tz in range(tile_job_info.tmaxz - 1, tile_job_info.tminz - 1, -1):
|
|---|
| 1029 | tminx, tminy, tmaxx, tmaxy = tile_job_info.tminmax[tz]
|
|---|
| 1030 | for ty in range(tmaxy, tminy - 1, -1):
|
|---|
| 1031 | for tx in range(tminx, tmaxx + 1):
|
|---|
| 1032 |
|
|---|
| 1033 | ti += 1
|
|---|
| 1034 | tilefilename = os.path.join(output_folder,
|
|---|
| 1035 | str(tz),
|
|---|
| 1036 | str(tx),
|
|---|
| 1037 | "%s.%s" % (ty, tile_job_info.tile_extension))
|
|---|
| 1038 |
|
|---|
| 1039 | if options.verbose:
|
|---|
| 1040 | print(ti, '/', tcount, tilefilename)
|
|---|
| 1041 |
|
|---|
| 1042 | if options.resume and os.path.exists(tilefilename):
|
|---|
| 1043 | if options.verbose:
|
|---|
| 1044 | print("Tile generation skipped because of --resume")
|
|---|
| 1045 | else:
|
|---|
| 1046 | progress_bar.log_progress()
|
|---|
| 1047 | continue
|
|---|
| 1048 |
|
|---|
| 1049 | # Create directories for the tile
|
|---|
| 1050 | if not os.path.exists(os.path.dirname(tilefilename)):
|
|---|
| 1051 | os.makedirs(os.path.dirname(tilefilename))
|
|---|
| 1052 |
|
|---|
| 1053 | dsquery = mem_driver.Create('', 2 * tile_job_info.tile_size,
|
|---|
| 1054 | 2 * tile_job_info.tile_size, tilebands)
|
|---|
| 1055 | # TODO: fill the null value
|
|---|
| 1056 | dstile = mem_driver.Create('', tile_job_info.tile_size, tile_job_info.tile_size,
|
|---|
| 1057 | tilebands)
|
|---|
| 1058 |
|
|---|
| 1059 | # TODO: Implement more clever walking on the tiles with cache functionality
|
|---|
| 1060 | # probably walk should start with reading of four tiles from top left corner
|
|---|
| 1061 | # Hilbert curve
|
|---|
| 1062 |
|
|---|
| 1063 | children = []
|
|---|
| 1064 | # Read the tiles and write them to query window
|
|---|
| 1065 | for y in range(2 * ty, 2 * ty + 2):
|
|---|
| 1066 | for x in range(2 * tx, 2 * tx + 2):
|
|---|
| 1067 | minx, miny, maxx, maxy = tile_job_info.tminmax[tz + 1]
|
|---|
| 1068 | if x >= minx and x <= maxx and y >= miny and y <= maxy:
|
|---|
| 1069 | base_tile_path = os.path.join(output_folder, str(tz + 1), str(x),
|
|---|
| 1070 | "%s.%s" % (y, tile_job_info.tile_extension))
|
|---|
| 1071 | if not os.path.isfile(base_tile_path):
|
|---|
| 1072 | continue
|
|---|
| 1073 |
|
|---|
| 1074 | dsquerytile = gdal.Open(
|
|---|
| 1075 | base_tile_path,
|
|---|
| 1076 | gdal.GA_ReadOnly)
|
|---|
| 1077 | if (ty == 0 and y == 1) or (ty != 0 and (y % (2 * ty)) != 0):
|
|---|
| 1078 | tileposy = 0
|
|---|
| 1079 | else:
|
|---|
| 1080 | tileposy = tile_job_info.tile_size
|
|---|
| 1081 | if tx:
|
|---|
| 1082 | tileposx = x % (2 * tx) * tile_job_info.tile_size
|
|---|
| 1083 | elif tx == 0 and x == 1:
|
|---|
| 1084 | tileposx = tile_job_info.tile_size
|
|---|
| 1085 | else:
|
|---|
| 1086 | tileposx = 0
|
|---|
| 1087 | dsquery.WriteRaster(
|
|---|
| 1088 | tileposx, tileposy, tile_job_info.tile_size,
|
|---|
| 1089 | tile_job_info.tile_size,
|
|---|
| 1090 | dsquerytile.ReadRaster(0, 0,
|
|---|
| 1091 | tile_job_info.tile_size,
|
|---|
| 1092 | tile_job_info.tile_size),
|
|---|
| 1093 | band_list=list(range(1, tilebands + 1)))
|
|---|
| 1094 | children.append([x, y, tz + 1])
|
|---|
| 1095 |
|
|---|
| 1096 | if children:
|
|---|
| 1097 | scale_query_to_tile(dsquery, dstile, tile_driver, options,
|
|---|
| 1098 | tilefilename=tilefilename)
|
|---|
| 1099 | # Write a copy of tile to png/jpg
|
|---|
| 1100 | if options.resampling != 'antialias':
|
|---|
| 1101 | # Write a copy of tile to png/jpg
|
|---|
| 1102 | out_driver.CreateCopy(tilefilename, dstile, strict=0)
|
|---|
| 1103 |
|
|---|
| 1104 | if options.verbose:
|
|---|
| 1105 | print("\tbuild from zoom", tz + 1,
|
|---|
| 1106 | " tiles:", (2 * tx, 2 * ty), (2 * tx + 1, 2 * ty),
|
|---|
| 1107 | (2 * tx, 2 * ty + 1), (2 * tx + 1, 2 * ty + 1))
|
|---|
| 1108 |
|
|---|
| 1109 | # Create a KML file for this tile.
|
|---|
| 1110 | if tile_job_info.kml:
|
|---|
| 1111 | with open(os.path.join(
|
|---|
| 1112 | output_folder,
|
|---|
| 1113 | '%d/%d/%d.kml' % (tz, tx, ty)
|
|---|
| 1114 | ), 'wb') as f:
|
|---|
| 1115 | f.write(generate_kml(
|
|---|
| 1116 | tx, ty, tz, tile_job_info.tile_extension, tile_job_info.tile_size,
|
|---|
| 1117 | get_tile_swne(tile_job_info, options), options, children
|
|---|
| 1118 | ).encode('utf-8'))
|
|---|
| 1119 |
|
|---|
| 1120 | if not options.verbose and not options.quiet:
|
|---|
| 1121 | progress_bar.log_progress()
|
|---|
| 1122 |
|
|---|
| 1123 |
|
|---|
| 1124 | def optparse_init():
|
|---|
| 1125 | """Prepare the option parser for input (argv)"""
|
|---|
| 1126 |
|
|---|
| 1127 | from optparse import OptionParser, OptionGroup
|
|---|
| 1128 | usage = "Usage: %prog [options] input_file [output]"
|
|---|
| 1129 | p = OptionParser(usage, version="%prog " + __version__)
|
|---|
| 1130 | p.add_option("-p", "--profile", dest='profile',
|
|---|
| 1131 | type='choice', choices=profile_list,
|
|---|
| 1132 | help=("Tile cutting profile (%s) - default 'mercator' "
|
|---|
| 1133 | "(Google Maps compatible)" % ",".join(profile_list)))
|
|---|
| 1134 | p.add_option("-r", "--resampling", dest="resampling",
|
|---|
| 1135 | type='choice', choices=resampling_list,
|
|---|
| 1136 | help="Resampling method (%s) - default 'average'" % ",".join(resampling_list))
|
|---|
| 1137 | p.add_option('-s', '--s_srs', dest="s_srs", metavar="SRS",
|
|---|
| 1138 | help="The spatial reference system used for the source input data")
|
|---|
| 1139 | p.add_option('-z', '--zoom', dest="zoom",
|
|---|
| 1140 | help="Zoom levels to render (format:'2-5' or '10').")
|
|---|
| 1141 | p.add_option('-e', '--resume', dest="resume", action="store_true",
|
|---|
| 1142 | help="Resume mode. Generate only missing files.")
|
|---|
| 1143 | p.add_option('-a', '--srcnodata', dest="srcnodata", metavar="NODATA",
|
|---|
| 1144 | help="NODATA transparency value to assign to the input data")
|
|---|
| 1145 | p.add_option('-d', '--tmscompatible', dest="tmscompatible", action="store_true",
|
|---|
| 1146 | help=("When using the geodetic profile, specifies the base resolution "
|
|---|
| 1147 | "as 0.703125 or 2 tiles at zoom level 0."))
|
|---|
| 1148 | p.add_option("-v", "--verbose",
|
|---|
| 1149 | action="store_true", dest="verbose",
|
|---|
| 1150 | help="Print status messages to stdout")
|
|---|
| 1151 | p.add_option("-x", "--exclude",
|
|---|
| 1152 | action="store_true", dest="exclude_transparent",
|
|---|
| 1153 | help="Exclude transparent tiles from result tileset")
|
|---|
| 1154 | p.add_option("-q", "--quiet",
|
|---|
| 1155 | action="store_true", dest="quiet",
|
|---|
| 1156 | help="Disable messages and status to stdout")
|
|---|
| 1157 | p.add_option("--processes",
|
|---|
| 1158 | dest="nb_processes",
|
|---|
| 1159 | type='int',
|
|---|
| 1160 | help="Number of processes to use for tiling")
|
|---|
| 1161 | p.add_option("--tilesize", dest="tilesize", default=256,
|
|---|
| 1162 | type='int',
|
|---|
| 1163 | help="Tile size in pixel of a tile")
|
|---|
| 1164 |
|
|---|
| 1165 | # KML options
|
|---|
| 1166 | g = OptionGroup(p, "KML (Google Earth) options",
|
|---|
| 1167 | "Options for generated Google Earth SuperOverlay metadata")
|
|---|
| 1168 | g.add_option("-k", "--force-kml", dest='kml', action="store_true",
|
|---|
| 1169 | help=("Generate KML for Google Earth - default for 'geodetic' profile and "
|
|---|
| 1170 | "'raster' in EPSG:4326. For a dataset with different projection use "
|
|---|
| 1171 | "with caution!"))
|
|---|
| 1172 | g.add_option("-n", "--no-kml", dest='kml', action="store_false",
|
|---|
| 1173 | help="Avoid automatic generation of KML files for EPSG:4326")
|
|---|
| 1174 | g.add_option("-u", "--url", dest='url',
|
|---|
| 1175 | help="URL address where the generated tiles are going to be published")
|
|---|
| 1176 | p.add_option_group(g)
|
|---|
| 1177 |
|
|---|
| 1178 | # HTML options
|
|---|
| 1179 | g = OptionGroup(p, "Web viewer options",
|
|---|
| 1180 | "Options for generated HTML viewers a la Google Maps")
|
|---|
| 1181 | g.add_option("-w", "--webviewer", dest='webviewer', type='choice', choices=webviewer_list,
|
|---|
| 1182 | help="Web viewer to generate (%s) - default 'all'" % ",".join(webviewer_list))
|
|---|
| 1183 | g.add_option("-t", "--title", dest='title',
|
|---|
| 1184 | help="Title of the map")
|
|---|
| 1185 | g.add_option("-c", "--copyright", dest='copyright',
|
|---|
| 1186 | help="Copyright for the map")
|
|---|
| 1187 | g.add_option("-g", "--googlekey", dest='googlekey',
|
|---|
| 1188 | help="Google Maps API key from http://code.google.com/apis/maps/signup.html")
|
|---|
| 1189 | g.add_option("-b", "--bingkey", dest='bingkey',
|
|---|
| 1190 | help="Bing Maps API key from https://www.bingmapsportal.com/")
|
|---|
| 1191 | p.add_option_group(g)
|
|---|
| 1192 |
|
|---|
| 1193 | p.set_defaults(verbose=False, profile="mercator", kml=False, url='',
|
|---|
| 1194 | webviewer='all', copyright='', resampling='average', resume=False,
|
|---|
| 1195 | googlekey='INSERT_YOUR_KEY_HERE', bingkey='INSERT_YOUR_KEY_HERE',
|
|---|
| 1196 | processes=1)
|
|---|
| 1197 |
|
|---|
| 1198 | return p
|
|---|
| 1199 |
|
|---|
| 1200 |
|
|---|
| 1201 | def process_args(argv):
|
|---|
| 1202 | parser = optparse_init()
|
|---|
| 1203 | options, args = parser.parse_args(args=argv)
|
|---|
| 1204 |
|
|---|
| 1205 | # Args should be either an input file OR an input file and an output folder
|
|---|
| 1206 | if not args:
|
|---|
| 1207 | exit_with_error("You need to specify at least an input file as argument to the script")
|
|---|
| 1208 | if len(args) > 2:
|
|---|
| 1209 | exit_with_error("Processing of several input files is not supported.",
|
|---|
| 1210 | "Please first use a tool like gdal_vrtmerge.py or gdal_merge.py on the "
|
|---|
| 1211 | "files: gdal_vrtmerge.py -o merged.vrt %s" % " ".join(args))
|
|---|
| 1212 |
|
|---|
| 1213 | input_file = args[0]
|
|---|
| 1214 | if not os.path.isfile(input_file):
|
|---|
| 1215 | exit_with_error("The provided input file %s does not exist or is not a file" % input_file)
|
|---|
| 1216 |
|
|---|
| 1217 | if len(args) == 2:
|
|---|
| 1218 | output_folder = args[1]
|
|---|
| 1219 | else:
|
|---|
| 1220 | # Directory with input filename without extension in actual directory
|
|---|
| 1221 | output_folder = os.path.splitext(os.path.basename(input_file))[0]
|
|---|
| 1222 |
|
|---|
| 1223 | options = options_post_processing(options, input_file, output_folder)
|
|---|
| 1224 |
|
|---|
| 1225 | return input_file, output_folder, options
|
|---|
| 1226 |
|
|---|
| 1227 |
|
|---|
| 1228 | def options_post_processing(options, input_file, output_folder):
|
|---|
| 1229 | if not options.title:
|
|---|
| 1230 | options.title = os.path.basename(input_file)
|
|---|
| 1231 |
|
|---|
| 1232 | if options.url and not options.url.endswith('/'):
|
|---|
| 1233 | options.url += '/'
|
|---|
| 1234 | if options.url:
|
|---|
| 1235 | out_path = output_folder
|
|---|
| 1236 | if out_path.endswith("/"):
|
|---|
| 1237 | out_path = out_path[:-1]
|
|---|
| 1238 | options.url += os.path.basename(out_path) + '/'
|
|---|
| 1239 |
|
|---|
| 1240 | # Supported options
|
|---|
| 1241 | if options.resampling == 'antialias' and not numpy_available:
|
|---|
| 1242 | exit_with_error("'antialias' resampling algorithm is not available.",
|
|---|
| 1243 | "Install PIL (Python Imaging Library) and numpy.")
|
|---|
| 1244 |
|
|---|
| 1245 | try:
|
|---|
| 1246 | os.path.basename(input_file).encode('ascii')
|
|---|
| 1247 | except UnicodeEncodeError:
|
|---|
| 1248 | full_ascii = False
|
|---|
| 1249 | else:
|
|---|
| 1250 | full_ascii = True
|
|---|
| 1251 |
|
|---|
| 1252 | # LC_CTYPE check
|
|---|
| 1253 | if not full_ascii and 'UTF-8' not in os.environ.get("LC_CTYPE", ""):
|
|---|
| 1254 | if not options.quiet:
|
|---|
| 1255 | print("\nWARNING: "
|
|---|
| 1256 | "You are running gdal2tiles.py with a LC_CTYPE environment variable that is "
|
|---|
| 1257 | "not UTF-8 compatible, and your input file contains non-ascii characters. "
|
|---|
| 1258 | "The generated sample googlemaps, openlayers or "
|
|---|
| 1259 | "leaflet files might contain some invalid characters as a result\n")
|
|---|
| 1260 |
|
|---|
| 1261 | # Output the results
|
|---|
| 1262 | if options.verbose:
|
|---|
| 1263 | print("Options:", options)
|
|---|
| 1264 | print("Input:", input_file)
|
|---|
| 1265 | print("Output:", output_folder)
|
|---|
| 1266 | print("Cache: %s MB" % (gdal.GetCacheMax() / 1024 / 1024))
|
|---|
| 1267 | print('')
|
|---|
| 1268 |
|
|---|
| 1269 | return options
|
|---|
| 1270 |
|
|---|
| 1271 |
|
|---|
| 1272 | class TileDetail(object):
|
|---|
| 1273 | tx = 0
|
|---|
| 1274 | ty = 0
|
|---|
| 1275 | tz = 0
|
|---|
| 1276 | rx = 0
|
|---|
| 1277 | ry = 0
|
|---|
| 1278 | rxsize = 0
|
|---|
| 1279 | rysize = 0
|
|---|
| 1280 | wx = 0
|
|---|
| 1281 | wy = 0
|
|---|
| 1282 | wxsize = 0
|
|---|
| 1283 | wysize = 0
|
|---|
| 1284 | querysize = 0
|
|---|
| 1285 |
|
|---|
| 1286 | def __init__(self, **kwargs):
|
|---|
| 1287 | for key in kwargs:
|
|---|
| 1288 | if hasattr(self, key):
|
|---|
| 1289 | setattr(self, key, kwargs[key])
|
|---|
| 1290 |
|
|---|
| 1291 | def __unicode__(self):
|
|---|
| 1292 | return "TileDetail %s\n%s\n%s\n" % (self.tx, self.ty, self.tz)
|
|---|
| 1293 |
|
|---|
| 1294 | def __str__(self):
|
|---|
| 1295 | return "TileDetail %s\n%s\n%s\n" % (self.tx, self.ty, self.tz)
|
|---|
| 1296 |
|
|---|
| 1297 | def __repr__(self):
|
|---|
| 1298 | return "TileDetail %s\n%s\n%s\n" % (self.tx, self.ty, self.tz)
|
|---|
| 1299 |
|
|---|
| 1300 |
|
|---|
| 1301 | class TileJobInfo(object):
|
|---|
| 1302 | """
|
|---|
| 1303 | Plain object to hold tile job configuration for a dataset
|
|---|
| 1304 | """
|
|---|
| 1305 | src_file = ""
|
|---|
| 1306 | nb_data_bands = 0
|
|---|
| 1307 | output_file_path = ""
|
|---|
| 1308 | tile_extension = ""
|
|---|
| 1309 | tile_size = 0
|
|---|
| 1310 | tile_driver = None
|
|---|
| 1311 | kml = False
|
|---|
| 1312 | tminmax = []
|
|---|
| 1313 | tminz = 0
|
|---|
| 1314 | tmaxz = 0
|
|---|
| 1315 | in_srs_wkt = 0
|
|---|
| 1316 | out_geo_trans = []
|
|---|
| 1317 | ominy = 0
|
|---|
| 1318 | is_epsg_4326 = False
|
|---|
| 1319 | options = None
|
|---|
| 1320 | exclude_transparent = False
|
|---|
| 1321 |
|
|---|
| 1322 | def __init__(self, **kwargs):
|
|---|
| 1323 | for key in kwargs:
|
|---|
| 1324 | if hasattr(self, key):
|
|---|
| 1325 | setattr(self, key, kwargs[key])
|
|---|
| 1326 |
|
|---|
| 1327 | def __unicode__(self):
|
|---|
| 1328 | return "TileJobInfo %s\n" % (self.src_file)
|
|---|
| 1329 |
|
|---|
| 1330 | def __str__(self):
|
|---|
| 1331 | return "TileJobInfo %s\n" % (self.src_file)
|
|---|
| 1332 |
|
|---|
| 1333 | def __repr__(self):
|
|---|
| 1334 | return "TileJobInfo %s\n" % (self.src_file)
|
|---|
| 1335 |
|
|---|
| 1336 |
|
|---|
| 1337 | class Gdal2TilesError(Exception):
|
|---|
| 1338 | pass
|
|---|
| 1339 |
|
|---|
| 1340 |
|
|---|
| 1341 | class GDAL2Tiles(object):
|
|---|
| 1342 |
|
|---|
| 1343 | def __init__(self, input_file, output_folder, options):
|
|---|
| 1344 | """Constructor function - initialization"""
|
|---|
| 1345 | self.out_drv = None
|
|---|
| 1346 | self.mem_drv = None
|
|---|
| 1347 | self.warped_input_dataset = None
|
|---|
| 1348 | self.out_srs = None
|
|---|
| 1349 | self.nativezoom = None
|
|---|
| 1350 | self.tminmax = None
|
|---|
| 1351 | self.tsize = None
|
|---|
| 1352 | self.mercator = None
|
|---|
| 1353 | self.geodetic = None
|
|---|
| 1354 | self.alphaband = None
|
|---|
| 1355 | self.dataBandsCount = None
|
|---|
| 1356 | self.out_gt = None
|
|---|
| 1357 | self.tileswne = None
|
|---|
| 1358 | self.swne = None
|
|---|
| 1359 | self.ominx = None
|
|---|
| 1360 | self.omaxx = None
|
|---|
| 1361 | self.omaxy = None
|
|---|
| 1362 | self.ominy = None
|
|---|
| 1363 |
|
|---|
| 1364 | self.input_file = None
|
|---|
| 1365 | self.output_folder = None
|
|---|
| 1366 |
|
|---|
| 1367 | self.isepsg4326 = None
|
|---|
| 1368 | self.in_srs_wkt = None
|
|---|
| 1369 |
|
|---|
| 1370 | # Tile format
|
|---|
| 1371 | self.tile_size = 256
|
|---|
| 1372 | if options.tilesize:
|
|---|
| 1373 | self.tile_size = options.tilesize
|
|---|
| 1374 | self.tiledriver = 'PNG'
|
|---|
| 1375 | self.tileext = 'png'
|
|---|
| 1376 | self.tmp_dir = tempfile.mkdtemp()
|
|---|
| 1377 | self.tmp_vrt_filename = os.path.join(self.tmp_dir, str(uuid4()) + '.vrt')
|
|---|
| 1378 |
|
|---|
| 1379 | # Should we read bigger window of the input raster and scale it down?
|
|---|
| 1380 | # Note: Modified later by open_input()
|
|---|
| 1381 | # Not for 'near' resampling
|
|---|
| 1382 | # Not for Wavelet based drivers (JPEG2000, ECW, MrSID)
|
|---|
| 1383 | # Not for 'raster' profile
|
|---|
| 1384 | self.scaledquery = True
|
|---|
| 1385 | # How big should be query window be for scaling down
|
|---|
| 1386 | # Later on reset according the chosen resampling algorightm
|
|---|
| 1387 | self.querysize = 4 * self.tile_size
|
|---|
| 1388 |
|
|---|
| 1389 | # Should we use Read on the input file for generating overview tiles?
|
|---|
| 1390 | # Note: Modified later by open_input()
|
|---|
| 1391 | # Otherwise the overview tiles are generated from existing underlying tiles
|
|---|
| 1392 | self.overviewquery = False
|
|---|
| 1393 |
|
|---|
| 1394 | self.input_file = input_file
|
|---|
| 1395 | self.output_folder = output_folder
|
|---|
| 1396 | self.options = options
|
|---|
| 1397 |
|
|---|
| 1398 | if self.options.resampling == 'near':
|
|---|
| 1399 | self.querysize = self.tile_size
|
|---|
| 1400 |
|
|---|
| 1401 | elif self.options.resampling == 'bilinear':
|
|---|
| 1402 | self.querysize = self.tile_size * 2
|
|---|
| 1403 |
|
|---|
| 1404 | # User specified zoom levels
|
|---|
| 1405 | self.tminz = None
|
|---|
| 1406 | self.tmaxz = None
|
|---|
| 1407 | if self.options.zoom:
|
|---|
| 1408 | minmax = self.options.zoom.split('-', 1)
|
|---|
| 1409 | minmax.extend([''])
|
|---|
| 1410 | zoom_min, zoom_max = minmax[:2]
|
|---|
| 1411 | self.tminz = int(zoom_min)
|
|---|
| 1412 | if zoom_max:
|
|---|
| 1413 | self.tmaxz = int(zoom_max)
|
|---|
| 1414 | else:
|
|---|
| 1415 | self.tmaxz = int(zoom_min)
|
|---|
| 1416 |
|
|---|
| 1417 | # KML generation
|
|---|
| 1418 | self.kml = self.options.kml
|
|---|
| 1419 |
|
|---|
| 1420 | # -------------------------------------------------------------------------
|
|---|
| 1421 | def open_input(self):
|
|---|
| 1422 | """Initialization of the input raster, reprojection if necessary"""
|
|---|
| 1423 | gdal.AllRegister()
|
|---|
| 1424 |
|
|---|
| 1425 | self.out_drv = gdal.GetDriverByName(self.tiledriver)
|
|---|
| 1426 | self.mem_drv = gdal.GetDriverByName('MEM')
|
|---|
| 1427 |
|
|---|
| 1428 | if not self.out_drv:
|
|---|
| 1429 | raise Exception("The '%s' driver was not found, is it available in this GDAL build?" %
|
|---|
| 1430 | self.tiledriver)
|
|---|
| 1431 | if not self.mem_drv:
|
|---|
| 1432 | raise Exception("The 'MEM' driver was not found, is it available in this GDAL build?")
|
|---|
| 1433 |
|
|---|
| 1434 | # Open the input file
|
|---|
| 1435 |
|
|---|
| 1436 | if self.input_file:
|
|---|
| 1437 | input_dataset = gdal.Open(self.input_file, gdal.GA_ReadOnly)
|
|---|
| 1438 | else:
|
|---|
| 1439 | raise Exception("No input file was specified")
|
|---|
| 1440 |
|
|---|
| 1441 | if self.options.verbose:
|
|---|
| 1442 | print("Input file:",
|
|---|
| 1443 | "( %sP x %sL - %s bands)" % (input_dataset.RasterXSize,
|
|---|
| 1444 | input_dataset.RasterYSize,
|
|---|
| 1445 | input_dataset.RasterCount))
|
|---|
| 1446 |
|
|---|
| 1447 | if not input_dataset:
|
|---|
| 1448 | # Note: GDAL prints the ERROR message too
|
|---|
| 1449 | exit_with_error("It is not possible to open the input file '%s'." % self.input_file)
|
|---|
| 1450 |
|
|---|
| 1451 | # Read metadata from the input file
|
|---|
| 1452 | if input_dataset.RasterCount == 0:
|
|---|
| 1453 | exit_with_error("Input file '%s' has no raster band" % self.input_file)
|
|---|
| 1454 |
|
|---|
| 1455 | if input_dataset.GetRasterBand(1).GetRasterColorTable():
|
|---|
| 1456 | exit_with_error(
|
|---|
| 1457 | "Please convert this file to RGB/RGBA and run gdal2tiles on the result.",
|
|---|
| 1458 | "From paletted file you can create RGBA file (temp.vrt) by:\n"
|
|---|
| 1459 | "gdal_translate -of vrt -expand rgba %s temp.vrt\n"
|
|---|
| 1460 | "then run:\n"
|
|---|
| 1461 | "gdal2tiles temp.vrt" % self.input_file
|
|---|
| 1462 | )
|
|---|
| 1463 |
|
|---|
| 1464 | in_nodata = setup_no_data_values(input_dataset, self.options)
|
|---|
| 1465 |
|
|---|
| 1466 | if self.options.verbose:
|
|---|
| 1467 | print("Preprocessed file:",
|
|---|
| 1468 | "( %sP x %sL - %s bands)" % (input_dataset.RasterXSize,
|
|---|
| 1469 | input_dataset.RasterYSize,
|
|---|
| 1470 | input_dataset.RasterCount))
|
|---|
| 1471 |
|
|---|
| 1472 | in_srs, self.in_srs_wkt = setup_input_srs(input_dataset, self.options)
|
|---|
| 1473 |
|
|---|
| 1474 | self.out_srs = setup_output_srs(in_srs, self.options)
|
|---|
| 1475 |
|
|---|
| 1476 | # If input and output reference systems are different, we reproject the input dataset into
|
|---|
| 1477 | # the output reference system for easier manipulation
|
|---|
| 1478 |
|
|---|
| 1479 | self.warped_input_dataset = None
|
|---|
| 1480 |
|
|---|
| 1481 | if self.options.profile in ('mercator', 'geodetic'):
|
|---|
| 1482 |
|
|---|
| 1483 | if not in_srs:
|
|---|
| 1484 | exit_with_error(
|
|---|
| 1485 | "Input file has unknown SRS.",
|
|---|
| 1486 | "Use --s_srs ESPG:xyz (or similar) to provide source reference system.")
|
|---|
| 1487 |
|
|---|
| 1488 | if not has_georeference(input_dataset):
|
|---|
| 1489 | exit_with_error(
|
|---|
| 1490 | "There is no georeference - neither affine transformation (worldfile) "
|
|---|
| 1491 | "nor GCPs. You can generate only 'raster' profile tiles.",
|
|---|
| 1492 | "Either gdal2tiles with parameter -p 'raster' or use another GIS "
|
|---|
| 1493 | "software for georeference e.g. gdal_transform -gcp / -a_ullr / -a_srs"
|
|---|
| 1494 | )
|
|---|
| 1495 |
|
|---|
| 1496 | if ((in_srs.ExportToProj4() != self.out_srs.ExportToProj4()) or
|
|---|
| 1497 | (input_dataset.GetGCPCount() != 0)):
|
|---|
| 1498 | self.warped_input_dataset = reproject_dataset(
|
|---|
| 1499 | input_dataset, in_srs, self.out_srs)
|
|---|
| 1500 |
|
|---|
| 1501 | if in_nodata:
|
|---|
| 1502 | self.warped_input_dataset = update_no_data_values(
|
|---|
| 1503 | self.warped_input_dataset, in_nodata, options=self.options)
|
|---|
| 1504 | else:
|
|---|
| 1505 | self.warped_input_dataset = update_alpha_value_for_non_alpha_inputs(
|
|---|
| 1506 | self.warped_input_dataset, options=self.options)
|
|---|
| 1507 |
|
|---|
| 1508 | if self.warped_input_dataset and self.options.verbose:
|
|---|
| 1509 | print("Projected file:", "tiles.vrt", "( %sP x %sL - %s bands)" % (
|
|---|
| 1510 | self.warped_input_dataset.RasterXSize,
|
|---|
| 1511 | self.warped_input_dataset.RasterYSize,
|
|---|
| 1512 | self.warped_input_dataset.RasterCount))
|
|---|
| 1513 |
|
|---|
| 1514 | if not self.warped_input_dataset:
|
|---|
| 1515 | self.warped_input_dataset = input_dataset
|
|---|
| 1516 |
|
|---|
| 1517 | gdal.GetDriverByName('VRT').CreateCopy(self.tmp_vrt_filename,
|
|---|
| 1518 | self.warped_input_dataset)
|
|---|
| 1519 |
|
|---|
| 1520 | # Get alpha band (either directly or from NODATA value)
|
|---|
| 1521 | self.alphaband = self.warped_input_dataset.GetRasterBand(1).GetMaskBand()
|
|---|
| 1522 | self.dataBandsCount = nb_data_bands(self.warped_input_dataset)
|
|---|
| 1523 |
|
|---|
| 1524 | # KML test
|
|---|
| 1525 | self.isepsg4326 = False
|
|---|
| 1526 | srs4326 = osr.SpatialReference()
|
|---|
| 1527 | srs4326.ImportFromEPSG(4326)
|
|---|
| 1528 | if self.out_srs and srs4326.ExportToProj4() == self.out_srs.ExportToProj4():
|
|---|
| 1529 | self.kml = True
|
|---|
| 1530 | self.isepsg4326 = True
|
|---|
| 1531 | if self.options.verbose:
|
|---|
| 1532 | print("KML autotest OK!")
|
|---|
| 1533 |
|
|---|
| 1534 | # Read the georeference
|
|---|
| 1535 | self.out_gt = self.warped_input_dataset.GetGeoTransform()
|
|---|
| 1536 |
|
|---|
| 1537 | # Test the size of the pixel
|
|---|
| 1538 |
|
|---|
| 1539 | # Report error in case rotation/skew is in geotransform (possible only in 'raster' profile)
|
|---|
| 1540 | if (self.out_gt[2], self.out_gt[4]) != (0, 0):
|
|---|
| 1541 | exit_with_error("Georeference of the raster contains rotation or skew. "
|
|---|
| 1542 | "Such raster is not supported. Please use gdalwarp first.")
|
|---|
| 1543 |
|
|---|
| 1544 | # Here we expect: pixel is square, no rotation on the raster
|
|---|
| 1545 |
|
|---|
| 1546 | # Output Bounds - coordinates in the output SRS
|
|---|
| 1547 | self.ominx = self.out_gt[0]
|
|---|
| 1548 | self.omaxx = self.out_gt[0] + self.warped_input_dataset.RasterXSize * self.out_gt[1]
|
|---|
| 1549 | self.omaxy = self.out_gt[3]
|
|---|
| 1550 | self.ominy = self.out_gt[3] - self.warped_input_dataset.RasterYSize * self.out_gt[1]
|
|---|
| 1551 | # Note: maybe round(x, 14) to avoid the gdal_translate behaviour, when 0 becomes -1e-15
|
|---|
| 1552 |
|
|---|
| 1553 | if self.options.verbose:
|
|---|
| 1554 | print("Bounds (output srs):", round(self.ominx, 13), self.ominy, self.omaxx, self.omaxy)
|
|---|
| 1555 |
|
|---|
| 1556 | # Calculating ranges for tiles in different zoom levels
|
|---|
| 1557 | if self.options.profile == 'mercator':
|
|---|
| 1558 |
|
|---|
| 1559 | self.mercator = GlobalMercator(tile_size=self.tile_size)
|
|---|
| 1560 |
|
|---|
| 1561 | # Function which generates SWNE in LatLong for given tile
|
|---|
| 1562 | self.tileswne = self.mercator.TileLatLonBounds
|
|---|
| 1563 |
|
|---|
| 1564 | # Generate table with min max tile coordinates for all zoomlevels
|
|---|
| 1565 | self.tminmax = list(range(0, 32))
|
|---|
| 1566 | for tz in range(0, 32):
|
|---|
| 1567 | tminx, tminy = self.mercator.MetersToTile(self.ominx, self.ominy, tz)
|
|---|
| 1568 | tmaxx, tmaxy = self.mercator.MetersToTile(self.omaxx, self.omaxy, tz)
|
|---|
| 1569 | # crop tiles extending world limits (+-180,+-90)
|
|---|
| 1570 | tminx, tminy = max(0, tminx), max(0, tminy)
|
|---|
| 1571 | tmaxx, tmaxy = min(2**tz - 1, tmaxx), min(2**tz - 1, tmaxy)
|
|---|
| 1572 | self.tminmax[tz] = (tminx, tminy, tmaxx, tmaxy)
|
|---|
| 1573 |
|
|---|
| 1574 | # TODO: Maps crossing 180E (Alaska?)
|
|---|
| 1575 |
|
|---|
| 1576 | # Get the minimal zoom level (map covers area equivalent to one tile)
|
|---|
| 1577 | if self.tminz is None:
|
|---|
| 1578 | self.tminz = self.mercator.ZoomForPixelSize(
|
|---|
| 1579 | self.out_gt[1] *
|
|---|
| 1580 | max(self.warped_input_dataset.RasterXSize,
|
|---|
| 1581 | self.warped_input_dataset.RasterYSize) /
|
|---|
| 1582 | float(self.tile_size))
|
|---|
| 1583 |
|
|---|
| 1584 | # Get the maximal zoom level
|
|---|
| 1585 | # (closest possible zoom level up on the resolution of raster)
|
|---|
| 1586 | if self.tmaxz is None:
|
|---|
| 1587 | self.tmaxz = self.mercator.ZoomForPixelSize(self.out_gt[1])
|
|---|
| 1588 |
|
|---|
| 1589 | if self.options.verbose:
|
|---|
| 1590 | print("Bounds (latlong):",
|
|---|
| 1591 | self.mercator.MetersToLatLon(self.ominx, self.ominy),
|
|---|
| 1592 | self.mercator.MetersToLatLon(self.omaxx, self.omaxy))
|
|---|
| 1593 | print('MinZoomLevel:', self.tminz)
|
|---|
| 1594 | print("MaxZoomLevel:",
|
|---|
| 1595 | self.tmaxz,
|
|---|
| 1596 | "(",
|
|---|
| 1597 | self.mercator.Resolution(self.tmaxz),
|
|---|
| 1598 | ")")
|
|---|
| 1599 |
|
|---|
| 1600 | if self.options.profile == 'geodetic':
|
|---|
| 1601 |
|
|---|
| 1602 | self.geodetic = GlobalGeodetic(self.options.tmscompatible, tile_size=self.tile_size)
|
|---|
| 1603 |
|
|---|
| 1604 | # Function which generates SWNE in LatLong for given tile
|
|---|
| 1605 | self.tileswne = self.geodetic.TileLatLonBounds
|
|---|
| 1606 |
|
|---|
| 1607 | # Generate table with min max tile coordinates for all zoomlevels
|
|---|
| 1608 | self.tminmax = list(range(0, 32))
|
|---|
| 1609 | for tz in range(0, 32):
|
|---|
| 1610 | tminx, tminy = self.geodetic.LonLatToTile(self.ominx, self.ominy, tz)
|
|---|
| 1611 | tmaxx, tmaxy = self.geodetic.LonLatToTile(self.omaxx, self.omaxy, tz)
|
|---|
| 1612 | # crop tiles extending world limits (+-180,+-90)
|
|---|
| 1613 | tminx, tminy = max(0, tminx), max(0, tminy)
|
|---|
| 1614 | tmaxx, tmaxy = min(2**(tz + 1) - 1, tmaxx), min(2**tz - 1, tmaxy)
|
|---|
| 1615 | self.tminmax[tz] = (tminx, tminy, tmaxx, tmaxy)
|
|---|
| 1616 |
|
|---|
| 1617 | # TODO: Maps crossing 180E (Alaska?)
|
|---|
| 1618 |
|
|---|
| 1619 | # Get the maximal zoom level
|
|---|
| 1620 | # (closest possible zoom level up on the resolution of raster)
|
|---|
| 1621 | if self.tminz is None:
|
|---|
| 1622 | self.tminz = self.geodetic.ZoomForPixelSize(
|
|---|
| 1623 | self.out_gt[1] *
|
|---|
| 1624 | max(self.warped_input_dataset.RasterXSize,
|
|---|
| 1625 | self.warped_input_dataset.RasterYSize) /
|
|---|
| 1626 | float(self.tile_size))
|
|---|
| 1627 |
|
|---|
| 1628 | # Get the maximal zoom level
|
|---|
| 1629 | # (closest possible zoom level up on the resolution of raster)
|
|---|
| 1630 | if self.tmaxz is None:
|
|---|
| 1631 | self.tmaxz = self.geodetic.ZoomForPixelSize(self.out_gt[1])
|
|---|
| 1632 |
|
|---|
| 1633 | if self.options.verbose:
|
|---|
| 1634 | print("Bounds (latlong):", self.ominx, self.ominy, self.omaxx, self.omaxy)
|
|---|
| 1635 |
|
|---|
| 1636 | if self.options.profile == 'raster':
|
|---|
| 1637 |
|
|---|
| 1638 | def log2(x):
|
|---|
| 1639 | return math.log10(x) / math.log10(2)
|
|---|
| 1640 |
|
|---|
| 1641 | self.nativezoom = int(
|
|---|
| 1642 | max(math.ceil(log2(self.warped_input_dataset.RasterXSize / float(self.tile_size))),
|
|---|
| 1643 | math.ceil(log2(self.warped_input_dataset.RasterYSize / float(self.tile_size)))))
|
|---|
| 1644 |
|
|---|
| 1645 | if self.options.verbose:
|
|---|
| 1646 | print("Native zoom of the raster:", self.nativezoom)
|
|---|
| 1647 |
|
|---|
| 1648 | # Get the minimal zoom level (whole raster in one tile)
|
|---|
| 1649 | if self.tminz is None:
|
|---|
| 1650 | self.tminz = 0
|
|---|
| 1651 |
|
|---|
| 1652 | # Get the maximal zoom level (native resolution of the raster)
|
|---|
| 1653 | if self.tmaxz is None:
|
|---|
| 1654 | self.tmaxz = self.nativezoom
|
|---|
| 1655 |
|
|---|
| 1656 | # Generate table with min max tile coordinates for all zoomlevels
|
|---|
| 1657 | self.tminmax = list(range(0, self.tmaxz + 1))
|
|---|
| 1658 | self.tsize = list(range(0, self.tmaxz + 1))
|
|---|
| 1659 | for tz in range(0, self.tmaxz + 1):
|
|---|
| 1660 | tsize = 2.0**(self.nativezoom - tz) * self.tile_size
|
|---|
| 1661 | tminx, tminy = 0, 0
|
|---|
| 1662 | tmaxx = int(math.ceil(self.warped_input_dataset.RasterXSize / tsize)) - 1
|
|---|
| 1663 | tmaxy = int(math.ceil(self.warped_input_dataset.RasterYSize / tsize)) - 1
|
|---|
| 1664 | self.tsize[tz] = math.ceil(tsize)
|
|---|
| 1665 | self.tminmax[tz] = (tminx, tminy, tmaxx, tmaxy)
|
|---|
| 1666 |
|
|---|
| 1667 | # Function which generates SWNE in LatLong for given tile
|
|---|
| 1668 | if self.kml and self.in_srs_wkt:
|
|---|
| 1669 | ct = osr.CoordinateTransformation(in_srs, srs4326)
|
|---|
| 1670 |
|
|---|
| 1671 | def rastertileswne(x, y, z):
|
|---|
| 1672 | pixelsizex = (2**(self.tmaxz - z) * self.out_gt[1]) # X-pixel size in level
|
|---|
| 1673 | west = self.out_gt[0] + x * self.tile_size * pixelsizex
|
|---|
| 1674 | east = west + self.tile_size * pixelsizex
|
|---|
| 1675 | south = self.ominy + y * self.tile_size * pixelsizex
|
|---|
| 1676 | north = south + self.tile_size * pixelsizex
|
|---|
| 1677 | if not self.isepsg4326:
|
|---|
| 1678 | # Transformation to EPSG:4326 (WGS84 datum)
|
|---|
| 1679 | west, south = ct.TransformPoint(west, south)[:2]
|
|---|
| 1680 | east, north = ct.TransformPoint(east, north)[:2]
|
|---|
| 1681 | return south, west, north, east
|
|---|
| 1682 |
|
|---|
| 1683 | self.tileswne = rastertileswne
|
|---|
| 1684 | else:
|
|---|
| 1685 | self.tileswne = lambda x, y, z: (0, 0, 0, 0) # noqa
|
|---|
| 1686 |
|
|---|
| 1687 | def generate_metadata(self):
|
|---|
| 1688 | """
|
|---|
| 1689 | Generation of main metadata files and HTML viewers (metadata related to particular
|
|---|
| 1690 | tiles are generated during the tile processing).
|
|---|
| 1691 | """
|
|---|
| 1692 |
|
|---|
| 1693 | if not os.path.exists(self.output_folder):
|
|---|
| 1694 | os.makedirs(self.output_folder)
|
|---|
| 1695 |
|
|---|
| 1696 | if self.options.profile == 'mercator':
|
|---|
| 1697 |
|
|---|
| 1698 | south, west = self.mercator.MetersToLatLon(self.ominx, self.ominy)
|
|---|
| 1699 | north, east = self.mercator.MetersToLatLon(self.omaxx, self.omaxy)
|
|---|
| 1700 | south, west = max(-85.05112878, south), max(-180.0, west)
|
|---|
| 1701 | north, east = min(85.05112878, north), min(180.0, east)
|
|---|
| 1702 | self.swne = (south, west, north, east)
|
|---|
| 1703 |
|
|---|
| 1704 | # Generate googlemaps.html
|
|---|
| 1705 | if self.options.webviewer in ('all', 'google') and self.options.profile == 'mercator':
|
|---|
| 1706 | if (not self.options.resume or not
|
|---|
| 1707 | os.path.exists(os.path.join(self.output_folder, 'googlemaps.html'))):
|
|---|
| 1708 | with open(os.path.join(self.output_folder, 'googlemaps.html'), 'wb') as f:
|
|---|
| 1709 | f.write(self.generate_googlemaps().encode('utf-8'))
|
|---|
| 1710 |
|
|---|
| 1711 | # Generate openlayers.html
|
|---|
| 1712 | if self.options.webviewer in ('all', 'openlayers'):
|
|---|
| 1713 | if (not self.options.resume or not
|
|---|
| 1714 | os.path.exists(os.path.join(self.output_folder, 'openlayers.html'))):
|
|---|
| 1715 | with open(os.path.join(self.output_folder, 'openlayers.html'), 'wb') as f:
|
|---|
| 1716 | f.write(self.generate_openlayers().encode('utf-8'))
|
|---|
| 1717 |
|
|---|
| 1718 | # Generate leaflet.html
|
|---|
| 1719 | if self.options.webviewer in ('all', 'leaflet'):
|
|---|
| 1720 | if (not self.options.resume or not
|
|---|
| 1721 | os.path.exists(os.path.join(self.output_folder, 'leaflet.html'))):
|
|---|
| 1722 | with open(os.path.join(self.output_folder, 'leaflet.html'), 'wb') as f:
|
|---|
| 1723 | f.write(self.generate_leaflet().encode('utf-8'))
|
|---|
| 1724 |
|
|---|
| 1725 | elif self.options.profile == 'geodetic':
|
|---|
| 1726 |
|
|---|
| 1727 | west, south = self.ominx, self.ominy
|
|---|
| 1728 | east, north = self.omaxx, self.omaxy
|
|---|
| 1729 | south, west = max(-90.0, south), max(-180.0, west)
|
|---|
| 1730 | north, east = min(90.0, north), min(180.0, east)
|
|---|
| 1731 | self.swne = (south, west, north, east)
|
|---|
| 1732 |
|
|---|
| 1733 | # Generate openlayers.html
|
|---|
| 1734 | if self.options.webviewer in ('all', 'openlayers'):
|
|---|
| 1735 | if (not self.options.resume or not
|
|---|
| 1736 | os.path.exists(os.path.join(self.output_folder, 'openlayers.html'))):
|
|---|
| 1737 | with open(os.path.join(self.output_folder, 'openlayers.html'), 'wb') as f:
|
|---|
| 1738 | f.write(self.generate_openlayers().encode('utf-8'))
|
|---|
| 1739 |
|
|---|
| 1740 | elif self.options.profile == 'raster':
|
|---|
| 1741 |
|
|---|
| 1742 | west, south = self.ominx, self.ominy
|
|---|
| 1743 | east, north = self.omaxx, self.omaxy
|
|---|
| 1744 |
|
|---|
| 1745 | self.swne = (south, west, north, east)
|
|---|
| 1746 |
|
|---|
| 1747 | # Generate openlayers.html
|
|---|
| 1748 | if self.options.webviewer in ('all', 'openlayers'):
|
|---|
| 1749 | if (not self.options.resume or not
|
|---|
| 1750 | os.path.exists(os.path.join(self.output_folder, 'openlayers.html'))):
|
|---|
| 1751 | with open(os.path.join(self.output_folder, 'openlayers.html'), 'wb') as f:
|
|---|
| 1752 | f.write(self.generate_openlayers().encode('utf-8'))
|
|---|
| 1753 |
|
|---|
| 1754 | # Generate tilemapresource.xml.
|
|---|
| 1755 | if not self.options.resume or not os.path.exists(os.path.join(self.output_folder, 'tilemapresource.xml')):
|
|---|
| 1756 | with open(os.path.join(self.output_folder, 'tilemapresource.xml'), 'wb') as f:
|
|---|
| 1757 | f.write(self.generate_tilemapresource().encode('utf-8'))
|
|---|
| 1758 |
|
|---|
| 1759 | if self.kml:
|
|---|
| 1760 | # TODO: Maybe problem for not automatically generated tminz
|
|---|
| 1761 | # The root KML should contain links to all tiles in the tminz level
|
|---|
| 1762 | children = []
|
|---|
| 1763 | xmin, ymin, xmax, ymax = self.tminmax[self.tminz]
|
|---|
| 1764 | for x in range(xmin, xmax + 1):
|
|---|
| 1765 | for y in range(ymin, ymax + 1):
|
|---|
| 1766 | children.append([x, y, self.tminz])
|
|---|
| 1767 | # Generate Root KML
|
|---|
| 1768 | if self.kml:
|
|---|
| 1769 | if (not self.options.resume or not
|
|---|
| 1770 | os.path.exists(os.path.join(self.output_folder, 'doc.kml'))):
|
|---|
| 1771 | with open(os.path.join(self.output_folder, 'doc.kml'), 'wb') as f:
|
|---|
| 1772 | f.write(generate_kml(
|
|---|
| 1773 | None, None, None, self.tileext, self.tile_size, self.tileswne,
|
|---|
| 1774 | self.options, children
|
|---|
| 1775 | ).encode('utf-8'))
|
|---|
| 1776 |
|
|---|
| 1777 | def generate_base_tiles(self):
|
|---|
| 1778 | """
|
|---|
| 1779 | Generation of the base tiles (the lowest in the pyramid) directly from the input raster
|
|---|
| 1780 | """
|
|---|
| 1781 |
|
|---|
| 1782 | if not self.options.quiet:
|
|---|
| 1783 | print("Generating Base Tiles:")
|
|---|
| 1784 |
|
|---|
| 1785 | if self.options.verbose:
|
|---|
| 1786 | print('')
|
|---|
| 1787 | print("Tiles generated from the max zoom level:")
|
|---|
| 1788 | print("----------------------------------------")
|
|---|
| 1789 | print('')
|
|---|
| 1790 |
|
|---|
| 1791 | # Set the bounds
|
|---|
| 1792 | tminx, tminy, tmaxx, tmaxy = self.tminmax[self.tmaxz]
|
|---|
| 1793 |
|
|---|
| 1794 | ds = self.warped_input_dataset
|
|---|
| 1795 | tilebands = self.dataBandsCount + 1
|
|---|
| 1796 | querysize = self.querysize
|
|---|
| 1797 |
|
|---|
| 1798 | if self.options.verbose:
|
|---|
| 1799 | print("dataBandsCount: ", self.dataBandsCount)
|
|---|
| 1800 | print("tilebands: ", tilebands)
|
|---|
| 1801 |
|
|---|
| 1802 | tcount = (1 + abs(tmaxx - tminx)) * (1 + abs(tmaxy - tminy))
|
|---|
| 1803 | ti = 0
|
|---|
| 1804 |
|
|---|
| 1805 | tile_details = []
|
|---|
| 1806 |
|
|---|
| 1807 | tz = self.tmaxz
|
|---|
| 1808 | for ty in range(tmaxy, tminy - 1, -1):
|
|---|
| 1809 | for tx in range(tminx, tmaxx + 1):
|
|---|
| 1810 |
|
|---|
| 1811 | ti += 1
|
|---|
| 1812 | tilefilename = os.path.join(
|
|---|
| 1813 | self.output_folder, str(tz), str(tx), "%s.%s" % (ty, self.tileext))
|
|---|
| 1814 | if self.options.verbose:
|
|---|
| 1815 | print(ti, '/', tcount, tilefilename)
|
|---|
| 1816 |
|
|---|
| 1817 | if self.options.resume and os.path.exists(tilefilename):
|
|---|
| 1818 | if self.options.verbose:
|
|---|
| 1819 | print("Tile generation skipped because of --resume")
|
|---|
| 1820 | continue
|
|---|
| 1821 |
|
|---|
| 1822 | # Create directories for the tile
|
|---|
| 1823 | if not os.path.exists(os.path.dirname(tilefilename)):
|
|---|
| 1824 | os.makedirs(os.path.dirname(tilefilename))
|
|---|
| 1825 |
|
|---|
| 1826 | if self.options.profile == 'mercator':
|
|---|
| 1827 | # Tile bounds in EPSG:3857
|
|---|
| 1828 | b = self.mercator.TileBounds(tx, ty, tz)
|
|---|
| 1829 | elif self.options.profile == 'geodetic':
|
|---|
| 1830 | b = self.geodetic.TileBounds(tx, ty, tz)
|
|---|
| 1831 |
|
|---|
| 1832 | # Don't scale up by nearest neighbour, better change the querysize
|
|---|
| 1833 | # to the native resolution (and return smaller query tile) for scaling
|
|---|
| 1834 |
|
|---|
| 1835 | if self.options.profile in ('mercator', 'geodetic'):
|
|---|
| 1836 | rb, wb = self.geo_query(ds, b[0], b[3], b[2], b[1])
|
|---|
| 1837 |
|
|---|
| 1838 | # Pixel size in the raster covering query geo extent
|
|---|
| 1839 | nativesize = wb[0] + wb[2]
|
|---|
| 1840 | if self.options.verbose:
|
|---|
| 1841 | print("\tNative Extent (querysize", nativesize, "): ", rb, wb)
|
|---|
| 1842 |
|
|---|
| 1843 | # Tile bounds in raster coordinates for ReadRaster query
|
|---|
| 1844 | rb, wb = self.geo_query(ds, b[0], b[3], b[2], b[1], querysize=querysize)
|
|---|
| 1845 |
|
|---|
| 1846 | rx, ry, rxsize, rysize = rb
|
|---|
| 1847 | wx, wy, wxsize, wysize = wb
|
|---|
| 1848 |
|
|---|
| 1849 | else: # 'raster' profile:
|
|---|
| 1850 |
|
|---|
| 1851 | tsize = int(self.tsize[tz]) # tile_size in raster coordinates for actual zoom
|
|---|
| 1852 | xsize = self.warped_input_dataset.RasterXSize # size of the raster in pixels
|
|---|
| 1853 | ysize = self.warped_input_dataset.RasterYSize
|
|---|
| 1854 | if tz >= self.nativezoom:
|
|---|
| 1855 | querysize = self.tile_size
|
|---|
| 1856 |
|
|---|
| 1857 | rx = (tx) * tsize
|
|---|
| 1858 | rxsize = 0
|
|---|
| 1859 | if tx == tmaxx:
|
|---|
| 1860 | rxsize = xsize % tsize
|
|---|
| 1861 | if rxsize == 0:
|
|---|
| 1862 | rxsize = tsize
|
|---|
| 1863 |
|
|---|
| 1864 | rysize = 0
|
|---|
| 1865 | if ty == tmaxy:
|
|---|
| 1866 | rysize = ysize % tsize
|
|---|
| 1867 | if rysize == 0:
|
|---|
| 1868 | rysize = tsize
|
|---|
| 1869 | ry = ysize - (ty * tsize) - rysize
|
|---|
| 1870 |
|
|---|
| 1871 | wx, wy = 0, 0
|
|---|
| 1872 | wxsize = int(rxsize / float(tsize) * self.tile_size)
|
|---|
| 1873 | wysize = int(rysize / float(tsize) * self.tile_size)
|
|---|
| 1874 | if wysize != self.tile_size:
|
|---|
| 1875 | wy = self.tile_size - wysize
|
|---|
| 1876 |
|
|---|
| 1877 | # Read the source raster if anything is going inside the tile as per the computed
|
|---|
| 1878 | # geo_query
|
|---|
| 1879 | tile_details.append(
|
|---|
| 1880 | TileDetail(
|
|---|
| 1881 | tx=tx, ty=ty, tz=tz, rx=rx, ry=ry, rxsize=rxsize, rysize=rysize, wx=wx,
|
|---|
| 1882 | wy=wy, wxsize=wxsize, wysize=wysize, querysize=querysize,
|
|---|
| 1883 | )
|
|---|
| 1884 | )
|
|---|
| 1885 |
|
|---|
| 1886 | conf = TileJobInfo(
|
|---|
| 1887 | src_file=self.tmp_vrt_filename,
|
|---|
| 1888 | nb_data_bands=self.dataBandsCount,
|
|---|
| 1889 | output_file_path=self.output_folder,
|
|---|
| 1890 | tile_extension=self.tileext,
|
|---|
| 1891 | tile_driver=self.tiledriver,
|
|---|
| 1892 | tile_size=self.tile_size,
|
|---|
| 1893 | kml=self.kml,
|
|---|
| 1894 | tminmax=self.tminmax,
|
|---|
| 1895 | tminz=self.tminz,
|
|---|
| 1896 | tmaxz=self.tmaxz,
|
|---|
| 1897 | in_srs_wkt=self.in_srs_wkt,
|
|---|
| 1898 | out_geo_trans=self.out_gt,
|
|---|
| 1899 | ominy=self.ominy,
|
|---|
| 1900 | is_epsg_4326=self.isepsg4326,
|
|---|
| 1901 | options=self.options,
|
|---|
| 1902 | exclude_transparent=self.options.exclude_transparent,
|
|---|
| 1903 | )
|
|---|
| 1904 |
|
|---|
| 1905 | return conf, tile_details
|
|---|
| 1906 |
|
|---|
| 1907 | def geo_query(self, ds, ulx, uly, lrx, lry, querysize=0):
|
|---|
| 1908 | """
|
|---|
| 1909 | For given dataset and query in cartographic coordinates returns parameters for ReadRaster()
|
|---|
| 1910 | in raster coordinates and x/y shifts (for border tiles). If the querysize is not given, the
|
|---|
| 1911 | extent is returned in the native resolution of dataset ds.
|
|---|
| 1912 |
|
|---|
| 1913 | raises Gdal2TilesError if the dataset does not contain anything inside this geo_query
|
|---|
| 1914 | """
|
|---|
| 1915 | geotran = ds.GetGeoTransform()
|
|---|
| 1916 | rx = int((ulx - geotran[0]) / geotran[1] + 0.001)
|
|---|
| 1917 | ry = int((uly - geotran[3]) / geotran[5] + 0.001)
|
|---|
| 1918 | rxsize = int((lrx - ulx) / geotran[1] + 0.5)
|
|---|
| 1919 | rysize = int((lry - uly) / geotran[5] + 0.5)
|
|---|
| 1920 |
|
|---|
| 1921 | if not querysize:
|
|---|
| 1922 | wxsize, wysize = rxsize, rysize
|
|---|
| 1923 | else:
|
|---|
| 1924 | wxsize, wysize = querysize, querysize
|
|---|
| 1925 |
|
|---|
| 1926 | # Coordinates should not go out of the bounds of the raster
|
|---|
| 1927 | wx = 0
|
|---|
| 1928 | if rx < 0:
|
|---|
| 1929 | rxshift = abs(rx)
|
|---|
| 1930 | wx = int(wxsize * (float(rxshift) / rxsize))
|
|---|
| 1931 | wxsize = wxsize - wx
|
|---|
| 1932 | rxsize = rxsize - int(rxsize * (float(rxshift) / rxsize))
|
|---|
| 1933 | rx = 0
|
|---|
| 1934 | if rx + rxsize > ds.RasterXSize:
|
|---|
| 1935 | wxsize = int(wxsize * (float(ds.RasterXSize - rx) / rxsize))
|
|---|
| 1936 | rxsize = ds.RasterXSize - rx
|
|---|
| 1937 |
|
|---|
| 1938 | wy = 0
|
|---|
| 1939 | if ry < 0:
|
|---|
| 1940 | ryshift = abs(ry)
|
|---|
| 1941 | wy = int(wysize * (float(ryshift) / rysize))
|
|---|
| 1942 | wysize = wysize - wy
|
|---|
| 1943 | rysize = rysize - int(rysize * (float(ryshift) / rysize))
|
|---|
| 1944 | ry = 0
|
|---|
| 1945 | if ry + rysize > ds.RasterYSize:
|
|---|
| 1946 | wysize = int(wysize * (float(ds.RasterYSize - ry) / rysize))
|
|---|
| 1947 | rysize = ds.RasterYSize - ry
|
|---|
| 1948 |
|
|---|
| 1949 | return (rx, ry, rxsize, rysize), (wx, wy, wxsize, wysize)
|
|---|
| 1950 |
|
|---|
| 1951 | def generate_tilemapresource(self):
|
|---|
| 1952 | """
|
|---|
| 1953 | Template for tilemapresource.xml. Returns filled string. Expected variables:
|
|---|
| 1954 | title, north, south, east, west, isepsg4326, projection, publishurl,
|
|---|
| 1955 | zoompixels, tile_size, tileformat, profile
|
|---|
| 1956 | """
|
|---|
| 1957 |
|
|---|
| 1958 | args = {}
|
|---|
| 1959 | args['title'] = self.options.title
|
|---|
| 1960 | args['south'], args['west'], args['north'], args['east'] = self.swne
|
|---|
| 1961 | args['tile_size'] = self.tile_size
|
|---|
| 1962 | args['tileformat'] = self.tileext
|
|---|
| 1963 | args['publishurl'] = self.options.url
|
|---|
| 1964 | args['profile'] = self.options.profile
|
|---|
| 1965 |
|
|---|
| 1966 | if self.options.profile == 'mercator':
|
|---|
| 1967 | args['srs'] = "EPSG:3857"
|
|---|
| 1968 | elif self.options.profile == 'geodetic':
|
|---|
| 1969 | args['srs'] = "EPSG:4326"
|
|---|
| 1970 | elif self.options.s_srs:
|
|---|
| 1971 | args['srs'] = self.options.s_srs
|
|---|
| 1972 | elif self.out_srs:
|
|---|
| 1973 | args['srs'] = self.out_srs.ExportToWkt()
|
|---|
| 1974 | else:
|
|---|
| 1975 | args['srs'] = ""
|
|---|
| 1976 |
|
|---|
| 1977 | s = """<?xml version="1.0" encoding="utf-8"?>
|
|---|
| 1978 | <TileMap version="1.0.0" tilemapservice="http://tms.osgeo.org/1.0.0">
|
|---|
| 1979 | <Title>%(title)s</Title>
|
|---|
| 1980 | <Abstract></Abstract>
|
|---|
| 1981 | <SRS>%(srs)s</SRS>
|
|---|
| 1982 | <BoundingBox minx="%(west).14f" miny="%(south).14f" maxx="%(east).14f" maxy="%(north).14f"/>
|
|---|
| 1983 | <Origin x="%(west).14f" y="%(south).14f"/>
|
|---|
| 1984 | <TileFormat width="%(tile_size)d" height="%(tile_size)d" mime-type="image/%(tileformat)s" extension="%(tileformat)s"/>
|
|---|
| 1985 | <TileSets profile="%(profile)s">
|
|---|
| 1986 | """ % args # noqa
|
|---|
| 1987 | for z in range(self.tminz, self.tmaxz + 1):
|
|---|
| 1988 | if self.options.profile == 'raster':
|
|---|
| 1989 | s += """ <TileSet href="%s%d" units-per-pixel="%.14f" order="%d"/>\n""" % (
|
|---|
| 1990 | args['publishurl'], z, (2**(self.nativezoom - z) * self.out_gt[1]), z)
|
|---|
| 1991 | elif self.options.profile == 'mercator':
|
|---|
| 1992 | s += """ <TileSet href="%s%d" units-per-pixel="%.14f" order="%d"/>\n""" % (
|
|---|
| 1993 | args['publishurl'], z, 156543.0339 / 2**z, z)
|
|---|
| 1994 | elif self.options.profile == 'geodetic':
|
|---|
| 1995 | s += """ <TileSet href="%s%d" units-per-pixel="%.14f" order="%d"/>\n""" % (
|
|---|
| 1996 | args['publishurl'], z, 0.703125 / 2**z, z)
|
|---|
| 1997 | s += """ </TileSets>
|
|---|
| 1998 | </TileMap>
|
|---|
| 1999 | """
|
|---|
| 2000 | return s
|
|---|
| 2001 |
|
|---|
| 2002 | def generate_googlemaps(self):
|
|---|
| 2003 | """
|
|---|
| 2004 | Template for googlemaps.html implementing Overlay of tiles for 'mercator' profile.
|
|---|
| 2005 | It returns filled string. Expected variables:
|
|---|
| 2006 | title, googlemapskey, north, south, east, west, minzoom, maxzoom, tile_size, tileformat,
|
|---|
| 2007 | publishurl
|
|---|
| 2008 | """
|
|---|
| 2009 | args = {}
|
|---|
| 2010 | args['title'] = self.options.title
|
|---|
| 2011 | args['googlemapskey'] = self.options.googlekey
|
|---|
| 2012 | args['south'], args['west'], args['north'], args['east'] = self.swne
|
|---|
| 2013 | args['minzoom'] = self.tminz
|
|---|
| 2014 | args['maxzoom'] = self.tmaxz
|
|---|
| 2015 | args['tile_size'] = self.tile_size
|
|---|
| 2016 | args['tileformat'] = self.tileext
|
|---|
| 2017 | args['publishurl'] = self.options.url
|
|---|
| 2018 | args['copyright'] = self.options.copyright
|
|---|
| 2019 |
|
|---|
| 2020 | s = r"""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
|---|
| 2021 | <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
|
|---|
| 2022 | <head>
|
|---|
| 2023 | <title>%(title)s</title>
|
|---|
| 2024 | <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
|
|---|
| 2025 | <meta http-equiv='imagetoolbar' content='no'/>
|
|---|
| 2026 | <style type="text/css"> v\:* {behavior:url(#default#VML);}
|
|---|
| 2027 | html, body { overflow: hidden; padding: 0; height: 100%%; width: 100%%; font-family: 'Lucida Grande',Geneva,Arial,Verdana,sans-serif; }
|
|---|
| 2028 | body { margin: 10px; background: #fff; }
|
|---|
| 2029 | h1 { margin: 0; padding: 6px; border:0; font-size: 20pt; }
|
|---|
| 2030 | #header { height: 43px; padding: 0; background-color: #eee; border: 1px solid #888; }
|
|---|
| 2031 | #subheader { height: 12px; text-align: right; font-size: 10px; color: #555;}
|
|---|
| 2032 | #map { height: 95%%; border: 1px solid #888; }
|
|---|
| 2033 | </style>
|
|---|
| 2034 | <script src='http://maps.google.com/maps?file=api&v=2&key=%(googlemapskey)s'></script>
|
|---|
| 2035 | <script>
|
|---|
| 2036 | //<![CDATA[
|
|---|
| 2037 |
|
|---|
| 2038 | /*
|
|---|
| 2039 | * Constants for given map
|
|---|
| 2040 | * TODO: read it from tilemapresource.xml
|
|---|
| 2041 | */
|
|---|
| 2042 |
|
|---|
| 2043 | var mapBounds = new GLatLngBounds(new GLatLng(%(south)s, %(west)s), new GLatLng(%(north)s, %(east)s));
|
|---|
| 2044 | var mapMinZoom = %(minzoom)s;
|
|---|
| 2045 | var mapMaxZoom = %(maxzoom)s;
|
|---|
| 2046 |
|
|---|
| 2047 | var opacity = 0.75;
|
|---|
| 2048 | var map;
|
|---|
| 2049 | var hybridOverlay;
|
|---|
| 2050 |
|
|---|
| 2051 | /*
|
|---|
| 2052 | * Create a Custom Opacity GControl
|
|---|
| 2053 | * http://www.maptiler.org/google-maps-overlay-opacity-control/
|
|---|
| 2054 | */
|
|---|
| 2055 |
|
|---|
| 2056 | var CTransparencyLENGTH = 58;
|
|---|
| 2057 | // maximum width that the knob can move (slide width minus knob width)
|
|---|
| 2058 |
|
|---|
| 2059 | function CTransparencyControl( overlay ) {
|
|---|
| 2060 | this.overlay = overlay;
|
|---|
| 2061 | this.opacity = overlay.getTileLayer().getOpacity();
|
|---|
| 2062 | }
|
|---|
| 2063 | CTransparencyControl.prototype = new GControl();
|
|---|
| 2064 |
|
|---|
| 2065 | // This function positions the slider to match the specified opacity
|
|---|
| 2066 | CTransparencyControl.prototype.setSlider = function(pos) {
|
|---|
| 2067 | var left = Math.round((CTransparencyLENGTH*pos));
|
|---|
| 2068 | this.slide.left = left;
|
|---|
| 2069 | this.knob.style.left = left+"px";
|
|---|
| 2070 | this.knob.style.top = "0px";
|
|---|
| 2071 | }
|
|---|
| 2072 |
|
|---|
| 2073 | // This function reads the slider and sets the overlay opacity level
|
|---|
| 2074 | CTransparencyControl.prototype.setOpacity = function() {
|
|---|
| 2075 | // set the global variable
|
|---|
| 2076 | opacity = this.slide.left/CTransparencyLENGTH;
|
|---|
| 2077 | this.map.clearOverlays();
|
|---|
| 2078 | this.map.addOverlay(this.overlay, { zPriority: 0 });
|
|---|
| 2079 | if (this.map.getCurrentMapType() == G_HYBRID_MAP) {
|
|---|
| 2080 | this.map.addOverlay(hybridOverlay);
|
|---|
| 2081 | }
|
|---|
| 2082 | }
|
|---|
| 2083 |
|
|---|
| 2084 | // This gets called by the API when addControl(new CTransparencyControl())
|
|---|
| 2085 | CTransparencyControl.prototype.initialize = function(map) {
|
|---|
| 2086 | var that=this;
|
|---|
| 2087 | this.map = map;
|
|---|
| 2088 |
|
|---|
| 2089 | // Is this MSIE, if so we need to use AlphaImageLoader
|
|---|
| 2090 | var agent = navigator.userAgent.toLowerCase();
|
|---|
| 2091 | if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){this.ie = true} else {this.ie = false}
|
|---|
| 2092 |
|
|---|
| 2093 | // create the background graphic as a <div> containing an image
|
|---|
| 2094 | var container = document.createElement("div");
|
|---|
| 2095 | container.style.width="70px";
|
|---|
| 2096 | container.style.height="21px";
|
|---|
| 2097 |
|
|---|
| 2098 | // Handle transparent PNG files in MSIE
|
|---|
| 2099 | if (this.ie) {
|
|---|
| 2100 | var loader = "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://www.maptiler.org/img/opacity-slider.png', sizingMethod='crop');";
|
|---|
| 2101 | container.innerHTML = '<div style="height:21px; width:70px; ' +loader+ '" ></div>';
|
|---|
| 2102 | } else {
|
|---|
| 2103 | container.innerHTML = '<div style="height:21px; width:70px; background-image: url(http://www.maptiler.org/img/opacity-slider.png)" ></div>';
|
|---|
| 2104 | }
|
|---|
| 2105 |
|
|---|
| 2106 | // create the knob as a GDraggableObject
|
|---|
| 2107 | // Handle transparent PNG files in MSIE
|
|---|
| 2108 | if (this.ie) {
|
|---|
| 2109 | var loader = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://www.maptiler.org/img/opacity-slider.png', sizingMethod='crop');";
|
|---|
| 2110 | this.knob = document.createElement("div");
|
|---|
| 2111 | this.knob.style.height="21px";
|
|---|
| 2112 | this.knob.style.width="13px";
|
|---|
| 2113 | this.knob.style.overflow="hidden";
|
|---|
| 2114 | this.knob_img = document.createElement("div");
|
|---|
| 2115 | this.knob_img.style.height="21px";
|
|---|
| 2116 | this.knob_img.style.width="83px";
|
|---|
| 2117 | this.knob_img.style.filter=loader;
|
|---|
| 2118 | this.knob_img.style.position="relative";
|
|---|
| 2119 | this.knob_img.style.left="-70px";
|
|---|
| 2120 | this.knob.appendChild(this.knob_img);
|
|---|
| 2121 | } else {
|
|---|
| 2122 | this.knob = document.createElement("div");
|
|---|
| 2123 | this.knob.style.height="21px";
|
|---|
| 2124 | this.knob.style.width="13px";
|
|---|
| 2125 | this.knob.style.backgroundImage="url(http://www.maptiler.org/img/opacity-slider.png)";
|
|---|
| 2126 | this.knob.style.backgroundPosition="-70px 0px";
|
|---|
| 2127 | }
|
|---|
| 2128 | container.appendChild(this.knob);
|
|---|
| 2129 | this.slide=new GDraggableObject(this.knob, {container:container});
|
|---|
| 2130 | this.slide.setDraggableCursor('pointer');
|
|---|
| 2131 | this.slide.setDraggingCursor('pointer');
|
|---|
| 2132 | this.container = container;
|
|---|
| 2133 |
|
|---|
| 2134 | // attach the control to the map
|
|---|
| 2135 | map.getContainer().appendChild(container);
|
|---|
| 2136 |
|
|---|
| 2137 | // init slider
|
|---|
| 2138 | this.setSlider(this.opacity);
|
|---|
| 2139 |
|
|---|
| 2140 | // Listen for the slider being moved and set the opacity
|
|---|
| 2141 | GEvent.addListener(this.slide, "dragend", function() {that.setOpacity()});
|
|---|
| 2142 | //GEvent.addListener(this.container, "click", function( x, y ) { alert(x, y) });
|
|---|
| 2143 |
|
|---|
| 2144 | return container;
|
|---|
| 2145 | }
|
|---|
| 2146 |
|
|---|
| 2147 | // Set the default position for the control
|
|---|
| 2148 | CTransparencyControl.prototype.getDefaultPosition = function() {
|
|---|
| 2149 | return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 47));
|
|---|
| 2150 | }
|
|---|
| 2151 |
|
|---|
| 2152 | /*
|
|---|
| 2153 | * Full-screen Window Resize
|
|---|
| 2154 | */
|
|---|
| 2155 |
|
|---|
| 2156 | function getWindowHeight() {
|
|---|
| 2157 | if (self.innerHeight) return self.innerHeight;
|
|---|
| 2158 | if (document.documentElement && document.documentElement.clientHeight)
|
|---|
| 2159 | return document.documentElement.clientHeight;
|
|---|
| 2160 | if (document.body) return document.body.clientHeight;
|
|---|
| 2161 | return 0;
|
|---|
| 2162 | }
|
|---|
| 2163 |
|
|---|
| 2164 | function getWindowWidth() {
|
|---|
| 2165 | if (self.innerWidth) return self.innerWidth;
|
|---|
| 2166 | if (document.documentElement && document.documentElement.clientWidth)
|
|---|
| 2167 | return document.documentElement.clientWidth;
|
|---|
| 2168 | if (document.body) return document.body.clientWidth;
|
|---|
| 2169 | return 0;
|
|---|
| 2170 | }
|
|---|
| 2171 |
|
|---|
| 2172 | function resize() {
|
|---|
| 2173 | var map = document.getElementById("map");
|
|---|
| 2174 | var header = document.getElementById("header");
|
|---|
| 2175 | var subheader = document.getElementById("subheader");
|
|---|
| 2176 | map.style.height = (getWindowHeight()-80) + "px";
|
|---|
| 2177 | map.style.width = (getWindowWidth()-20) + "px";
|
|---|
| 2178 | header.style.width = (getWindowWidth()-20) + "px";
|
|---|
| 2179 | subheader.style.width = (getWindowWidth()-20) + "px";
|
|---|
| 2180 | // map.checkResize();
|
|---|
| 2181 | }
|
|---|
| 2182 |
|
|---|
| 2183 |
|
|---|
| 2184 | /*
|
|---|
| 2185 | * Main load function:
|
|---|
| 2186 | */
|
|---|
| 2187 |
|
|---|
| 2188 | function load() {
|
|---|
| 2189 |
|
|---|
| 2190 | if (GBrowserIsCompatible()) {
|
|---|
| 2191 |
|
|---|
| 2192 | // Bug in the Google Maps: Copyright for Overlay is not correctly displayed
|
|---|
| 2193 | var gcr = GMapType.prototype.getCopyrights;
|
|---|
| 2194 | GMapType.prototype.getCopyrights = function(bounds,zoom) {
|
|---|
| 2195 | return ["%(copyright)s"].concat(gcr.call(this,bounds,zoom));
|
|---|
| 2196 | }
|
|---|
| 2197 |
|
|---|
| 2198 | map = new GMap2( document.getElementById("map"), { backgroundColor: '#fff' } );
|
|---|
| 2199 |
|
|---|
| 2200 | map.addMapType(G_PHYSICAL_MAP);
|
|---|
| 2201 | map.setMapType(G_PHYSICAL_MAP);
|
|---|
| 2202 |
|
|---|
| 2203 | map.setCenter( mapBounds.getCenter(), map.getBoundsZoomLevel( mapBounds ));
|
|---|
| 2204 |
|
|---|
| 2205 | hybridOverlay = new GTileLayerOverlay( G_HYBRID_MAP.getTileLayers()[1] );
|
|---|
| 2206 | GEvent.addListener(map, "maptypechanged", function() {
|
|---|
| 2207 | if (map.getCurrentMapType() == G_HYBRID_MAP) {
|
|---|
| 2208 | map.addOverlay(hybridOverlay);
|
|---|
| 2209 | } else {
|
|---|
| 2210 | map.removeOverlay(hybridOverlay);
|
|---|
| 2211 | }
|
|---|
| 2212 | } );
|
|---|
| 2213 |
|
|---|
| 2214 | var tilelayer = new GTileLayer(GCopyrightCollection(''), mapMinZoom, mapMaxZoom);
|
|---|
| 2215 | var mercator = new GMercatorProjection(mapMaxZoom+1);
|
|---|
| 2216 | tilelayer.getTileUrl = function(tile,zoom) {
|
|---|
| 2217 | if ((zoom < mapMinZoom) || (zoom > mapMaxZoom)) {
|
|---|
| 2218 | return "http://www.maptiler.org/img/none.png";
|
|---|
| 2219 | }
|
|---|
| 2220 | var ymax = 1 << zoom;
|
|---|
| 2221 | var y = ymax - tile.y -1;
|
|---|
| 2222 | var tileBounds = new GLatLngBounds(
|
|---|
| 2223 | mercator.fromPixelToLatLng( new GPoint( (tile.x)*256, (tile.y+1)*256 ) , zoom ),
|
|---|
| 2224 | mercator.fromPixelToLatLng( new GPoint( (tile.x+1)*256, (tile.y)*256 ) , zoom )
|
|---|
| 2225 | );
|
|---|
| 2226 | if (mapBounds.intersects(tileBounds)) {
|
|---|
| 2227 | return zoom+"/"+tile.x+"/"+y+".png";
|
|---|
| 2228 | } else {
|
|---|
| 2229 | return "http://www.maptiler.org/img/none.png";
|
|---|
| 2230 | }
|
|---|
| 2231 | }
|
|---|
| 2232 | // IE 7-: support for PNG alpha channel
|
|---|
| 2233 | // Unfortunately, the opacity for whole overlay is then not changeable, either or...
|
|---|
| 2234 | tilelayer.isPng = function() { return true;};
|
|---|
| 2235 | tilelayer.getOpacity = function() { return opacity; }
|
|---|
| 2236 |
|
|---|
| 2237 | overlay = new GTileLayerOverlay( tilelayer );
|
|---|
| 2238 | map.addOverlay(overlay);
|
|---|
| 2239 |
|
|---|
| 2240 | map.addControl(new GLargeMapControl());
|
|---|
| 2241 | map.addControl(new GHierarchicalMapTypeControl());
|
|---|
| 2242 | map.addControl(new CTransparencyControl( overlay ));
|
|---|
| 2243 | """ % args # noqa
|
|---|
| 2244 | if self.kml:
|
|---|
| 2245 | s += """
|
|---|
| 2246 | map.addMapType(G_SATELLITE_3D_MAP);
|
|---|
| 2247 | map.getEarthInstance(getEarthInstanceCB);
|
|---|
| 2248 | """
|
|---|
| 2249 | s += """
|
|---|
| 2250 |
|
|---|
| 2251 | map.enableContinuousZoom();
|
|---|
| 2252 | map.enableScrollWheelZoom();
|
|---|
| 2253 |
|
|---|
| 2254 | map.setMapType(G_HYBRID_MAP);
|
|---|
| 2255 | }
|
|---|
| 2256 | resize();
|
|---|
| 2257 | }
|
|---|
| 2258 | """
|
|---|
| 2259 | if self.kml:
|
|---|
| 2260 | s += """
|
|---|
| 2261 | function getEarthInstanceCB(object) {
|
|---|
| 2262 | var ge = object;
|
|---|
| 2263 |
|
|---|
| 2264 | if (ge) {
|
|---|
| 2265 | var url = document.location.toString();
|
|---|
| 2266 | url = url.substr(0,url.lastIndexOf('/'))+'/doc.kml';
|
|---|
| 2267 | var link = ge.createLink("");
|
|---|
| 2268 | if ("%(publishurl)s") { link.setHref("%(publishurl)s/doc.kml") }
|
|---|
| 2269 | else { link.setHref(url) };
|
|---|
| 2270 | var networkLink = ge.createNetworkLink("");
|
|---|
| 2271 | networkLink.setName("TMS Map Overlay");
|
|---|
| 2272 | networkLink.setFlyToView(true);
|
|---|
| 2273 | networkLink.setLink(link);
|
|---|
| 2274 | ge.getFeatures().appendChild(networkLink);
|
|---|
| 2275 | } else {
|
|---|
| 2276 | // alert("You should open a KML in Google Earth");
|
|---|
| 2277 | // add div with the link to generated KML... - maybe JavaScript redirect to the URL of KML?
|
|---|
| 2278 | }
|
|---|
| 2279 | }
|
|---|
| 2280 | """ % args # noqa
|
|---|
| 2281 | s += """
|
|---|
| 2282 | onresize=function(){ resize(); };
|
|---|
| 2283 |
|
|---|
| 2284 | //]]>
|
|---|
| 2285 | </script>
|
|---|
| 2286 | </head>
|
|---|
| 2287 | <body onload="load()">
|
|---|
| 2288 | <div id="header"><h1>%(title)s</h1></div>
|
|---|
| 2289 | <div id="subheader">Generated by <a href="http://www.klokan.cz/projects/gdal2tiles/">GDAL2Tiles</a>, Copyright © 2008 <a href="http://www.klokan.cz/">Klokan Petr Pridal</a>, <a href="http://www.gdal.org/">GDAL</a> & <a href="http://www.osgeo.org/">OSGeo</a> <a href="http://code.google.com/soc/">GSoC</a>
|
|---|
| 2290 | <!-- PLEASE, LET THIS NOTE ABOUT AUTHOR AND PROJECT SOMEWHERE ON YOUR WEBSITE, OR AT LEAST IN THE COMMENT IN HTML. THANK YOU -->
|
|---|
| 2291 | </div>
|
|---|
| 2292 | <div id="map"></div>
|
|---|
| 2293 | </body>
|
|---|
| 2294 | </html>
|
|---|
| 2295 | """ % args # noqa
|
|---|
| 2296 |
|
|---|
| 2297 | return s
|
|---|
| 2298 |
|
|---|
| 2299 | def generate_leaflet(self):
|
|---|
| 2300 | """
|
|---|
| 2301 | Template for leaflet.html implementing overlay of tiles for 'mercator' profile.
|
|---|
| 2302 | It returns filled string. Expected variables:
|
|---|
| 2303 | title, north, south, east, west, minzoom, maxzoom, tile_size, tileformat, publishurl
|
|---|
| 2304 | """
|
|---|
| 2305 |
|
|---|
| 2306 | args = {}
|
|---|
| 2307 | args['title'] = self.options.title.replace('"', '\\"')
|
|---|
| 2308 | args['htmltitle'] = self.options.title
|
|---|
| 2309 | args['south'], args['west'], args['north'], args['east'] = self.swne
|
|---|
| 2310 | args['centerlon'] = (args['north'] + args['south']) / 2.
|
|---|
| 2311 | args['centerlat'] = (args['west'] + args['east']) / 2.
|
|---|
| 2312 | args['minzoom'] = self.tminz
|
|---|
| 2313 | args['maxzoom'] = self.tmaxz
|
|---|
| 2314 | args['beginzoom'] = self.tmaxz
|
|---|
| 2315 | args['tile_size'] = self.tile_size # not used
|
|---|
| 2316 | args['tileformat'] = self.tileext
|
|---|
| 2317 | args['publishurl'] = self.options.url # not used
|
|---|
| 2318 | args['copyright'] = self.options.copyright.replace('"', '\\"')
|
|---|
| 2319 |
|
|---|
| 2320 | s = """<!DOCTYPE html>
|
|---|
| 2321 | <html lang="en">
|
|---|
| 2322 | <head>
|
|---|
| 2323 | <meta charset="utf-8">
|
|---|
| 2324 | <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' />
|
|---|
| 2325 | <title>%(htmltitle)s</title>
|
|---|
| 2326 |
|
|---|
| 2327 | <!-- Leaflet -->
|
|---|
| 2328 | <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.css" />
|
|---|
| 2329 | <script src="http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.js"></script>
|
|---|
| 2330 |
|
|---|
| 2331 | <style>
|
|---|
| 2332 | body { margin:0; padding:0; }
|
|---|
| 2333 | body, table, tr, td, th, div, h1, h2, input { font-family: "Calibri", "Trebuchet MS", "Ubuntu", Serif; font-size: 11pt; }
|
|---|
| 2334 | #map { position:absolute; top:0; bottom:0; width:100%%; } /* full size */
|
|---|
| 2335 | .ctl {
|
|---|
| 2336 | padding: 2px 10px 2px 10px;
|
|---|
| 2337 | background: white;
|
|---|
| 2338 | background: rgba(255,255,255,0.9);
|
|---|
| 2339 | box-shadow: 0 0 15px rgba(0,0,0,0.2);
|
|---|
| 2340 | border-radius: 5px;
|
|---|
| 2341 | text-align: right;
|
|---|
| 2342 | }
|
|---|
| 2343 | .title {
|
|---|
| 2344 | font-size: 18pt;
|
|---|
| 2345 | font-weight: bold;
|
|---|
| 2346 | }
|
|---|
| 2347 | .src {
|
|---|
| 2348 | font-size: 10pt;
|
|---|
| 2349 | }
|
|---|
| 2350 |
|
|---|
| 2351 | </style>
|
|---|
| 2352 |
|
|---|
| 2353 | </head>
|
|---|
| 2354 | <body>
|
|---|
| 2355 |
|
|---|
| 2356 | <div id="map"></div>
|
|---|
| 2357 |
|
|---|
| 2358 | <script>
|
|---|
| 2359 | /* **** Leaflet **** */
|
|---|
| 2360 |
|
|---|
| 2361 | // Base layers
|
|---|
| 2362 | // .. OpenStreetMap
|
|---|
| 2363 | var osm = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors', minZoom: %(minzoom)s, maxZoom: %(maxzoom)s});
|
|---|
| 2364 |
|
|---|
| 2365 | // .. CartoDB Positron
|
|---|
| 2366 | var cartodb = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, © <a href="http://cartodb.com/attributions">CartoDB</a>', minZoom: %(minzoom)s, maxZoom: %(maxzoom)s});
|
|---|
| 2367 |
|
|---|
| 2368 | // .. OSM Toner
|
|---|
| 2369 | var toner = L.tileLayer('http://{s}.tile.stamen.com/toner/{z}/{x}/{y}.png', {attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://www.openstreetmap.org/copyright">ODbL</a>.', minZoom: %(minzoom)s, maxZoom: %(maxzoom)s});
|
|---|
| 2370 |
|
|---|
| 2371 | // .. White background
|
|---|
| 2372 | var white = L.tileLayer("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEAAQMAAABmvDolAAAAA1BMVEX///+nxBvIAAAAH0lEQVQYGe3BAQ0AAADCIPunfg43YAAAAAAAAAAA5wIhAAAB9aK9BAAAAABJRU5ErkJggg==", {minZoom: %(minzoom)s, maxZoom: %(maxzoom)s});
|
|---|
| 2373 |
|
|---|
| 2374 | // Overlay layers (TMS)
|
|---|
| 2375 | var lyr = L.tileLayer('./{z}/{x}/{y}.%(tileformat)s', {tms: true, opacity: 0.7, attribution: "%(copyright)s", minZoom: %(minzoom)s, maxZoom: %(maxzoom)s});
|
|---|
| 2376 |
|
|---|
| 2377 | // Map
|
|---|
| 2378 | var map = L.map('map', {
|
|---|
| 2379 | center: [%(centerlon)s, %(centerlat)s],
|
|---|
| 2380 | zoom: %(beginzoom)s,
|
|---|
| 2381 | minZoom: %(minzoom)s,
|
|---|
| 2382 | maxZoom: %(maxzoom)s,
|
|---|
| 2383 | layers: [osm]
|
|---|
| 2384 | });
|
|---|
| 2385 |
|
|---|
| 2386 | var basemaps = {"OpenStreetMap": osm, "CartoDB Positron": cartodb, "Stamen Toner": toner, "Without background": white}
|
|---|
| 2387 | var overlaymaps = {"Layer": lyr}
|
|---|
| 2388 |
|
|---|
| 2389 | // Title
|
|---|
| 2390 | var title = L.control();
|
|---|
| 2391 | title.onAdd = function(map) {
|
|---|
| 2392 | this._div = L.DomUtil.create('div', 'ctl title');
|
|---|
| 2393 | this.update();
|
|---|
| 2394 | return this._div;
|
|---|
| 2395 | };
|
|---|
| 2396 | title.update = function(props) {
|
|---|
| 2397 | this._div.innerHTML = "%(title)s";
|
|---|
| 2398 | };
|
|---|
| 2399 | title.addTo(map);
|
|---|
| 2400 |
|
|---|
| 2401 | // Note
|
|---|
| 2402 | var src = 'Generated by <a href="http://www.klokan.cz/projects/gdal2tiles/">GDAL2Tiles</a>, Copyright © 2008 <a href="http://www.klokan.cz/">Klokan Petr Pridal</a>, <a href="http://www.gdal.org/">GDAL</a> & <a href="http://www.osgeo.org/">OSGeo</a> <a href="http://code.google.com/soc/">GSoC</a>';
|
|---|
| 2403 | var title = L.control({position: 'bottomleft'});
|
|---|
| 2404 | title.onAdd = function(map) {
|
|---|
| 2405 | this._div = L.DomUtil.create('div', 'ctl src');
|
|---|
| 2406 | this.update();
|
|---|
| 2407 | return this._div;
|
|---|
| 2408 | };
|
|---|
| 2409 | title.update = function(props) {
|
|---|
| 2410 | this._div.innerHTML = src;
|
|---|
| 2411 | };
|
|---|
| 2412 | title.addTo(map);
|
|---|
| 2413 |
|
|---|
| 2414 |
|
|---|
| 2415 | // Add base layers
|
|---|
| 2416 | L.control.layers(basemaps, overlaymaps, {collapsed: false}).addTo(map);
|
|---|
| 2417 |
|
|---|
| 2418 | // Fit to overlay bounds (SW and NE points with (lat, lon))
|
|---|
| 2419 | map.fitBounds([[%(south)s, %(east)s], [%(north)s, %(west)s]]);
|
|---|
| 2420 |
|
|---|
| 2421 | </script>
|
|---|
| 2422 |
|
|---|
| 2423 | </body>
|
|---|
| 2424 | </html>
|
|---|
| 2425 |
|
|---|
| 2426 | """ % args # noqa
|
|---|
| 2427 |
|
|---|
| 2428 | return s
|
|---|
| 2429 |
|
|---|
| 2430 | def generate_openlayers(self):
|
|---|
| 2431 | """
|
|---|
| 2432 | Template for openlayers.html implementing overlay of available Spherical Mercator layers.
|
|---|
| 2433 |
|
|---|
| 2434 | It returns filled string. Expected variables:
|
|---|
| 2435 | title, bingkey, north, south, east, west, minzoom, maxzoom, tile_size, tileformat, publishurl
|
|---|
| 2436 | """
|
|---|
| 2437 |
|
|---|
| 2438 | args = {}
|
|---|
| 2439 | args['title'] = self.options.title
|
|---|
| 2440 | args['bingkey'] = self.options.bingkey
|
|---|
| 2441 | args['south'], args['west'], args['north'], args['east'] = self.swne
|
|---|
| 2442 | args['minzoom'] = self.tminz
|
|---|
| 2443 | args['maxzoom'] = self.tmaxz
|
|---|
| 2444 | args['tile_size'] = self.tile_size
|
|---|
| 2445 | args['tileformat'] = self.tileext
|
|---|
| 2446 | args['publishurl'] = self.options.url
|
|---|
| 2447 | args['copyright'] = self.options.copyright
|
|---|
| 2448 | if self.options.tmscompatible:
|
|---|
| 2449 | args['tmsoffset'] = "-1"
|
|---|
| 2450 | else:
|
|---|
| 2451 | args['tmsoffset'] = ""
|
|---|
| 2452 | if self.options.profile == 'raster':
|
|---|
| 2453 | args['rasterzoomlevels'] = self.tmaxz + 1
|
|---|
| 2454 | args['rastermaxresolution'] = 2**(self.nativezoom) * self.out_gt[1]
|
|---|
| 2455 |
|
|---|
| 2456 | s = r"""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
|---|
| 2457 | <html xmlns="http://www.w3.org/1999/xhtml"
|
|---|
| 2458 | <head>
|
|---|
| 2459 | <title>%(title)s</title>
|
|---|
| 2460 | <meta http-equiv='imagetoolbar' content='no'/>
|
|---|
| 2461 | <style type="text/css"> v\:* {behavior:url(#default#VML);}
|
|---|
| 2462 | html, body { overflow: hidden; padding: 0; height: 100%%; width: 100%%; font-family: 'Lucida Grande',Geneva,Arial,Verdana,sans-serif; }
|
|---|
| 2463 | body { margin: 10px; background: #fff; }
|
|---|
| 2464 | h1 { margin: 0; padding: 6px; border:0; font-size: 20pt; }
|
|---|
| 2465 | #header { height: 43px; padding: 0; background-color: #eee; border: 1px solid #888; }
|
|---|
| 2466 | #subheader { height: 12px; text-align: right; font-size: 10px; color: #555;}
|
|---|
| 2467 | #map { height: 95%%; border: 1px solid #888; }
|
|---|
| 2468 | .olImageLoadError { display: none; }
|
|---|
| 2469 | .olControlLayerSwitcher .layersDiv { border-radius: 10px 0 0 10px; }
|
|---|
| 2470 | </style>""" % args # noqa
|
|---|
| 2471 |
|
|---|
| 2472 | if self.options.profile == 'mercator':
|
|---|
| 2473 | s += """
|
|---|
| 2474 | <script src='http://maps.google.com/maps/api/js?sensor=false&v=3.7'></script>
|
|---|
| 2475 | """ % args
|
|---|
| 2476 |
|
|---|
| 2477 | s += """
|
|---|
| 2478 | <script src="http://www.openlayers.org/api/2.12/OpenLayers.js"></script>
|
|---|
| 2479 | <script>
|
|---|
| 2480 | var map;
|
|---|
| 2481 | var mapBounds = new OpenLayers.Bounds( %(west)s, %(south)s, %(east)s, %(north)s);
|
|---|
| 2482 | var mapMinZoom = %(minzoom)s;
|
|---|
| 2483 | var mapMaxZoom = %(maxzoom)s;
|
|---|
| 2484 | var emptyTileURL = "http://www.maptiler.org/img/none.png";
|
|---|
| 2485 | OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
|
|---|
| 2486 |
|
|---|
| 2487 | function init(){""" % args
|
|---|
| 2488 |
|
|---|
| 2489 | if self.options.profile == 'mercator':
|
|---|
| 2490 | s += """
|
|---|
| 2491 | var options = {
|
|---|
| 2492 | div: "map",
|
|---|
| 2493 | controls: [],
|
|---|
| 2494 | projection: "EPSG:3857",
|
|---|
| 2495 | displayProjection: new OpenLayers.Projection("EPSG:4326"),
|
|---|
| 2496 | numZoomLevels: 20
|
|---|
| 2497 | };
|
|---|
| 2498 | map = new OpenLayers.Map(options);
|
|---|
| 2499 |
|
|---|
| 2500 | // Create Google Mercator layers
|
|---|
| 2501 | var gmap = new OpenLayers.Layer.Google("Google Streets",
|
|---|
| 2502 | {
|
|---|
| 2503 | type: google.maps.MapTypeId.ROADMAP,
|
|---|
| 2504 | sphericalMercator: true
|
|---|
| 2505 | });
|
|---|
| 2506 | var gsat = new OpenLayers.Layer.Google("Google Satellite",
|
|---|
| 2507 | {
|
|---|
| 2508 | type: google.maps.MapTypeId.SATELLITE,
|
|---|
| 2509 | sphericalMercator: true
|
|---|
| 2510 | });
|
|---|
| 2511 | var ghyb = new OpenLayers.Layer.Google("Google Hybrid",
|
|---|
| 2512 | {
|
|---|
| 2513 | type: google.maps.MapTypeId.HYBRID,
|
|---|
| 2514 | sphericalMercator: true
|
|---|
| 2515 | });
|
|---|
| 2516 | var gter = new OpenLayers.Layer.Google("Google Terrain",
|
|---|
| 2517 | {
|
|---|
| 2518 | type: google.maps.MapTypeId.TERRAIN,
|
|---|
| 2519 | sphericalMercator: true
|
|---|
| 2520 | });
|
|---|
| 2521 |
|
|---|
| 2522 | // Create Bing layers
|
|---|
| 2523 | var broad = new OpenLayers.Layer.Bing({
|
|---|
| 2524 | name: "Bing Roads",
|
|---|
| 2525 | key: "%(bingkey)s",
|
|---|
| 2526 | type: "Road",
|
|---|
| 2527 | sphericalMercator: true
|
|---|
| 2528 | });
|
|---|
| 2529 | var baer = new OpenLayers.Layer.Bing({
|
|---|
| 2530 | name: "Bing Aerial",
|
|---|
| 2531 | key: "%(bingkey)s",
|
|---|
| 2532 | type: "Aerial",
|
|---|
| 2533 | sphericalMercator: true
|
|---|
| 2534 | });
|
|---|
| 2535 | var bhyb = new OpenLayers.Layer.Bing({
|
|---|
| 2536 | name: "Bing Hybrid",
|
|---|
| 2537 | key: "%(bingkey)s",
|
|---|
| 2538 | type: "AerialWithLabels",
|
|---|
| 2539 | sphericalMercator: true
|
|---|
| 2540 | });
|
|---|
| 2541 |
|
|---|
| 2542 | // Create OSM layer
|
|---|
| 2543 | var osm = new OpenLayers.Layer.OSM("OpenStreetMap");
|
|---|
| 2544 |
|
|---|
| 2545 | // create TMS Overlay layer
|
|---|
| 2546 | var tmsoverlay = new OpenLayers.Layer.TMS("TMS Overlay", "",
|
|---|
| 2547 | {
|
|---|
| 2548 | serviceVersion: '.',
|
|---|
| 2549 | layername: '.',
|
|---|
| 2550 | alpha: true,
|
|---|
| 2551 | type: '%(tileformat)s',
|
|---|
| 2552 | isBaseLayer: false,
|
|---|
| 2553 | getURL: getURL
|
|---|
| 2554 | });
|
|---|
| 2555 | if (OpenLayers.Util.alphaHack() == false) {
|
|---|
| 2556 | tmsoverlay.setOpacity(0.7);
|
|---|
| 2557 | }
|
|---|
| 2558 |
|
|---|
| 2559 | map.addLayers([gmap, gsat, ghyb, gter,
|
|---|
| 2560 | broad, baer, bhyb,
|
|---|
| 2561 | osm, tmsoverlay]);
|
|---|
| 2562 |
|
|---|
| 2563 | var switcherControl = new OpenLayers.Control.LayerSwitcher();
|
|---|
| 2564 | map.addControl(switcherControl);
|
|---|
| 2565 | switcherControl.maximizeControl();
|
|---|
| 2566 |
|
|---|
| 2567 | map.zoomToExtent(mapBounds.transform(map.displayProjection, map.projection));
|
|---|
| 2568 | """ % args # noqa
|
|---|
| 2569 |
|
|---|
| 2570 | elif self.options.profile == 'geodetic':
|
|---|
| 2571 | s += """
|
|---|
| 2572 | var options = {
|
|---|
| 2573 | div: "map",
|
|---|
| 2574 | controls: [],
|
|---|
| 2575 | projection: "EPSG:4326"
|
|---|
| 2576 | };
|
|---|
| 2577 | map = new OpenLayers.Map(options);
|
|---|
| 2578 |
|
|---|
| 2579 | var wms = new OpenLayers.Layer.WMS("VMap0",
|
|---|
| 2580 | "http://tilecache.osgeo.org/wms-c/Basic.py?",
|
|---|
| 2581 | {
|
|---|
| 2582 | layers: 'basic',
|
|---|
| 2583 | format: 'image/png'
|
|---|
| 2584 | }
|
|---|
| 2585 | );
|
|---|
| 2586 | var tmsoverlay = new OpenLayers.Layer.TMS("TMS Overlay", "",
|
|---|
| 2587 | {
|
|---|
| 2588 | serviceVersion: '.',
|
|---|
| 2589 | layername: '.',
|
|---|
| 2590 | alpha: true,
|
|---|
| 2591 | type: '%(tileformat)s',
|
|---|
| 2592 | isBaseLayer: false,
|
|---|
| 2593 | getURL: getURL
|
|---|
| 2594 | });
|
|---|
| 2595 | if (OpenLayers.Util.alphaHack() == false) {
|
|---|
| 2596 | tmsoverlay.setOpacity(0.7);
|
|---|
| 2597 | }
|
|---|
| 2598 |
|
|---|
| 2599 | map.addLayers([wms,tmsoverlay]);
|
|---|
| 2600 |
|
|---|
| 2601 | var switcherControl = new OpenLayers.Control.LayerSwitcher();
|
|---|
| 2602 | map.addControl(switcherControl);
|
|---|
| 2603 | switcherControl.maximizeControl();
|
|---|
| 2604 |
|
|---|
| 2605 | map.zoomToExtent(mapBounds);
|
|---|
| 2606 | """ % args # noqa
|
|---|
| 2607 |
|
|---|
| 2608 | elif self.options.profile == 'raster':
|
|---|
| 2609 | s += """
|
|---|
| 2610 | var options = {
|
|---|
| 2611 | div: "map",
|
|---|
| 2612 | controls: [],
|
|---|
| 2613 | maxExtent: new OpenLayers.Bounds(%(west)s, %(south)s, %(east)s, %(north)s),
|
|---|
| 2614 | maxResolution: %(rastermaxresolution)f,
|
|---|
| 2615 | numZoomLevels: %(rasterzoomlevels)d
|
|---|
| 2616 | };
|
|---|
| 2617 | map = new OpenLayers.Map(options);
|
|---|
| 2618 |
|
|---|
| 2619 | var layer = new OpenLayers.Layer.TMS("TMS Layer", "",
|
|---|
| 2620 | {
|
|---|
| 2621 | serviceVersion: '.',
|
|---|
| 2622 | layername: '.',
|
|---|
| 2623 | alpha: true,
|
|---|
| 2624 | type: '%(tileformat)s',
|
|---|
| 2625 | getURL: getURL
|
|---|
| 2626 | });
|
|---|
| 2627 |
|
|---|
| 2628 | map.addLayer(layer);
|
|---|
| 2629 | map.zoomToExtent(mapBounds);
|
|---|
| 2630 | """ % args # noqa
|
|---|
| 2631 |
|
|---|
| 2632 | s += """
|
|---|
| 2633 | map.addControls([new OpenLayers.Control.PanZoomBar(),
|
|---|
| 2634 | new OpenLayers.Control.Navigation(),
|
|---|
| 2635 | new OpenLayers.Control.MousePosition(),
|
|---|
| 2636 | new OpenLayers.Control.ArgParser(),
|
|---|
| 2637 | new OpenLayers.Control.Attribution()]);
|
|---|
| 2638 | }
|
|---|
| 2639 | """ % args
|
|---|
| 2640 |
|
|---|
| 2641 | if self.options.profile == 'mercator':
|
|---|
| 2642 | s += """
|
|---|
| 2643 | function getURL(bounds) {
|
|---|
| 2644 | bounds = this.adjustBounds(bounds);
|
|---|
| 2645 | var res = this.getServerResolution();
|
|---|
| 2646 | var x = Math.round((bounds.left - this.tileOrigin.lon) / (res * this.tileSize.w));
|
|---|
| 2647 | var y = Math.round((bounds.bottom - this.tileOrigin.lat) / (res * this.tileSize.h));
|
|---|
| 2648 | var z = this.getServerZoom();
|
|---|
| 2649 | if (this.map.baseLayer.CLASS_NAME === 'OpenLayers.Layer.Bing') {
|
|---|
| 2650 | z+=1;
|
|---|
| 2651 | }
|
|---|
| 2652 | var path = this.serviceVersion + "/" + this.layername + "/" + z + "/" + x + "/" + y + "." + this.type;
|
|---|
| 2653 | var url = this.url;
|
|---|
| 2654 | if (OpenLayers.Util.isArray(url)) {
|
|---|
| 2655 | url = this.selectUrl(path, url);
|
|---|
| 2656 | }
|
|---|
| 2657 | if (mapBounds.intersectsBounds(bounds) && (z >= mapMinZoom) && (z <= mapMaxZoom)) {
|
|---|
| 2658 | return url + path;
|
|---|
| 2659 | } else {
|
|---|
| 2660 | return emptyTileURL;
|
|---|
| 2661 | }
|
|---|
| 2662 | }
|
|---|
| 2663 | """ % args # noqa
|
|---|
| 2664 |
|
|---|
| 2665 | elif self.options.profile == 'geodetic':
|
|---|
| 2666 | s += """
|
|---|
| 2667 | function getURL(bounds) {
|
|---|
| 2668 | bounds = this.adjustBounds(bounds);
|
|---|
| 2669 | var res = this.getServerResolution();
|
|---|
| 2670 | var x = Math.round((bounds.left - this.tileOrigin.lon) / (res * this.tileSize.w));
|
|---|
| 2671 | var y = Math.round((bounds.bottom - this.tileOrigin.lat) / (res * this.tileSize.h));
|
|---|
| 2672 | var z = this.getServerZoom()%(tmsoffset)s;
|
|---|
| 2673 | var path = this.serviceVersion + "/" + this.layername + "/" + z + "/" + x + "/" + y + "." + this.type;
|
|---|
| 2674 | var url = this.url;
|
|---|
| 2675 | if (OpenLayers.Util.isArray(url)) {
|
|---|
| 2676 | url = this.selectUrl(path, url);
|
|---|
| 2677 | }
|
|---|
| 2678 | if (mapBounds.intersectsBounds(bounds) && (z >= mapMinZoom) && (z <= mapMaxZoom)) {
|
|---|
| 2679 | return url + path;
|
|---|
| 2680 | } else {
|
|---|
| 2681 | return emptyTileURL;
|
|---|
| 2682 | }
|
|---|
| 2683 | }
|
|---|
| 2684 | """ % args # noqa
|
|---|
| 2685 |
|
|---|
| 2686 | elif self.options.profile == 'raster':
|
|---|
| 2687 | s += """
|
|---|
| 2688 | function getURL(bounds) {
|
|---|
| 2689 | bounds = this.adjustBounds(bounds);
|
|---|
| 2690 | var res = this.getServerResolution();
|
|---|
| 2691 | var x = Math.round((bounds.left - this.tileOrigin.lon) / (res * this.tileSize.w));
|
|---|
| 2692 | var y = Math.round((bounds.bottom - this.tileOrigin.lat) / (res * this.tileSize.h));
|
|---|
| 2693 | var z = this.getServerZoom();
|
|---|
| 2694 | var path = this.serviceVersion + "/" + this.layername + "/" + z + "/" + x + "/" + y + "." + this.type;
|
|---|
| 2695 | var url = this.url;
|
|---|
| 2696 | if (OpenLayers.Util.isArray(url)) {
|
|---|
| 2697 | url = this.selectUrl(path, url);
|
|---|
| 2698 | }
|
|---|
| 2699 | if (mapBounds.intersectsBounds(bounds) && (z >= mapMinZoom) && (z <= mapMaxZoom)) {
|
|---|
| 2700 | return url + path;
|
|---|
| 2701 | } else {
|
|---|
| 2702 | return emptyTileURL;
|
|---|
| 2703 | }
|
|---|
| 2704 | }
|
|---|
| 2705 | """ % args # noqa
|
|---|
| 2706 |
|
|---|
| 2707 | s += """
|
|---|
| 2708 | function getWindowHeight() {
|
|---|
| 2709 | if (self.innerHeight) return self.innerHeight;
|
|---|
| 2710 | if (document.documentElement && document.documentElement.clientHeight)
|
|---|
| 2711 | return document.documentElement.clientHeight;
|
|---|
| 2712 | if (document.body) return document.body.clientHeight;
|
|---|
| 2713 | return 0;
|
|---|
| 2714 | }
|
|---|
| 2715 |
|
|---|
| 2716 | function getWindowWidth() {
|
|---|
| 2717 | if (self.innerWidth) return self.innerWidth;
|
|---|
| 2718 | if (document.documentElement && document.documentElement.clientWidth)
|
|---|
| 2719 | return document.documentElement.clientWidth;
|
|---|
| 2720 | if (document.body) return document.body.clientWidth;
|
|---|
| 2721 | return 0;
|
|---|
| 2722 | }
|
|---|
| 2723 |
|
|---|
| 2724 | function resize() {
|
|---|
| 2725 | var map = document.getElementById("map");
|
|---|
| 2726 | var header = document.getElementById("header");
|
|---|
| 2727 | var subheader = document.getElementById("subheader");
|
|---|
| 2728 | map.style.height = (getWindowHeight()-80) + "px";
|
|---|
| 2729 | map.style.width = (getWindowWidth()-20) + "px";
|
|---|
| 2730 | header.style.width = (getWindowWidth()-20) + "px";
|
|---|
| 2731 | subheader.style.width = (getWindowWidth()-20) + "px";
|
|---|
| 2732 | if (map.updateSize) { map.updateSize(); };
|
|---|
| 2733 | }
|
|---|
| 2734 |
|
|---|
| 2735 | onresize=function(){ resize(); };
|
|---|
| 2736 |
|
|---|
| 2737 | </script>
|
|---|
| 2738 | </head>
|
|---|
| 2739 | <body onload="init()">
|
|---|
| 2740 | <div id="header"><h1>%(title)s</h1></div>
|
|---|
| 2741 | <div id="subheader">Generated by <a href="http://www.klokan.cz/projects/gdal2tiles/">GDAL2Tiles</a>, Copyright © 2008 <a href="http://www.klokan.cz/">Klokan Petr Pridal</a>, <a href="http://www.gdal.org/">GDAL</a> & <a href="http://www.osgeo.org/">OSGeo</a> <a href="http://code.google.com/soc/">GSoC</a>
|
|---|
| 2742 | <!-- PLEASE, LET THIS NOTE ABOUT AUTHOR AND PROJECT SOMEWHERE ON YOUR WEBSITE, OR AT LEAST IN THE COMMENT IN HTML. THANK YOU -->
|
|---|
| 2743 | </div>
|
|---|
| 2744 | <div id="map"></div>
|
|---|
| 2745 | <script type="text/javascript" >resize()</script>
|
|---|
| 2746 | </body>
|
|---|
| 2747 | </html>""" % args # noqa
|
|---|
| 2748 |
|
|---|
| 2749 | return s
|
|---|
| 2750 |
|
|---|
| 2751 |
|
|---|
| [b72d9c4] | 2752 | def worker_tile_details(input_file, output_folder, options, send_pipe=None):
|
|---|
| 2753 | try:
|
|---|
| 2754 | gdal2tiles = GDAL2Tiles(input_file, output_folder, options)
|
|---|
| 2755 | gdal2tiles.open_input()
|
|---|
| 2756 | gdal2tiles.generate_metadata()
|
|---|
| 2757 | tile_job_info, tile_details = gdal2tiles.generate_base_tiles()
|
|---|
| 2758 | return_data = (tile_job_info, tile_details)
|
|---|
| 2759 | if send_pipe:
|
|---|
| 2760 | send_pipe.send(return_data)
|
|---|
| 2761 |
|
|---|
| 2762 | return return_data
|
|---|
| 2763 | except Exception as e:
|
|---|
| 2764 | print("worker_tile_details failed ", str(e))
|
|---|
| 2765 |
|
|---|
| 2766 |
|
|---|
| 2767 | def progress_printer_thread(queue, nb_jobs):
|
|---|
| 2768 | pb = ProgressBar(nb_jobs)
|
|---|
| 2769 | pb.start()
|
|---|
| 2770 | for _ in range(nb_jobs):
|
|---|
| 2771 | queue.get()
|
|---|
| 2772 | pb.log_progress()
|
|---|
| 2773 | queue.task_done()
|
|---|
| 2774 |
|
|---|
| [9f5877d] | 2775 |
|
|---|
| 2776 | class ProgressBar(object):
|
|---|
| 2777 |
|
|---|
| 2778 | def __init__(self, total_items):
|
|---|
| 2779 | self.total_items = total_items
|
|---|
| 2780 | self.nb_items_done = 0
|
|---|
| 2781 | self.current_progress = 0
|
|---|
| 2782 | self.STEP = 2.5
|
|---|
| 2783 |
|
|---|
| 2784 | def start(self):
|
|---|
| 2785 | sys.stdout.write("0")
|
|---|
| 2786 |
|
|---|
| 2787 | def log_progress(self, nb_items=1):
|
|---|
| 2788 | self.nb_items_done += nb_items
|
|---|
| 2789 | progress = float(self.nb_items_done) / self.total_items * 100
|
|---|
| 2790 | if progress >= self.current_progress + self.STEP:
|
|---|
| 2791 | done = False
|
|---|
| 2792 | while not done:
|
|---|
| 2793 | if self.current_progress + self.STEP <= progress:
|
|---|
| 2794 | self.current_progress += self.STEP
|
|---|
| 2795 | if self.current_progress % 10 == 0:
|
|---|
| 2796 | sys.stdout.write(str(int(self.current_progress)))
|
|---|
| 2797 | if self.current_progress == 100:
|
|---|
| 2798 | sys.stdout.write("\n")
|
|---|
| 2799 | else:
|
|---|
| 2800 | sys.stdout.write(".")
|
|---|
| 2801 | else:
|
|---|
| 2802 | done = True
|
|---|
| 2803 | sys.stdout.flush()
|
|---|
| 2804 |
|
|---|
| 2805 |
|
|---|
| 2806 | def get_tile_swne(tile_job_info, options):
|
|---|
| 2807 | if options.profile == 'mercator':
|
|---|
| 2808 | mercator = GlobalMercator()
|
|---|
| 2809 | tile_swne = mercator.TileLatLonBounds
|
|---|
| 2810 | elif options.profile == 'geodetic':
|
|---|
| 2811 | geodetic = GlobalGeodetic(options.tmscompatible)
|
|---|
| 2812 | tile_swne = geodetic.TileLatLonBounds
|
|---|
| 2813 | elif options.profile == 'raster':
|
|---|
| 2814 | srs4326 = osr.SpatialReference()
|
|---|
| 2815 | srs4326.ImportFromEPSG(4326)
|
|---|
| 2816 | if tile_job_info.kml and tile_job_info.in_srs_wkt:
|
|---|
| 2817 | in_srs = osr.SpatialReference()
|
|---|
| 2818 | in_srs.ImportFromWkt(tile_job_info.in_srs_wkt)
|
|---|
| 2819 | ct = osr.CoordinateTransformation(in_srs, srs4326)
|
|---|
| 2820 |
|
|---|
| 2821 | def rastertileswne(x, y, z):
|
|---|
| 2822 | pixelsizex = (2 ** (tile_job_info.tmaxz - z) * tile_job_info.out_geo_trans[1])
|
|---|
| 2823 | west = tile_job_info.out_geo_trans[0] + x * tile_job_info.tile_size * pixelsizex
|
|---|
| 2824 | east = west + tile_job_info.tile_size * pixelsizex
|
|---|
| 2825 | south = tile_job_info.ominy + y * tile_job_info.tile_size * pixelsizex
|
|---|
| 2826 | north = south + tile_job_info.tile_size * pixelsizex
|
|---|
| 2827 | if not tile_job_info.is_epsg_4326:
|
|---|
| 2828 | # Transformation to EPSG:4326 (WGS84 datum)
|
|---|
| 2829 | west, south = ct.TransformPoint(west, south)[:2]
|
|---|
| 2830 | east, north = ct.TransformPoint(east, north)[:2]
|
|---|
| 2831 | return south, west, north, east
|
|---|
| 2832 |
|
|---|
| 2833 | tile_swne = rastertileswne
|
|---|
| 2834 | else:
|
|---|
| 2835 | tile_swne = lambda x, y, z: (0, 0, 0, 0) # noqa
|
|---|
| 2836 | else:
|
|---|
| 2837 | tile_swne = lambda x, y, z: (0, 0, 0, 0) # noqa
|
|---|
| 2838 |
|
|---|
| 2839 | return tile_swne
|
|---|
| 2840 |
|
|---|
| 2841 |
|
|---|
| 2842 | def single_threaded_tiling(input_file, output_folder, options):
|
|---|
| 2843 | """
|
|---|
| 2844 | Keep a single threaded version that stays clear of multiprocessing, for platforms that would not
|
|---|
| 2845 | support it
|
|---|
| 2846 | """
|
|---|
| 2847 | if options.verbose:
|
|---|
| 2848 | print("Begin tiles details calc")
|
|---|
| 2849 | conf, tile_details = worker_tile_details(input_file, output_folder, options)
|
|---|
| 2850 |
|
|---|
| 2851 | if options.verbose:
|
|---|
| 2852 | print("Tiles details calc complete.")
|
|---|
| 2853 |
|
|---|
| 2854 | if not options.verbose and not options.quiet:
|
|---|
| 2855 | progress_bar = ProgressBar(len(tile_details))
|
|---|
| 2856 | progress_bar.start()
|
|---|
| 2857 |
|
|---|
| 2858 | for tile_detail in tile_details:
|
|---|
| 2859 | create_base_tile(conf, tile_detail)
|
|---|
| 2860 |
|
|---|
| 2861 | if not options.verbose and not options.quiet:
|
|---|
| 2862 | progress_bar.log_progress()
|
|---|
| 2863 |
|
|---|
| 2864 | if getattr(threadLocal, 'cached_ds', None):
|
|---|
| 2865 | del threadLocal.cached_ds
|
|---|
| 2866 |
|
|---|
| 2867 | create_overview_tiles(conf, output_folder, options)
|
|---|
| 2868 |
|
|---|
| 2869 | shutil.rmtree(os.path.dirname(conf.src_file))
|
|---|
| 2870 |
|
|---|
| 2871 |
|
|---|
| 2872 | def multi_threaded_tiling(input_file, output_folder, options):
|
|---|
| 2873 | nb_processes = options.nb_processes or 1
|
|---|
| 2874 |
|
|---|
| 2875 | # Make sure that all processes do not consume more than GDAL_CACHEMAX
|
|---|
| 2876 | os.environ['GDAL_CACHEMAX'] = '%d' % int(gdal.GetCacheMax() / nb_processes)
|
|---|
| 2877 |
|
|---|
| [b72d9c4] | 2878 | (conf_receiver, conf_sender) = Pipe(False)
|
|---|
| [9f5877d] | 2879 |
|
|---|
| 2880 | if options.verbose:
|
|---|
| 2881 | print("Begin tiles details calc")
|
|---|
| [b72d9c4] | 2882 | p = Process(target=worker_tile_details,
|
|---|
| 2883 | args=[input_file, output_folder, options],
|
|---|
| 2884 | kwargs={"send_pipe": conf_sender})
|
|---|
| 2885 | p.start()
|
|---|
| 2886 | # Make sure to consume the queue before joining. If the payload is too big, it won't be put in
|
|---|
| 2887 | # one go in the queue and therefore the sending process will never finish, waiting for space in
|
|---|
| 2888 | # the queue to send data
|
|---|
| 2889 | conf, tile_details = conf_receiver.recv()
|
|---|
| 2890 | p.join()
|
|---|
| [9f5877d] | 2891 | if options.verbose:
|
|---|
| 2892 | print("Tiles details calc complete.")
|
|---|
| [b72d9c4] | 2893 | # Have to create the Queue through a multiprocessing.Manager to get a Queue Proxy,
|
|---|
| 2894 | # otherwise you can't pass it as a param in the method invoked by the pool...
|
|---|
| 2895 | manager = Manager()
|
|---|
| 2896 | queue = manager.Queue()
|
|---|
| 2897 | pool = Pool(processes=nb_processes)
|
|---|
| [9f5877d] | 2898 | # TODO: gbataille - check the confs for which each element is an array... one useless level?
|
|---|
| 2899 | # TODO: gbataille - assign an ID to each job for print in verbose mode "ReadRaster Extent ..."
|
|---|
| [b72d9c4] | 2900 | for tile_detail in tile_details:
|
|---|
| 2901 | pool.apply_async(create_base_tile, (conf, tile_detail), {"queue": queue})
|
|---|
| 2902 |
|
|---|
| 2903 | if not options.verbose and not options.quiet:
|
|---|
| 2904 | p = Process(target=progress_printer_thread, args=[queue, len(tile_details)])
|
|---|
| 2905 | p.start()
|
|---|
| [9f5877d] | 2906 |
|
|---|
| 2907 | pool.close()
|
|---|
| 2908 | pool.join() # Jobs finished
|
|---|
| [b72d9c4] | 2909 | if not options.verbose and not options.quiet:
|
|---|
| 2910 | p.join() # Traces done
|
|---|
| [9f5877d] | 2911 |
|
|---|
| 2912 | create_overview_tiles(conf, output_folder, options)
|
|---|
| 2913 |
|
|---|
| 2914 | shutil.rmtree(os.path.dirname(conf.src_file))
|
|---|
| 2915 |
|
|---|
| 2916 |
|
|---|
| 2917 | def main():
|
|---|
| 2918 | # TODO: gbataille - use mkdtemp to work in a temp directory
|
|---|
| 2919 | # TODO: gbataille - debug intermediate tiles.vrt not produced anymore?
|
|---|
| 2920 | # TODO: gbataille - Refactor generate overview tiles to not depend on self variables
|
|---|
| 2921 | argv = gdal.GeneralCmdLineProcessor(sys.argv)
|
|---|
| 2922 | input_file, output_folder, options = process_args(argv[1:])
|
|---|
| 2923 | nb_processes = options.nb_processes or 1
|
|---|
| 2924 |
|
|---|
| 2925 | if nb_processes == 1:
|
|---|
| 2926 | single_threaded_tiling(input_file, output_folder, options)
|
|---|
| 2927 | else:
|
|---|
| 2928 | multi_threaded_tiling(input_file, output_folder, options)
|
|---|
| 2929 |
|
|---|
| 2930 |
|
|---|
| 2931 | if __name__ == '__main__':
|
|---|
| 2932 | main()
|
|---|
| 2933 |
|
|---|
| 2934 | # vim: set tabstop=4 shiftwidth=4 expandtab:
|
|---|