Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import csv
- import random
- from datetime import datetime
- from osgeo import ogr
- from shapely.geometry import Point
- from shapely.prepared import prep
- from shapely.wkb import loads
- start_time = all_start_time = datetime.now()
- 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
- # Get the geometry of India
- India = loads(feat.GetGeometryRef().ExportToWkb())
- IndiaP = prep(India)
- print 'reading/searching shapefile:', datetime.now() - start_time
- start_time = datetime.now()
- lon_min, lat_min, lon_max, lat_max = India.bounds # Now get the envelope
- n_points = 0 # A counter
- india_lonlat = [] # A list where we'll store longitudes/latitudes within India
- while n_points < 10000: # Until we reach our required number of points...
- # Draw random longitudes and latitudes within the envelope
- r_lon = random.uniform(lon_min, lon_max)
- r_lat = random.uniform(lat_min, lat_max)
- pt = Point(r_lon, r_lat)
- # Is this geometry within India?
- if IndiaP.contains(pt):
- # yes! Store the latitude&longitude and update counter
- india_lonlat.append([r_lon, r_lat])
- n_points += 1
- print 'generated', n_points, 'points:', datetime.now() - start_time
- start_time = datetime.now()
- # Save to a CSV file
- fp = open('india.csv', 'wb')
- w = csv.writer(fp)
- w.writerow(['Longitude', 'Latitude'])# Header
- w.writerows(india_lonlat)
- fp.close()
- print 'wrote CSV file:', datetime.now() - start_time
- start_time = datetime.now()
- print 'total time:', datetime.now() - all_start_time
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement