Skip to content

Commit

Permalink
Implemented minimal router for updating map view detail pannel.
Browse files Browse the repository at this point in the history
- moved default views and urls to async folders

- refactored everything to play nicely with django-leaflet
  • Loading branch information
linzjax committed May 11, 2017
1 parent 285f068 commit a60e07f
Show file tree
Hide file tree
Showing 55 changed files with 2,614 additions and 2,551 deletions.
9 changes: 6 additions & 3 deletions cadasta/config/urls/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,12 @@
url(r'^',
include('search.urls.async',
namespace='search')),
url(r'^',
include('organization.urls.async',
namespace='project')),
url(r'^',
include('party.urls.async',
namespace='party')),
]

urlpatterns = [
Expand All @@ -93,9 +99,6 @@
url(r'^',
include('party.urls.default',
namespace='parties')),
url(r'^',
include('spatial.urls.default',
namespace='locations')),
url(r'^',
include('resources.urls.default',
namespace='resources')),
Expand Down
2 changes: 1 addition & 1 deletion cadasta/core/static/css/main.css

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion cadasta/core/static/js/map_utils.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
function geoLocate(map) {
return function(event) {
map.locate({ setView: true });
}
};
}

function add_map_controls(map) {
Expand Down
22 changes: 11 additions & 11 deletions cadasta/core/static/js/rel_tenure.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
/* eslint-env jquery */

$('button#add-party').click(function() {
$('div#select-party').toggleClass('hidden');
$('div#new-item').toggleClass('hidden');
});
// $('button#add-party').click(function() {
// $('div#select-party').toggleClass('hidden');
// $('div#new-item').toggleClass('hidden');
// });

$('table#select-list tr').click(function(event) {
const target = $(event.target).closest('tr');
const relId = target.attr('data-id');
target.closest('tbody').find('tr.info').removeClass('info');
target.addClass('info');
$('input[name="id"]').val(relId);
});
// $('table#select-list tr').click(function(event) {
// const target = $(event.target).closest('tr');
// const relId = target.attr('data-id');
// target.closest('tbody').find('tr.info').removeClass('info');
// target.addClass('info');
// $('input[name="id"]').val(relId);
// });
18 changes: 16 additions & 2 deletions cadasta/core/static/js/smap/L.TileLayer.GeoJSON.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ L.TileLayer.Ajax = L.TileLayer.extend({
_requests: [],
_loadedfeatures: {},
_tiles: {},
_ticker: 1,
_addTile: function(tilePoint) {
var tile = {
datum: null,
Expand Down Expand Up @@ -40,12 +41,26 @@ L.TileLayer.Ajax = L.TileLayer.extend({
// _update has been refactored is no longer required?
// ****
// this._update(tilePoint);
if (tilePoint.x < 0 || tilePoint.y < 0) {
return;
}
var layer = this;
var req = new XMLHttpRequest();
this._requests.push(req);
req.onreadystatechange = this._xhrHandler(req, layer, tile, tilePoint);
req.open('GET', this.getTileUrl(tilePoint), true);
req.send();

// *** DELETE THIS ***
req.addEventListener("loadend", this._loadEnd.bind(this));
// *******************
},
_loadEnd: function() {
if (this._ticker < this._requests.length) {
this._ticker++;
} else {
$('#messages #loading').addClass('hidden');
}
},
_reset: function() {
L.TileLayer.prototype._reset.apply(this, arguments);
Expand Down Expand Up @@ -74,6 +89,7 @@ L.TileLayer.GeoJSON = L.TileLayer.Ajax.extend({
_clipPathRectangles: {},

initialize: function(url, options, geojsonOptions) {
$('#messages #loading').removeClass('hidden');
L.TileLayer.Ajax.prototype.initialize.call(this, url, options);
this.geojsonLayer = new L.GeoJSON(null, geojsonOptions);
this.features = L.deflate({
Expand Down Expand Up @@ -203,7 +219,6 @@ L.TileLayer.GeoJSON = L.TileLayer.Ajax.extend({
var features = L.Util.isArray(geojson) ? geojson : geojson.features,
i, len, feature;
if (features) {
$('#messages #loading').removeClass('hidden');
for (i = 0, len = features.length; i < len; i++) {
// Only add this if geometry or geometries are set and not null
feature = features[i];
Expand All @@ -217,7 +232,6 @@ L.TileLayer.GeoJSON = L.TileLayer.Ajax.extend({
}
}
}
$('#messages #loading').addClass('hidden');
return this;
}

Expand Down
26 changes: 15 additions & 11 deletions cadasta/core/static/js/smap/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
$(window).load(function () {
var js_files = [
'lazytiles.js',
'L.TileLayer.GeoJSON.js',
'map.js'
];
var body = $('body')
for (i in js_files) {
body.append($('<script src="/static/js/smap/' + js_files[i] + '"></script>'));
}
});
// $(window).load(function () {
// var js_files = [
// 'lazytiles.js',
// // 'L.TileLayer.GeoJSON.js',
// // 'map.js',
// 'routes.js',
// 'router.js'
// ];
// var body = $('body');
// for (var i in js_files) {
// body.append($('<script src="/static/js/smap/' + js_files[i] + '"></script>'));
// }
// // var sr = new SimpleRouter();
// // sr.router();
// });
43 changes: 43 additions & 0 deletions cadasta/core/static/js/smap/location_edit_js_temp.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-geocoder-mapzen/1.4.0/leaflet-geocoder-mapzen.js"></script>
<script src="{% static 'js/leaflet.markercluster.js' %}"></script>
<script src="{% static 'js/L.Map.Deflate.js' %}"></script>
<script src="{% static 'js/jquery-ui.min.js' %}"></script>
{% if get_current_language != "en-us" %}
{% get_current_language as LANGUAGE_CODE %}
<script src="https://cdn.rawgit.com/jquery/jquery-ui/1.12.1/ui/i18n/datepicker-{{ LANGUAGE_CODE }}.js"></script>
{% endif %}
<script src="{% static 'js/map_utils.js' %}"></script> -->
<script>
$(document).ready(function () {
$(window).on('map:init', function(e) {
if (e.detail) {
var detail = e.detail;
} else {
var detail = e.originalEvent.detail;
}
var map = detail.map;
var options = detail.options;
switch_layer_controls(map, options);

var orgSlug = '{{ object.organization.slug }}';
var projectSlug = '{{ object.slug }}';
var url = '/api/v1/organizations/'
+ orgSlug + '/projects/' + projectSlug + '/spatialresources/';
add_spatial_resources(map, url);

add_map_controls(map);
renderFeatures(detail.map,
'{% url "async:spatial:list" object.organization.slug object.slug %}?exclude={{location.id}}');

// Enable edit mode on map load and save the geometry on page save
setTimeout(enableMapEditMode, 500);
$('input.btn-primary')[0].addEventListener('click', saveOnMapEditMode);
});

$('.datepicker').datepicker({
yearRange: "c-200:c+200",
changeMonth: true,
changeYear: true,
});
});
</script>
79 changes: 54 additions & 25 deletions cadasta/core/static/js/smap/map.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
var SMap = (function() {
var map = L.map('mapid');
// var map = L.map('mapid');

var SMap = function(map) {
var layerscontrol = L.control.layers().addTo(map);

var geojsonTileLayer = new L.TileLayer.GeoJSON(
Expand All @@ -15,16 +16,16 @@ var SMap = (function() {
layer.bindPopup("<div class=\"text-wrap\">" +
"<h2><span>Location</span>" +
feature.properties.type + "</h2></div>" +
"<div class=\"btn-wrap\"><a href='" + feature.properties.url + "' class=\"btn btn-primary btn-sm btn-block\">" + options.trans['open'] + "</a>" +
"<div class=\"btn-wrap\"><a href='#/" + feature.properties.url + "' id=\"spatial-pop-up\" class=\"btn btn-primary btn-sm btn-block\">" + options.trans.open + "</a>" +
"</div>");
}
}
});
});

function add_tile_layers() {
for (var i = 0, n = layers.length; i < n; i++) {
var attrs = L.Util.extend(layers[i]['attrs']);
var layer = {name: layers[i]['label'], url: layers[i]['url'], options: attrs};
var attrs = L.Util.extend(layers[i].attrs);
var layer = {name: layers[i].label, url: layers[i].url, options: attrs};
var l = L.tileLayer(layer.url, layer.options);
layerscontrol.addBaseLayer(l, layer.name);

Expand Down Expand Up @@ -54,17 +55,20 @@ var SMap = (function() {
);
boundary.addTo(map);
projectBounds = boundary.getBounds();
options.projectExtent = projectBounds;
if (options.fitBounds === 'project') {
map.fitBounds(projectBounds);
return projectBounds;
}
} else {
map.fitBounds([[-45.0, -180.0], [45.0, 180.0]]);
}
}

load_project_extent()
load_project_extent();

function load_features() {;
// *** CURRENTLY DOES NOT WORK ***
function load_features() {
if (options.fitBounds === 'locations') {
var bounds = geojsonTileLayer.geojsonLayer.getBounds();
if (bounds.isValid()) {
Expand All @@ -77,23 +81,23 @@ var SMap = (function() {

function render_spatial_resource(){
$.ajax(fetch_spatial_resources).done(function(data){
if (data.length == 0) return;
if (data.length === 0) return;
var spatialResources = {};
$.each(data, function(idx, resource){
var name = resource.name;
var layers = {};
var group = new L.LayerGroup();
$.each(resource.spatial_resources, function(i, spatial_resource){
var layer = L.geoJson(spatial_resource.geom).addTo(group);
layers['name'] = spatial_resource.name;
layers['group'] = group;
layers.name = spatial_resource.name;
layers.group = group;
});
spatialResources[name] = layers;
});
$.each(spatialResources, function(sr){
var layer = spatialResources[sr];
layerscontrol.addOverlay(layer['group'], layer['name'], sr);
})
layerscontrol.addOverlay(layer.group, layer.name, sr);
});
});
}

Expand All @@ -102,18 +106,43 @@ var SMap = (function() {
function geoLocate() {
return function(event) {
map.locate({ setView: true });
}
};
}

$(window).on('hashchange', function() {
if (window.location.hash === '#overview')
$('.content-single').removeClass('detail-hidden')
else {
$('.content-single').addClass('detail-hidden')
}
function add_map_controls() {
var geocoder = L.control.geocoder('search-QctWfva', {
markers: false
}).addTo(map);
geocoder.on('select', function (e) {
map.setZoomAround(e.latlng, 9);
});

var Geolocate = L.Control.extend({
options: {
position: 'topleft'
},

onAdd: function() {
var controlDiv = L.DomUtil.create(
'div', 'leaflet-bar leaflet-control leaflet-control-geolocate'
);
controlDiv.title = gettext('Go to my location');
L.DomEvent
.addListener(controlDiv, 'click', L.DomEvent.stopPropagation)
.addListener(controlDiv, 'click', L.DomEvent.preventDefault)
.addListener(controlDiv, 'click', geoLocate(map));

L.DomUtil.create('span', 'glyphicon glyphicon-map-marker', controlDiv);

return controlDiv;
}
});

map.addControl(new Geolocate());
return map;
}

window.setTimeout(function() {
map.invalidateSize();
}, 400);
})
})();
return {
add_map_controls: add_map_controls,
};
};
62 changes: 62 additions & 0 deletions cadasta/core/static/js/smap/router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Based on http://joakim.beng.se/blog/posts/a-javascript-router-in-20-lines.html
var SimpleRouter = function(map){
routes = new CreateRoutes(map);

var el = null;
function router() {
var hash_path = location.hash.slice(1) || '/';
var view_url = '/async' + location.pathname;

if (hash_path !== '/') {
view_url = view_url + hash_path.substr(1) + '/';
}

var route = routes[hash_path] ? routes[hash_path] : null;

// Removes record id from hash_path to match key in routes.
if (!route) {
var records = ['/records/location', '/records/relationship']
var actions = ['/edit', '/delete', '/resources/add', '/resources/new', '/relationships/new']
var new_hash_path;

for (var i in records) {
if (hash_path.includes(records[i])) {
new_hash_path = records[i];
}
}

for (var i in actions) {
if (hash_path.includes(actions[i])) {
new_hash_path = new_hash_path + actions[i]
}
}
route = routes[new_hash_path];
console.log(new_hash_path);
console.log(view_url);
}


el = route.controller() || document.getElementById('project-detail');

$.get(view_url, function(response){
el.innerHTML = response;
if (route.eventHook) {
route.eventHook(view_url);
}
});
}

return {
router: router,
};
};

$(window).on('map:init', function (e) {
var detail = e.originalEvent ?
e.originalEvent.detail : e.detail;
console.log(detail.map);
var sr = new SimpleRouter(detail.map);
window.addEventListener('hashchange', sr.router);
window.addEventListener('load', sr.router);
});

Loading

0 comments on commit a60e07f

Please sign in to comment.