From bf08c245e19086a29f926c7dbc31661e0e61225d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20P=C3=A9ters?= Date: Wed, 21 Jun 2017 17:28:32 +0200 Subject: [PATCH] maps: move geojson layer code to its own method (#17082) --- combo/apps/maps/static/js/combo.map.js | 69 ++++++++++++++++++++++------------ 1 file changed, 44 insertions(+), 25 deletions(-) diff --git a/combo/apps/maps/static/js/combo.map.js b/combo/apps/maps/static/js/combo.map.js index 6bfc795..de1d8e8 100644 --- a/combo/apps/maps/static/js/combo.map.js +++ b/combo/apps/maps/static/js/combo.map.js @@ -1,4 +1,40 @@ $(function() { + L.Map.include( + { + add_geojson_layer: function(callback) { + var map = this; + var $map_widget = $(map.getContainer()); + var cell = $map_widget.parents('div.cell')[0]; + var geojson_url = $map_widget.data('geojson-url'); + if (!geojson_url) return; + + $.getJSON(geojson_url, function(data) { + var geo_json = L.geoJson(data, { + onEachFeature: function(feature, layer) { + $(cell).trigger('combo:map-feature-prepare', {'feature': feature, 'layer': layer}); + }, + pointToLayer: function (feature, latlng) { + var markerStyles = "background-color: " + feature.properties.layer.colour + ";"; + marker = L.divIcon({iconAnchor: [0, 30], + popupAnchor: [5, -45], + html: '' + }); + return L.marker(latlng, {icon: marker}); + } + }); + var bounds = geo_json.getBounds(); + if (map.geo_json) map.geo_json.remove(); + map.geo_json = geo_json; + geo_json.addTo(map); + if (callback) { + callback(geo_json); + } + }); + } + }); + function render_map(cell) { var $map_widget = $(cell).find('div.combo-cell-map'); var map_options = Object(); @@ -24,6 +60,7 @@ $(function() { var map = L.map($map_widget[0], map_options); var store_position_selector = $map_widget.data('store-position'); + $map_widget[0].leaflet_map = map; map.setView(latlng, map_options.zoom); if (init_state == 'device-location') { @@ -38,32 +75,14 @@ $(function() { attribution: map_attribution, maxZoom: map_options.maxZoom }).addTo(map); - if (geojson_url) { - $.getJSON(geojson_url, function(data) { - var geo_json = L.geoJson(data, { - onEachFeature: function(feature, layer) { - $(cell).trigger('combo:map-feature-prepare', {'feature': feature, 'layer': layer}); - }, - pointToLayer: function (feature, latlng) { - var markerStyles = "background-color: " + feature.properties.layer.colour + ";"; - marker = L.divIcon({iconAnchor: [0, 30], - popupAnchor: [5, -45], - html: '' - }); - return L.marker(latlng, {icon: marker}); - } - }); - var bounds = geo_json.getBounds(); - if (bounds.isValid()) { - if (init_state == 'fit-markers') { - map.fitBounds(bounds); - } - geo_json.addTo(map); + map.add_geojson_layer(function(geo_json) { + var bounds = geo_json.getBounds(); + if (bounds.isValid()) { + if (init_state == 'fit-markers') { + map.fitBounds(bounds); } - }); - } + } + }); }; $('div.cell.map').each(function() { render_map(this); -- 2.11.0