Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 142 additions & 0 deletions geotrek/common/static/common/js/leaflet.geojson.grid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
(function() {

L.GeoJSONTileLayer = L.GridLayer.extend({

includes: L.Evented.prototype,

url: null,
map: null,
layer: null,
features: null,
cache: null,

//
// Leaflet layer methods
//
initialize(url, options) {
this.url = url;
this.layer = new L.GeoJSON(null, options);
this.features = {};
this.cache = {};
L.GridLayer.prototype.initialize.call(this, options);
},

createTile(coords, done) {
var tile = L.DomUtil.create('div', 'leaflet-tile');
var url = this._expandUrl(this.url, coords);
if (this.cache[coords]) {
done.call(this);
} else {
this._ajaxRequest('GET', url, false, this._updateCache.bind(this, done, coords));
}
return tile;
},

onAdd(map) {
L.GridLayer.prototype.onAdd.call(this, map);
map.addLayer(this.layer);
this.map = map;
map.on('zoomanim', this._onZoomAnim.bind(this));
this.on('loading', this._onLoading.bind(this));
this.on('tileload', this._onTileLoad.bind(this));
this.on('tileunload', this._onTileUnLoad.bind(this));
},

onRemove(map) {
this.off('tileunload', this._onTileUnLoad.bind(this));
this.off('tileload', this._onTileLoad.bind(this));
this.off('loading', this._onLoading.bind(this));
map.off('zoomanim', this._onZoomAnim.bind(this));
this.map = null;
map.removeLayer(this.layer)
L.GridLayer.prototype.onRemove.call(this, map);
},

//
// Custom methods
//
_expandUrl: function(template, coords) {
return L.Util.template(template, coords);
},

_updateTiles: function() {
this.layer.clearLayers();
this.features = {};
for (var coords in this.cache) {
if (this.cache.hasOwnProperty(coords)) {
this._drawTile(coords);
}
}
},

_drawTile(coords) {
var geoData = this.cache[coords];
if (geoData.type == 'FeatureCollection'){
geoData = geoData.features;
}
for (var i=0;i<geoData.length;i++) {
var id = geoData[i].id;
if (!this.features[id]) {
this.layer.addData(geoData[i]);
this.features[id] = true;
}
}
if (!this.cache[coords]) {
this.cache[coords] = geoData;
}
},

_updateCache: function(done, coords, geoData) {
this.cache[coords] = geoData;
done.call(this);
},

_ajaxRequest: function(method, url, data, callback) {
var request = new XMLHttpRequest();
request.open(method, url, true);
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
callback(JSON.parse(request.responseText));
}
};
if (data) {
request.setRequestHeader('Content-type', 'application/json');
request.send(JSON.stringify(data));
} else {
request.send();
}
return request;
},

_onZoomAnim: function (e) {
var zoom = e.zoom;
if ((this.options.maxZoom && zoom > this.options.maxZoom) ||
(this.options.minZoom && zoom < this.options.minZoom)) {
this.map.removeLayer(this.layer);
this.cache = {};
this.layer.clearLayers();
} else {
this._updateTiles();
this.map.addLayer(this.layer);
}
},

_onLoading: function (e) {
this._updateTiles();
},

_onTileLoad: function (e) {
this._drawTile(e.coords);
},

_onTileUnLoad: function (e) {
delete this.cache[e.coords]
},

});

L.geoJSONTileLayer = function (url, options) {
return new L.GeoJSONTileLayer(url, options);
};

})();
89 changes: 89 additions & 0 deletions geotrek/common/templates/common/leaflet_test.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Leaflet tiling test
</title>
<link rel="stylesheet" href="//unpkg.com/[email protected]/dist/leaflet.css" />
</head>
<body>
<div id="map" style="height: 800px; width: 1900px;">
</div>
<script type="text/javascript" src="//unpkg.com/[email protected]/dist/leaflet.js"></script>
<script type="text/javascript" src="{% static 'common/js/leaflet.geojson.grid.js' %}"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
// create map
const map = L.map('map', {
center: [44, 4],
zoom: 8
});
// create base layer
const osm = L.tileLayer(
'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
{
minZoom: 5,
maxZoom: 19,
attribution: "¢ OSM"
}
)
// add base layer to map
osm.addTo(map);

// path grid layer
const tiles_path = new L.GeoJSONTileLayer('/api/path/path.geojson?tiles={z}/{x}/{y}', {
minZoom: 3,
maxZoom: 18,
style: {
"clickable": true,
"color": "#FF0000",
"fillColor": "#00D",
"weight": 2.0,
"opacity": 0.3,
"fillOpacity": 0.2
}
});

// trek grid layer
const tiles_trek = new L.GeoJSONTileLayer('/api/trek/trek.geojson?tiles={z}/{x}/{y}', {
minZoom: 3,
maxZoom: 18,
style:{
"clickable": true,
"color": "#006400",
"weight": 2.0,
}
});

// city grid layer
const tiles_city = new L.GeoJSONTileLayer('/api/city/city.geojson?tiles={z}/{x}/{y}', {
minZoom: 3,
maxZoom: 18,
style: {
"clickable": true,
"fillColor": "#00D",
"weight": 2.0,
"fillOpacity": 0.2
}
});

// base layer selector
const baseMaps = {
"OSM": osm,
};

// averlay layer selector
const overlayMaps = {
"Tronçons": tiles_path,
"Itinéraires": tiles_trek,
"Communes": tiles_city,
}

// control to show layers
L.control.layers(baseMaps, overlayMaps).addTo(map);
});

</script>
</body>
</html>
3 changes: 2 additions & 1 deletion geotrek/common/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from mapentity.registry import MapEntityOptions

from .views import (JSSettings, admin_check_extents, DocumentPublic, DocumentBookletPublic, import_view, import_update_json,
ThemeViewSet, MarkupPublic, sync_view, sync_update_json, SyncRandoRedirect)
ThemeViewSet, MarkupPublic, sync_view, sync_update_json, SyncRandoRedirect, LeafletTestView)


class LangConverter(converters.StringConverter):
Expand All @@ -21,6 +21,7 @@ class LangConverter(converters.StringConverter):
path('commands/syncview', sync_view, name='sync_randos_view'),
path('commands/statesync/', sync_update_json, name='sync_randos_state'),
path('api/<lang:lang>/themes.json', ThemeViewSet.as_view({'get': 'list'}), name="themes_json"),
path('leaflet-tiles/', LeafletTestView.as_view(), name="leaflet-tiles"),
]


Expand Down
5 changes: 5 additions & 0 deletions geotrek/common/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from django.db.utils import DatabaseError
from django.utils import translation
from django.http import JsonResponse, HttpResponse, HttpResponseNotFound
from django.views.generic import TemplateView
from django_celery_results.models import TaskResult
from django.shortcuts import get_object_or_404
from django.utils import timezone
Expand Down Expand Up @@ -502,3 +503,7 @@ def post(self, request, *args, **kwargs):


home = last_list


class LeafletTestView(TemplateView):
template_name = "common/leaflet_test.html"
2 changes: 2 additions & 0 deletions geotrek/core/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ def get_initial(self):
class PathLayer(MapEntityLayer):
properties = ['name', 'draft']
queryset = Path.objects.all()
geometry_field_db = 'geom'

def get_queryset(self):
qs = super(PathLayer, self).get_queryset()
Expand Down Expand Up @@ -299,6 +300,7 @@ def get_graph_json(request):
class TrailLayer(MapEntityLayer):
queryset = Trail.objects.existing()
properties = ['name']
geometry_field_db = 'geom'


class TrailList(MapEntityList):
Expand Down
7 changes: 7 additions & 0 deletions geotrek/diving/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,13 @@ def test_pois_on_treks_not_public(self):
response = self.client.get(reverse('diving:dive_poi_geojson', kwargs={'lang': translation.get_language(), 'pk': dive.pk}))
self.assertEqual(response.status_code, 404)

def test_bbox_filter(self):
class DiveGoodGeomFactory(DiveFactory):
geom = 'Point(700000 6600000)'

self.modelfactory = DiveGoodGeomFactory
super(DiveViewsTests, self).test_bbox_filter()


class DiveViewsLiveTests(CommonLiveTest):
model = Dive
Expand Down
2 changes: 2 additions & 0 deletions geotrek/diving/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,14 @@
class DiveLayer(MapEntityLayer):
properties = ['name', 'published']
queryset = Dive.objects.existing()
geometry_field_db = 'geom'


class DiveList(FlattenPicturesMixin, MapEntityList):
filterform = DiveFilterSet
columns = ['id', 'name', 'levels', 'thumbnail']
queryset = Dive.objects.existing()
template_name = 'diving/dive_list.html'


class DiveJsonList(MapEntityJsonList, DiveList):
Expand Down
1 change: 1 addition & 0 deletions geotrek/feedback/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ class ReportLayer(mapentity_views.MapEntityLayer):
model = feedback_models.Report
filterform = ReportFilterSet
properties = ['email']
geometry_field_db = 'geom'


class ReportList(mapentity_views.MapEntityList):
Expand Down
1 change: 1 addition & 0 deletions geotrek/infrastructure/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
class InfrastructureLayer(MapEntityLayer):
queryset = Infrastructure.objects.existing()
properties = ['name', 'published']
geometry_field_db = 'geom'


class InfrastructureList(MapEntityList):
Expand Down
5 changes: 5 additions & 0 deletions geotrek/land/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
class PhysicalEdgeLayer(MapEntityLayer):
queryset = PhysicalEdge.objects.existing()
properties = ['color_index', 'name']
geometry_field_db = 'geom'


class PhysicalEdgeList(MapEntityList):
Expand Down Expand Up @@ -57,6 +58,7 @@ class PhysicalEdgeDelete(MapEntityDelete):
class LandEdgeLayer(MapEntityLayer):
queryset = LandEdge.objects.existing()
properties = ['color_index', 'name']
geometry_field_db = 'geom'


class LandEdgeList(MapEntityList):
Expand Down Expand Up @@ -102,6 +104,7 @@ class LandEdgeDelete(MapEntityDelete):
class CompetenceEdgeLayer(MapEntityLayer):
queryset = CompetenceEdge.objects.existing()
properties = ['color_index', 'name']
geometry_field_db = 'geom'


class CompetenceEdgeList(MapEntityList):
Expand Down Expand Up @@ -147,6 +150,7 @@ class CompetenceEdgeDelete(MapEntityDelete):
class WorkManagementEdgeLayer(MapEntityLayer):
queryset = WorkManagementEdge.objects.existing()
properties = ['color_index', 'name']
geometry_field_db = 'geom'


class WorkManagementEdgeList(MapEntityList):
Expand Down Expand Up @@ -192,6 +196,7 @@ class WorkManagementEdgeDelete(MapEntityDelete):
class SignageManagementEdgeLayer(MapEntityLayer):
queryset = SignageManagementEdge.objects.existing()
properties = ['color_index', 'name']
geometry_field_db = 'geom'


class SignageManagementEdgeList(MapEntityList):
Expand Down
3 changes: 1 addition & 2 deletions geotrek/maintenance/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from django.utils.translation import ugettext_lazy as _
from django_filters import ChoiceFilter

from mapentity.filters import PolygonFilter, PythonPolygonFilter
from mapentity.filters import PolygonFilter

from geotrek.core.models import Topology
from geotrek.common.filters import (
Expand Down Expand Up @@ -77,7 +77,6 @@ def get_years(self):


class ProjectFilterSet(StructureRelatedFilterSet):
bbox = PythonPolygonFilter(field_name='geom')
in_year = YearBetweenFilter(field_name=('begin_year', 'end_year'),
widget=ProjectYearSelect,
label=_("Year of activity"))
Expand Down
4 changes: 2 additions & 2 deletions geotrek/maintenance/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -506,10 +506,10 @@ def jsonlist(bbox):
# Check that projects without interventions are always present
self.assertEqual(len(Project.objects.all()), 3)
self.assertEqual(len(jsonlist('')), 3)
self.assertEqual(len(jsonlist('?bbox=POLYGON((1%202%200%2C1%202%200%2C1%202%200%2C1%202%200%2C1%202%200))')), 2)
self.assertEqual(len(jsonlist('?tiles=5,16,11')), 2)

# Give a bbox that match intervention, and check that all 3 projects are back
bbox = '?bbox=POLYGON((2.9%2046.4%2C%203.1%2046.4%2C%203.1%2046.6%2C%202.9%2046.6%2C%202.9%2046.4))'
bbox = '?tiles=5,16,11'
self.assertEqual(len(jsonlist(bbox)), 3)

def test_deleted_interventions(self):
Expand Down
Loading