/django/contrib/gis/maps/google/zoom.py

https://code.google.com/p/mango-py/ · Python · 161 lines · 80 code · 29 blank · 52 comment · 10 complexity · d7a025db956279aa2035f7c9ad3bb7ba MD5 · raw file

  1. from django.contrib.gis.geos import GEOSGeometry, LinearRing, Polygon, Point
  2. from django.contrib.gis.maps.google.gmap import GoogleMapException
  3. from math import pi, sin, cos, log, exp, atan
  4. # Constants used for degree to radian conversion, and vice-versa.
  5. DTOR = pi / 180.
  6. RTOD = 180. / pi
  7. class GoogleZoom(object):
  8. """
  9. GoogleZoom is a utility for performing operations related to the zoom
  10. levels on Google Maps.
  11. This class is inspired by the OpenStreetMap Mapnik tile generation routine
  12. `generate_tiles.py`, and the article "How Big Is the World" (Hack #16) in
  13. "Google Maps Hacks" by Rich Gibson and Schuyler Erle.
  14. `generate_tiles.py` may be found at:
  15. http://trac.openstreetmap.org/browser/applications/rendering/mapnik/generate_tiles.py
  16. "Google Maps Hacks" may be found at http://safari.oreilly.com/0596101619
  17. """
  18. def __init__(self, num_zoom=19, tilesize=256):
  19. "Initializes the Google Zoom object."
  20. # Google's tilesize is 256x256, square tiles are assumed.
  21. self._tilesize = tilesize
  22. # The number of zoom levels
  23. self._nzoom = num_zoom
  24. # Initializing arrays to hold the parameters for each one of the
  25. # zoom levels.
  26. self._degpp = [] # Degrees per pixel
  27. self._radpp = [] # Radians per pixel
  28. self._npix = [] # 1/2 the number of pixels for a tile at the given zoom level
  29. # Incrementing through the zoom levels and populating the parameter arrays.
  30. z = tilesize # The number of pixels per zoom level.
  31. for i in xrange(num_zoom):
  32. # Getting the degrees and radians per pixel, and the 1/2 the number of
  33. # for every zoom level.
  34. self._degpp.append(z / 360.) # degrees per pixel
  35. self._radpp.append(z / (2 * pi)) # radians per pixl
  36. self._npix.append(z / 2) # number of pixels to center of tile
  37. # Multiplying `z` by 2 for the next iteration.
  38. z *= 2
  39. def __len__(self):
  40. "Returns the number of zoom levels."
  41. return self._nzoom
  42. def get_lon_lat(self, lonlat):
  43. "Unpacks longitude, latitude from GEOS Points and 2-tuples."
  44. if isinstance(lonlat, Point):
  45. lon, lat = lonlat.coords
  46. else:
  47. lon, lat = lonlat
  48. return lon, lat
  49. def lonlat_to_pixel(self, lonlat, zoom):
  50. "Converts a longitude, latitude coordinate pair for the given zoom level."
  51. # Setting up, unpacking the longitude, latitude values and getting the
  52. # number of pixels for the given zoom level.
  53. lon, lat = self.get_lon_lat(lonlat)
  54. npix = self._npix[zoom]
  55. # Calculating the pixel x coordinate by multiplying the longitude value
  56. # with with the number of degrees/pixel at the given zoom level.
  57. px_x = round(npix + (lon * self._degpp[zoom]))
  58. # Creating the factor, and ensuring that 1 or -1 is not passed in as the
  59. # base to the logarithm. Here's why:
  60. # if fac = -1, we'll get log(0) which is undefined;
  61. # if fac = 1, our logarithm base will be divided by 0, also undefined.
  62. fac = min(max(sin(DTOR * lat), -0.9999), 0.9999)
  63. # Calculating the pixel y coordinate.
  64. px_y = round(npix + (0.5 * log((1 + fac)/(1 - fac)) * (-1.0 * self._radpp[zoom])))
  65. # Returning the pixel x, y to the caller of the function.
  66. return (px_x, px_y)
  67. def pixel_to_lonlat(self, px, zoom):
  68. "Converts a pixel to a longitude, latitude pair at the given zoom level."
  69. if len(px) != 2:
  70. raise TypeError('Pixel should be a sequence of two elements.')
  71. # Getting the number of pixels for the given zoom level.
  72. npix = self._npix[zoom]
  73. # Calculating the longitude value, using the degrees per pixel.
  74. lon = (px[0] - npix) / self._degpp[zoom]
  75. # Calculating the latitude value.
  76. lat = RTOD * ( 2 * atan(exp((px[1] - npix)/ (-1.0 * self._radpp[zoom]))) - 0.5 * pi)
  77. # Returning the longitude, latitude coordinate pair.
  78. return (lon, lat)
  79. def tile(self, lonlat, zoom):
  80. """
  81. Returns a Polygon corresponding to the region represented by a fictional
  82. Google Tile for the given longitude/latitude pair and zoom level. This
  83. tile is used to determine the size of a tile at the given point.
  84. """
  85. # The given lonlat is the center of the tile.
  86. delta = self._tilesize / 2
  87. # Getting the pixel coordinates corresponding to the
  88. # the longitude/latitude.
  89. px = self.lonlat_to_pixel(lonlat, zoom)
  90. # Getting the lower-left and upper-right lat/lon coordinates
  91. # for the bounding box of the tile.
  92. ll = self.pixel_to_lonlat((px[0]-delta, px[1]-delta), zoom)
  93. ur = self.pixel_to_lonlat((px[0]+delta, px[1]+delta), zoom)
  94. # Constructing the Polygon, representing the tile and returning.
  95. return Polygon(LinearRing(ll, (ll[0], ur[1]), ur, (ur[0], ll[1]), ll), srid=4326)
  96. def get_zoom(self, geom):
  97. "Returns the optimal Zoom level for the given geometry."
  98. # Checking the input type.
  99. if not isinstance(geom, GEOSGeometry) or geom.srid != 4326:
  100. raise TypeError('get_zoom() expects a GEOS Geometry with an SRID of 4326.')
  101. # Getting the envelope for the geometry, and its associated width, height
  102. # and centroid.
  103. env = geom.envelope
  104. env_w, env_h = self.get_width_height(env.extent)
  105. center = env.centroid
  106. for z in xrange(self._nzoom):
  107. # Getting the tile at the zoom level.
  108. tile_w, tile_h = self.get_width_height(self.tile(center, z).extent)
  109. # When we span more than one tile, this is an approximately good
  110. # zoom level.
  111. if (env_w > tile_w) or (env_h > tile_h):
  112. if z == 0:
  113. raise GoogleMapException('Geometry width and height should not exceed that of the Earth.')
  114. return z-1
  115. # Otherwise, we've zoomed in to the max.
  116. return self._nzoom-1
  117. def get_width_height(self, extent):
  118. """
  119. Returns the width and height for the given extent.
  120. """
  121. # Getting the lower-left, upper-left, and upper-right
  122. # coordinates from the extent.
  123. ll = Point(extent[:2])
  124. ul = Point(extent[0], extent[3])
  125. ur = Point(extent[2:])
  126. # Calculating the width and height.
  127. height = ll.distance(ul)
  128. width = ul.distance(ur)
  129. return width, height