gmap.py 8.9 KB

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