gmap.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. from __future__ import unicode_literals
  2. from django.conf import settings
  3. from django.template.loader import render_to_string
  4. from django.utils.html import format_html
  5. from django.utils.safestring import mark_safe
  6. from django.utils.six.moves import xrange
  7. from django.contrib.gis.maps.google.overlays import GPolygon, GPolyline, GMarker
  8. class GoogleMapException(Exception):
  9. pass
  10. # The default Google Maps URL (for the API javascript)
  11. # TODO: Internationalize for Japan, UK, etc.
  12. GOOGLE_MAPS_URL = 'http://maps.google.com/maps?file=api&v=%s&key='
  13. class GoogleMap(object):
  14. "A class for generating Google Maps JavaScript."
  15. # String constants
  16. onunload = mark_safe('onunload="GUnload()"') # Cleans up after Google Maps
  17. vml_css = mark_safe('v\:* {behavior:url(#default#VML);}') # CSS for IE VML
  18. xmlns = mark_safe('xmlns:v="urn:schemas-microsoft-com:vml"') # XML Namespace (for IE VML).
  19. def __init__(self, key=None, api_url=None, version=None,
  20. center=None, zoom=None, dom_id='map',
  21. kml_urls=[], polylines=None, polygons=None, markers=None,
  22. template='gis/google/google-map.js',
  23. js_module='geodjango',
  24. extra_context={}):
  25. # The Google Maps API Key defined in the settings will be used
  26. # if not passed in as a parameter. The use of an API key is
  27. # _required_.
  28. if not key:
  29. try:
  30. self.key = settings.GOOGLE_MAPS_API_KEY
  31. except AttributeError:
  32. raise GoogleMapException('Google Maps API Key not found (try adding GOOGLE_MAPS_API_KEY to your settings).')
  33. else:
  34. self.key = key
  35. # Getting the Google Maps API version, defaults to using the latest ("2.x"),
  36. # this is not necessarily the most stable.
  37. if not version:
  38. self.version = getattr(settings, 'GOOGLE_MAPS_API_VERSION', '2.x')
  39. else:
  40. self.version = version
  41. # Can specify the API URL in the `api_url` keyword.
  42. if not api_url:
  43. self.api_url = getattr(settings, 'GOOGLE_MAPS_URL', GOOGLE_MAPS_URL) % self.version
  44. else:
  45. self.api_url = api_url
  46. # Setting the DOM id of the map, the load function, the JavaScript
  47. # template, and the KML URLs array.
  48. self.dom_id = dom_id
  49. self.extra_context = extra_context
  50. self.js_module = js_module
  51. self.template = template
  52. self.kml_urls = kml_urls
  53. # Does the user want any GMarker, GPolygon, and/or GPolyline overlays?
  54. overlay_info = [[GMarker, markers, 'markers'],
  55. [GPolygon, polygons, 'polygons'],
  56. [GPolyline, polylines, 'polylines']]
  57. for overlay_class, overlay_list, varname in overlay_info:
  58. setattr(self, varname, [])
  59. if overlay_list:
  60. for overlay in overlay_list:
  61. if isinstance(overlay, overlay_class):
  62. getattr(self, varname).append(overlay)
  63. else:
  64. getattr(self, varname).append(overlay_class(overlay))
  65. # If GMarker, GPolygons, and/or GPolylines are used the zoom will be
  66. # automatically calculated via the Google Maps API. If both a zoom
  67. # level and a center coordinate are provided with polygons/polylines,
  68. # no automatic determination will occur.
  69. self.calc_zoom = False
  70. if self.polygons or self.polylines or self.markers:
  71. if center is None or zoom is None:
  72. self.calc_zoom = True
  73. # Defaults for the zoom level and center coordinates if the zoom
  74. # is not automatically calculated.
  75. if zoom is None:
  76. zoom = 4
  77. self.zoom = zoom
  78. if center is None:
  79. center = (0, 0)
  80. self.center = center
  81. def render(self):
  82. """
  83. Generates the JavaScript necessary for displaying this Google Map.
  84. """
  85. params = {'calc_zoom': self.calc_zoom,
  86. 'center': self.center,
  87. 'dom_id': self.dom_id,
  88. 'js_module': self.js_module,
  89. 'kml_urls': self.kml_urls,
  90. 'zoom': self.zoom,
  91. 'polygons': self.polygons,
  92. 'polylines': self.polylines,
  93. 'icons': self.icons,
  94. 'markers': self.markers,
  95. }
  96. params.update(self.extra_context)
  97. return render_to_string(self.template, params)
  98. @property
  99. def body(self):
  100. "Returns HTML body tag for loading and unloading Google Maps javascript."
  101. return format_html('<body {0} {1}>', self.onload, self.onunload)
  102. @property
  103. def onload(self):
  104. "Returns the `onload` HTML <body> attribute."
  105. return format_html('onload="{0}.{1}_load()"', self.js_module, self.dom_id)
  106. @property
  107. def api_script(self):
  108. "Returns the <script> tag for the Google Maps API javascript."
  109. return format_html('<script src="{0}{1}" type="text/javascript"></script>',
  110. self.api_url, self.key)
  111. @property
  112. def js(self):
  113. "Returns only the generated Google Maps JavaScript (no <script> tags)."
  114. return self.render()
  115. @property
  116. def scripts(self):
  117. "Returns all <script></script> tags required with Google Maps JavaScript."
  118. return format_html('{0}\n <script type="text/javascript">\n//<![CDATA[\n{1}//]]>\n </script>',
  119. self.api_script, mark_safe(self.js))
  120. @property
  121. def style(self):
  122. "Returns additional CSS styling needed for Google Maps on IE."
  123. return format_html('<style type="text/css">{0}</style>', self.vml_css)
  124. @property
  125. def xhtml(self):
  126. "Returns XHTML information needed for IE VML overlays."
  127. return format_html('<html xmlns="http://www.w3.org/1999/xhtml" {0}>', self.xmlns)
  128. @property
  129. def icons(self):
  130. "Returns a sequence of GIcon objects in this map."
  131. return set(marker.icon for marker in self.markers if marker.icon)
  132. class GoogleMapSet(GoogleMap):
  133. def __init__(self, *args, **kwargs):
  134. """
  135. A class for generating sets of Google Maps that will be shown on the
  136. same page together.
  137. Example:
  138. gmapset = GoogleMapSet( GoogleMap( ... ), GoogleMap( ... ) )
  139. gmapset = GoogleMapSet( [ gmap1, gmap2] )
  140. """
  141. # The `google-multi.js` template is used instead of `google-single.js`
  142. # by default.
  143. template = kwargs.pop('template', 'gis/google/google-multi.js')
  144. # This is the template used to generate the GMap load JavaScript for
  145. # each map in the set.
  146. self.map_template = kwargs.pop('map_template', 'gis/google/google-single.js')
  147. # Running GoogleMap.__init__(), and resetting the template
  148. # value with default obtained above.
  149. super(GoogleMapSet, self).__init__(**kwargs)
  150. self.template = template
  151. # If a tuple/list passed in as first element of args, then assume
  152. if isinstance(args[0], (tuple, list)):
  153. self.maps = args[0]
  154. else:
  155. self.maps = args
  156. # Generating DOM ids for each of the maps in the set.
  157. self.dom_ids = ['map%d' % i for i in xrange(len(self.maps))]
  158. def load_map_js(self):
  159. """
  160. Returns JavaScript containing all of the loading routines for each
  161. map in this set.
  162. """
  163. result = []
  164. for dom_id, gmap in zip(self.dom_ids, self.maps):
  165. # Backup copies the GoogleMap DOM id and template attributes.
  166. # They are overridden on each GoogleMap instance in the set so
  167. # that only the loading JavaScript (and not the header variables)
  168. # is used with the generated DOM ids.
  169. tmp = (gmap.template, gmap.dom_id)
  170. gmap.template = self.map_template
  171. gmap.dom_id = dom_id
  172. result.append(gmap.js)
  173. # Restoring the backup values.
  174. gmap.template, gmap.dom_id = tmp
  175. return mark_safe(''.join(result))
  176. def render(self):
  177. """
  178. Generates the JavaScript for the collection of Google Maps in
  179. this set.
  180. """
  181. params = {'js_module': self.js_module,
  182. 'dom_ids': self.dom_ids,
  183. 'load_map_js': self.load_map_js(),
  184. 'icons': self.icons,
  185. }
  186. params.update(self.extra_context)
  187. return render_to_string(self.template, params)
  188. @property
  189. def onload(self):
  190. "Returns the `onload` HTML <body> attribute."
  191. # Overloaded to use the `load` function defined in the
  192. # `google-multi.js`, which calls the load routines for
  193. # each one of the individual maps in the set.
  194. return mark_safe('onload="%s.load()"' % self.js_module)
  195. @property
  196. def icons(self):
  197. "Returns a sequence of all icons in each map of the set."
  198. icons = set()
  199. for map in self.maps:
  200. icons |= map.icons
  201. return icons