I am very much strrugling on how to display my shapefiles stored in postgis database to the browser or to the web.. is there anyone there knows how to do it.? I am using geodjango framework in python,. I already achieve the displaying of maps in admin interface but when I create my public page for displaying the maps, its make my head aching,.I did not konow how to overlay my shapefiles stored in database to the base map openlayers / openstreetmap.
1 Answers
I would recommend to use the Django-rest-framework together with a small plugin called django-rest-framework-gis. With those two tools you can create a API endpoint that returns your spatial data in a geojson format.
You can then use front-end libraries such as Leaflet or OpenLayers to map your data on a website. Both of those libraries can handle geojson as data input for their layers.
The setup for the API endpoint is the more complicated part here, and in the beginning it takes some time to get used to the rest-framework. But in my eyes its well worth the effort.
Below is some example code for a Django setup to produce a geojson api endpoint, and an example of how to add it to a leaflet map on the front end (note that this code is meant as a guidance and is untested).
models.py
from django.contrib.gis.db import models
class SpatialData(models.Model):
name = models.CharField(max_length = 100)
description = models.TextField()
geom = models.PolygonField()
objects = models.GeoManager()
serializers.py
from rest_framework_gis.serializers import GeoFeatureModelSerializer
from .models import SpatialData
class SpatialDataSerializer(GeoFeatureModelSerializer):
class Meta:
model = SpatialData
geo_field = 'geom'
fields = ('name', 'description', )
views.py
from rest_framework import viewsets
from rest_framework_gis.filters import InBBOXFilter
from .models import SpatialData
from .serializers import SpatialDataSerializer
class SpatialDataViewSet(viewsets.ModelViewSet):
queryset = SpatialData.objects.all()
serializer_class = SpatialDataSerializer
filter_backends = (InBBOXFilter, )
urls.py
from django.conf.urls import patterns, include
from rest_framework import routers
from .views import SpatialDataViewSet
router = routers.DefaultRouter(trailing_slash=False)
router.register(r'spatialdata', SpatialDataViewSet)
urlpatterns = patterns('',
url(r'^api/', include(router.urls)),
)
map.js (this assumes you have a html page setup with leaflet imports, see for instance the quickstart totorial)
// Create map and layer variable
var map = L.map('map').setView([51.505, -0.09], 13);
var lyr;
// On moveend, update layer
map.on('moveend', function(){
// Remove previous version of layer
if(map.hasLayer(lyr)){
map.removeLayer(lyr);
}
// Add data for current view extent
bbox_filter = '&in_bbox=' + map.getBounds().toBBoxString();
$.getJSON('api/spatialdata?' + bbox_filter, function(data){
var lyr = L.geoJson(data.results).addTo(map);
});
});
- 3,013
- 22
- 36