I am in need of around 10000 and odd Indian latitude and longitude values for my openlayers project. I have to load them in a postgis db. so a sql file or atleast text file would be better than a link.
This is a nice problem for OGR's python interface. This is my attempt, using world.shp. Here's my code snippet:
from osgeo import ogr # Import ogr import random # Random number generators etc. g = ogr.Open ("world.shp") # Open the shapefile with all the world's countries # Loop over the different features until we find INDIA. for feat in g.GetLayer(0): if feat.GetFieldAsString("NAME").find ("INDIA") >= 0: break # We found India, break out of the loop. # feat now holds the feature of INDIA geom = feat.GetGeometryRef() # Get the geometry of Indina ( lon_min, lon_max, lat_min, lat_max ) = geom.GetEnvelope() # Now get the envelope n_points = 0 # A counter india_lon =  # A list where we'll store longitudes within India india_lat =  # A list where we'll store latitudes within India while n_points < 1000: # Until we reach our required number of points... # Draw random longitudes and latitudes within the envelope r_lon = random.random()*(lon_max - lon_min ) + lon_min r_lat = random.random()*(lat_max - lat_min ) + lat_min # Create a point geometry pt = ogr.Geometry( ogr.wkbPoint ) pt.SetPoint_2D( 0, r_lon, r_lat ) # Is this geometry within india? if pt.Within ( geom ): # yes! Store the latitude&longitude and update counter india_lon.append ( r_lon ) india_lat.append ( r_lat ) n_points = n_points + 1 # Save to a CSV file fp=open("india.txt", 'w' ) fp.write( "Longitude, Latitude\n" )# Header for (lon, lat) in zip (india_lon, india_lat): fp.write ("%f,%f\n" % ( lon, lat ) ) fp.close()
And here's how the result looks like:
Not the most efficient way of dealing with this, but nice to learn :)
You can generate 10000 random points within a polygon of India. There has been some recent work to do this:
- Random Points in Polygon in JTS (Martin Davis' blog)
- Random Point in Polygon for PostGIS (PostGIS wiki)
Update I've added a set-returning function to the PostGIS User's wiki, where I've used this question as an example. See that page for details. Although PostGIS also uses a prepared geometry, it isn't as fast as Shapely. My best speed for 10k points is 3023 ms (compared with 1125 ms for Shapely for same problem).