Sunday, 11 November 2018

postgis - Indian Latitude Longitude values


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.



Answer



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: One thousand random points over India


Not the most efficient way of dealing with this, but nice to learn :)


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...