1

My Python Google App Engine (no tag?) app has a datastore model of an Area of Interest, simplified as

import geojson
class AreaOfInterest(db.Model):
    name = db.StringProperty(required=True)
    #Geometry of area boundary
    coordinates = db.ListProperty(db.GeoPt, default=None) #convex polygon without holes

I wish to export this as GeoJSON, but am unsure of a (preferably Pythonic) way to convert the List of GeoPt to a geojson.Polygon object. Although I can convert to an array of Points with

coords = []
for c in self.coordinates:
    p = geojson.Point((c.lat, c.lon))
    coords.append(p)

I wish to embedd a Polygon into a GeoJson FeatureCollection thus:

def geojsonArea(self):
    polygon = geojson.Polygon((self.coordinates)) 
    #ValueError: Expect __geo_interface__' or a mapping, got datastore_types.GeoPt
    geojson_obj =   { 
        "type": "FeatureCollection",
        "area_name" :self.name,
        "features": [
          { "type": "Feature",
             "geometry": {
               "type": "Polygon",
               "coordinates": polygon
             },
             "properties": {
                "name": "boundary"
           }
        }
        ]
    }
    return geojson.dumps(geojson_obj)

But the call to geojson.Polygon expects something like Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]])

What is the cleanest way to make this conversion? Is it possible without looping through the list while building a string to pass to Polygon()?

1

This might not be the most Pythonic solution but it works. The resulting string complies with http://geojsonlint.com/.

def geojsonArea(self):
    coords = []
    for c in self.coordinates:
        p = {'lat': c.lat, 'lng': c.lon}
        coords.append(p)

    geojson_obj =   { 
        "type": "FeatureCollection",
        "area_name" :self.name,
        "features": [
          { "type": "Feature",
             "geometry": {
                 "type": "Polygon", 
                 "coordinates" : coords
            },
             "properties": {
                "name": "boundary"
           }
        }
        ]
    }
    return geojson.dumps(geojson_obj)

Converting a db.GeoPt to a Point has a different syntax to Polygon.

map_center = db.GeoPtProperty()     

def geojsonArea(self):
    center = []
    center.append(geojson.Point({'lat': self.map_center.lat, 'lng': self.map_center.lon}))
    #... 
    { 
      "type": "ViewPort",
      "geometry": center, 
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.