gmap: set center and zoomlevel automatically (closes #2144255)
Instead of hardcoding the default zoomlevel and setting the center to
the average of all markers, let gmap compute them so all markers fit in
the map.
--- a/web/data/cubicweb.gmap.js Wed Jan 04 17:21:14 2012 +0100
+++ b/web/data/cubicweb.gmap.js Mon Jan 09 16:20:49 2012 +0100
@@ -23,9 +23,24 @@
var jsonurl = wdgnode.getAttribute('cubicweb:loadurl');
var self = this; // bind this to a local variable
jQuery.getJSON(jsonurl, function(geodata) {
+ var zoomLevel;
+ var center;
+ var latlngbounds = new GLatLngBounds( );
+ for (var i = 0; i < geodata.markers.length; i++) {
+ var marker = geodata.markers[i];
+ var latlng = new GLatLng(marker.latitude, marker.longitude);
+ latlngbounds.extend( latlng );
+ }
+ if (geodata.zoomlevel) {
+ zoomLevel = geodata.zoomlevel;
+ } else {
+ zoomLevel = map.getBoundsZoomLevel( latlngbounds ) - 1;
if (geodata.center) {
- var zoomLevel = geodata.zoomlevel;
- map.setCenter(new GLatLng(geodata.center.latitude, geodata.center.longitude), zoomLevel);
+ center = new GLatng(geodata.center.latitude, geodata.center.longitude);
+ } else {
+ center = latlngbounds.getCenter();
+ }
+ map.setCenter(center, zoomLevel);
}
for (var i = 0; i < geodata.markers.length; i++) {
var marker = geodata.markers[i];
--- a/web/views/igeocodable.py Wed Jan 04 17:21:14 2012 +0100
+++ b/web/views/igeocodable.py Mon Jan 09 16:20:49 2012 +0100
@@ -62,7 +62,7 @@
content_type = 'application/json'
def call(self):
- zoomlevel = self._cw.form.pop('zoomlevel', 8)
+ zoomlevel = self._cw.form.pop('zoomlevel', None)
extraparams = self._cw.form.copy()
extraparams.pop('vid', None)
extraparams.pop('rql', None)
@@ -74,15 +74,13 @@
continue
markers.append(self.build_marker_data(entity, igeocodable,
extraparams))
- center = {
- 'latitude': sum(marker['latitude'] for marker in markers) / len(markers),
- 'longitude': sum(marker['longitude'] for marker in markers) / len(markers),
- }
+ if not markers:
+ return
geodata = {
- 'zoomlevel': int(zoomlevel),
- 'center': center,
'markers': markers,
}
+ if zoomlevel:
+ geodata['zoomlevel'] = zoomlevel
self.w(json_dumps(geodata))
def build_marker_data(self, entity, igeocodable, extraparams):