1

TL,DR; I want to get a random point from a polygon (potentially) using ST_GeneratePoints.


Background

I'm making a GeoDjango webservice and have a collection of UK Postcodes with respective boundaries like so:

from django.db import models as dj_models
from django.contrib.gis.db import models as gis_models

class Postcode(gis_models.Model):
      pretty_postcode = dj_models.CharField( max_length=8 )
      coords = gis_models.PolygonField( default='POLYGON EMPTY' )

I've found a delightful little PostGis function ST_GeneratePoints, it can find me random points in my coords region.

Your Challenge

Your mission if you so choose it, is to show how to use this function from within my python django app (or suggest a better way). Ideally ending up with a function like so:

from django.contrib.gis import geos
# ... other imports ...

class Postcode(gis_models.Model):
     # ... fields ...

     def get_random_point(self):
         rand_point = # code that executes ST_GeneratePoints
                      # and returns a geos.Point instance
         return rand_point

closed as unclear what you're asking by Mapperz Nov 24 '17 at 14:49

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

0

You can execute raw sql using a connection cursor. Something along the lines of the snippet below (which I have not tested, so it might not work 1:1 as it is shown)

from django.db import connection

def get_random_point(self):
    # Return only one point in the geometry.
    npoints = 1
    # Prepare sql command, return point as ewkt, passing the 
    # bounding geometry as ewkt.
    sql = 'SELECT ST_AsEWKT(ST_GeneratePoints(ST_GeomFromEWKT({ewkt}), npoints))'
    # Instanciate cursor.
    cursor = connection.cursor()
    # Inject coords into sql command and execute sql.
    cursor.execute(sql.format(ewkt=self.coords.ewkt))
    row = cursor.fetchall()
    # Convert result to python geometry.
    return OGRGeometry(row[0])

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