Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Leaflet Shapefile Viewer #54

Merged
merged 1 commit into from
Oct 30, 2019
Merged
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
27 changes: 27 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ Available plugins
* `OpenLayers Viewer`_
* `Leaflet GeoJSON Viewer`_
* `Leaflet WMTS Viewer`_
* `Leaflet ESRI Shapefile Viewer`_


OpenLayers Viewer
Expand Down Expand Up @@ -175,6 +176,31 @@ On CKAN >= 2.3, if you want the views to be created by default on all WMTS resou
ckan.views.default_views = ... wmts_view


Leaflet ESRI Shapefile Viewer
-----------------------------

.. image:: http://i.imgur.com/JDIRgPy.png

The Leaflet_ Shapefile_ viewer will render ESRI Shapfiles (A ZIP archive contains the .shp, .shx, .dbf, and .prj files) on a map and add a popup showing the features properties, for those resources that have a ``shp`` format.

To enable it, add ``shp_view`` to your ``ckan.plugins`` setting. (use ``shp_preview`` if you are using CKAN < 2.3)::

ckan.plugins = ... resource_proxy shp_view

On CKAN >= 2.3, if you want the views to be created by default on all Shapefiles, add the plugin to the following setting::


ckan.views.default_views = ... shp_view

The projection information (EPSG code, e.g., 4326 and 3857) will be loaded if there is a .prj file provided. You can also add a new field named 'resource_crs' in your custom resource fields or the following configuration option (The loading order is: .prj file, 'resource_crs' field, option and EPSG:4326/WGS84)::

ckanext.geoview.shp_viewer.srid = 4326

The encoding of the shapefile can be defined by a custom resource field named 'encoding' in the metadata of the dataset or the following configuration option (The loading order is: 'encoding' field, option and UTF-8)::

ckanext.geoview.shp_viewer.encoding = UTF-8


----------------------------------
Common base layers for Map Widgets
----------------------------------
Expand Down Expand Up @@ -250,4 +276,5 @@ To publish a new version to PyPI follow these steps:
.. _OpenLayers: http://openlayers.org
.. _Leaflet: http://leafletjs.com/
.. _GeoJSON: http://geojson.org/
.. _Shapefile: https://en.wikipedia.org/wiki/Shapefile
.. _ckanext-spatial: https://github.com/ckan/ckanext-spatial
82 changes: 82 additions & 0 deletions ckanext/geoview/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,16 @@ def get_openlayers_viewer_config():
if k.startswith(namespace)])


def get_shapefile_viewer_config():
'''
Returns a dict with all configuration options related to the
Shapefile viewer (ie those starting with 'ckanext.geoview.shp_viewer.')
'''
namespace = 'ckanext.geoview.shp_viewer.'
return dict([(k.replace(namespace, ''), v) for k, v in config.iteritems()
if k.startswith(namespace)])


class GeoViewBase(p.SingletonPlugin):
'''This base class is for view extensions. '''
if p.toolkit.check_ckan_version(min_version='2.3'):
Expand Down Expand Up @@ -345,3 +355,75 @@ def get_helpers(self):

class WMTSPreview(WMTSView):
pass


class SHPView(GeoViewBase):
p.implements(p.ITemplateHelpers, inherit=True)

SHP = ['shp', 'shapefile']

# IResourceView (CKAN >=2.3)
def info(self):
return {'name': 'shp_view',
'title': 'Shapefile',
'icon': 'map-marker',
'iframed': True,
'default_title': p.toolkit._('Shapefile'),
}

def can_view(self, data_dict):
resource = data_dict['resource']
format_lower = resource['format'].lower()

if format_lower in self.SHP:
return self.same_domain or self.proxy_enabled
return False

def view_template(self, context, data_dict):
return 'dataviewer/shp.html'

# IResourcePreview (CKAN < 2.3)
def can_preview(self, data_dict):
format_lower = data_dict['resource']['format'].lower()

correct_format = format_lower in self.SHP
can_preview_from_domain = (self.proxy_enabled or
data_dict['resource'].get('on_same_domain'))
quality = 2

if p.toolkit.check_ckan_version('2.1'):
if correct_format:
if can_preview_from_domain:
return {'can_preview': True, 'quality': quality}
else:
return {'can_preview': False,
'fixable': 'Enable resource_proxy',
'quality': quality}
else:
return {'can_preview': False, 'quality': quality}

return correct_format and can_preview_from_domain

def preview_template(self, context, data_dict):
return 'dataviewer/shp.html'

def setup_template_variables(self, context, data_dict):
import ckanext.resourceproxy.plugin as proxy
self.same_domain = data_dict['resource'].get('on_same_domain')
if self.proxy_enabled and not self.same_domain:
data_dict['resource']['original_url'] = \
data_dict['resource'].get('url')
data_dict['resource']['url'] = \
proxy.get_proxified_resource_url(data_dict)

## ITemplateHelpers

def get_helpers(self):
return {
'get_common_map_config_shp' : get_common_map_config,
'get_shapefile_viewer_config': get_shapefile_viewer_config,
}


class SHPPreview(SHPView):
pass
9 changes: 9 additions & 0 deletions ckanext/geoview/public/css/geo-resource-styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,15 @@
background-position: -162px -62px;
}

.label[data-format=shp] {
background-color: #0080ff;
}
.format-label[data-format=shp],
.format-label[data-format*=shp] {
background: url("../../img/gis-resources-sprite-icons.png") no-repeat 0 0;
background-position: -194px -62px;
}

.label[data-format=arcgis_rest] {
background-color: #5c3ee0;
}
38 changes: 38 additions & 0 deletions ckanext/geoview/public/css/shp_preview.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
html, body {
max-height: 600px;
padding: 0;
margin: 0;
background: none;
}

#map {
position: absolute;
width: 100%;
height: 100%;
}

#map .table{
width: 300px;
}

#map label {
font-weight: normal;
}

#map label:after {
content: none;
}

#map input {
width: auto;
top: auto;
}

.leaflet-popup-content-wrapper {
box-shadow: 0 1px 7px rgba(0,0,0,0.4);
background: #f8f8f9;
-webkit-border-radius: 5px;
border-radius: 5px;
overflow: auto;
max-height: 200px;
}
Binary file modified ckanext/geoview/public/img/gis-resources-sprite-icons.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified ckanext/geoview/public/img/gis-resources-sprite-icons.psd
Binary file not shown.
102 changes: 102 additions & 0 deletions ckanext/geoview/public/js/shp_preview.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// shapefile preview module
ckan.module('shppreview', function (jQuery, _) {
return {
options: {
table: '<table class="table table-striped table-bordered table-condensed"><tbody>{body}</tbody></table>',
row:'<tr><th>{key}</th><td>{value}</td></tr>',
style: {
fillColor: '#03F',
opacity: 0.7,
fillOpacity: 0.1,
weight: 2
},
i18n: {
'error': _('An error occurred: %(text)s %(error)s')
}
},
initialize: function () {
var self = this;

self.el.empty();
self.el.append($('<div></div>').attr('id', 'map'));
self.map = ckan.commonLeafletMap('map', this.options.map_config);

// hack to make leaflet use a particular location to look for images
L.Icon.Default.imagePath = this.options.site_url + 'js/vendor/leaflet/dist/images';

jQuery.get(preload_resource['url']).done(
function(data){
self.showPreview(preload_resource['url']);
})
.fail(
function(jqXHR, textStatus, errorThrown) {
self.showError(jqXHR, textStatus, errorThrown);
}
);
},

showError: function (jqXHR, textStatus, errorThrown) {
if (textStatus == 'error' && jqXHR.responseText.length) {
this.el.html(jqXHR.responseText);
} else {
this.el.html(this.i18n('error', {text: textStatus, error: errorThrown}));
}
},

showPreview: function (url) {
var self = this;
var encoding, crs;

function highLightStyle(e) {
gjLayer.eachLayer(function(l) {
gjLayer.resetStyle(l);
});
if('setStyle' in e.target) e.target.setStyle({
fillColor: '#FF0',
fillOpacity: 0.6
});
}

self.map.spin(true);
var gjLayer = L.geoJson([], {
style: self.options.style,
onEachFeature: function(feature, layer) {
var body = '';
jQuery.each(feature.properties, function(key, value) {
if (value != null && typeof value === 'object') {
value = JSON.stringify(value);
}
body += L.Util.template(self.options.row, {key: key, value: value});
});
var popupContent = L.Util.template(self.options.table, {body: body});
layer.bindPopup(popupContent);
layer.on({click: highLightStyle});
}
}).addTo(self.map);

if (preload_resource.encoding)
encoding = preload_resource.encoding;
else if (this.options.shp_config.encoding)
encoding = this.options.shp_config.encoding;
else
encoding = 'utf-8';

if (preload_resource.resource_crs)
crs = preload_resource.resource_crs;
else if (this.options.shp_config.srid)
crs = this.options.shp_config.srid;
else
crs = '4326';

loadshp({
url: url,
encoding: encoding,
EPSG: crs
}, function(data) {
gjLayer.addData(data);
self.map.fitBounds(gjLayer.getBounds());
self.map.spin(false);
});
}
}
});
10 changes: 10 additions & 0 deletions ckanext/geoview/public/js/vendor/jszip/jszip-utils.js

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

14 changes: 14 additions & 0 deletions ckanext/geoview/public/js/vendor/jszip/jszip.js

Large diffs are not rendered by default.

41 changes: 41 additions & 0 deletions ckanext/geoview/public/js/vendor/leaflet.spin/leaflet.spin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
L.SpinMapMixin = {
spin: function (state, options) {
if (!!state) {
// start spinning !
if (!this._spinner) {
this._spinner = new Spinner(options).spin(this._container);
this._spinning = 0;
}
this._spinning++;
}
else {
this._spinning--;
if (this._spinning <= 0) {
// end spinning !
if (this._spinner) {
this._spinner.stop();
this._spinner = null;
}
}
}
}
};

L.Map.include(L.SpinMapMixin);

L.Map.addInitHook(function () {
this.on('layeradd', function (e) {
// If added layer is currently loading, spin !
if (e.layer.loading) this.spin(true);
if (typeof e.layer.on != 'function') return;
e.layer.on('data:loading', function () { this.spin(true); }, this);
e.layer.on('data:loaded', function () { this.spin(false); }, this);
}, this);
this.on('layerremove', function (e) {
// Clean-up
if (e.layer.loading) this.spin(false);
if (typeof e.layer.on != 'function') return;
e.layer.off('data:loaded');
e.layer.off('data:loading');
}, this);
});
22 changes: 22 additions & 0 deletions ckanext/geoview/public/js/vendor/shp2geojson/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
The MIT License (MIT)

Copyright (c) 2015 Gipong

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Loading