If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!

Demo app available at https://github.com/ilvalle/w2pgis

Table definition (models/db.py):

db = DAL('postgres://web2py:web2py@localhost:5432/testw2p', lazy_tables=False,)

db.define_table('geostuff',
    Field('name', 'string'),
    Field('geometry', 'geometry()'),
)
n_rows = db(db.geostuff).count()
if not n_rows:
    db.geostuff.insert(name="My first geo point (London!)", geometry="POINT(-0.091109 51.512622)")
    db.geostuff.insert(name="My first linestring", geometry="LINESTRING (8.791595 45.660281, 11.343062 44.494932, 10.394590 43.722998)")

 

Controller (controllers/default.py):

from gluon.serializers import loads_json

def index(): 
    response.files.append('http://cdn.leafletjs.com/leaflet-0.7/leaflet.js')
    response.files.append('http://cdn.leafletjs.com/leaflet-0.7/leaflet.css')
    return {}

def get_geojson():
    rows= db(db.geostuff).select(db.geostuff.name, db.geostuff.geometry.st_asgeojson())

    features= [{"type": "Feature",
                "properties": {
                    "popupContent": r[db.geostuff.name]
                },
                "geometry": loads_json(r[db.geostuff.geometry.st_asgeojson()])} for r in rows] 

    return response.json({"type": "FeatureCollection", 'features': features})

 

and the final view (views/default/index.html):

{{left_sidebar_enabled,right_sidebar_enabled=False,True}}
{{extend 'layout.html'}}

<div id='map' style="height: 500px;"></div>
<script>
    var map = L.map('map').setView([51.505, -0.09], 2);
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    $(document).on('click', '#add', function() {
        $.getJSON('{{=URL('default', 'get_geojson')}}', function( data ) { 
            L.geoJson(data, {
                onEachFeature: onEachFeature}).addTo(map); 
        });
    });
    
    function onEachFeature (feature, layer) {
        var popupContent;
        if (feature.properties && feature.properties.popupContent) {
            popupContent = feature.properties.popupContent;
        }

        layer.bindPopup(popupContent);
    }
</script>
{{block right_sidebar}}
    <button id='add'>Add geojson</button>
{{pass}}

 

Comments (0)


Hosting graciously provided by:
Python Anywhere