v.import.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: v.import
  5. #
  6. # AUTHOR(S): Markus Metz
  7. #
  8. # PURPOSE: Import and reproject vector data on the fly
  9. #
  10. # COPYRIGHT: (C) 2015 by GRASS development team
  11. #
  12. # This program is free software under the GNU General
  13. # Public License (>=v2). Read the file COPYING that
  14. # comes with GRASS for details.
  15. #
  16. #############################################################################
  17. #%module
  18. #% description: Imports vector data into a GRASS vector map using OGR library and reproject on the fly.
  19. #% keyword: vector
  20. #% keyword: import
  21. #% keyword: projection
  22. #%end
  23. #%option
  24. #% key: input
  25. #% type: string
  26. #% required: yes
  27. #% description: Name of OGR datasource to be imported
  28. #% gisprompt: old,datasource,datasource
  29. #%end
  30. #%option
  31. #% key: layer
  32. #% type: string
  33. #% multiple: yes
  34. #% description: OGR layer name. If not given, all available layers are imported
  35. #% guisection: Input
  36. #% gisprompt: old,datasource_layer,datasource_layer
  37. #%end
  38. #%option G_OPT_V_OUTPUT
  39. #% description: Name for output vector map (default: input)
  40. #% required: no
  41. #% guisection: Output
  42. #%end
  43. #%option
  44. #% key: extent
  45. #% type: string
  46. #% options: input,region
  47. #% answer: input
  48. #% description: Ouput vector map extent
  49. #% descriptions: input;extent of input map;region;extent of current region
  50. #% guisection: Output
  51. #%end
  52. #%option
  53. #% key: encoding
  54. #% type: string
  55. #% label: Encoding value for attribute data
  56. #% descriptions: Overrides encoding interpretation, useful when importing ESRI Shapefile
  57. #% guisection: Output
  58. #%end
  59. #%flag
  60. #% key: f
  61. #% description: List supported OGR formats and exit
  62. #% suppress_required: yes
  63. #%end
  64. #%flag
  65. #% key: l
  66. #% description: List available OGR layers in data source and exit
  67. #%end
  68. import sys
  69. import os
  70. import shutil
  71. import atexit
  72. import math
  73. import grass.script as grass
  74. from grass.exceptions import CalledModuleError
  75. def cleanup():
  76. # remove temp location
  77. if tmploc:
  78. grass.try_rmdir(os.path.join(gisdbase, tmploc))
  79. if srcgisrc:
  80. grass.try_remove(srcgisrc)
  81. def main():
  82. global tmploc, srcgisrc, gisdbase
  83. # initialize global vars
  84. tmploc = None
  85. srcgisrc = None
  86. gisdbase = None
  87. # list formats and exit
  88. if flags['f']:
  89. grass.run_command('v.in.ogr', flags='f')
  90. return 0
  91. # list layers and exit
  92. if flags['l']:
  93. grass.run_command('v.in.ogr', flags='l', input=options['input'])
  94. return 0
  95. OGRdatasource = options['input']
  96. output = options['output']
  97. layers = options['layer']
  98. vflags = None
  99. if options['extent'] == 'region':
  100. vflags = 'r'
  101. vopts = {}
  102. if options['encoding']:
  103. vopts['encoding'] = options['encoding']
  104. grassenv = grass.gisenv()
  105. tgtloc = grassenv['LOCATION_NAME']
  106. tgtmapset = grassenv['MAPSET']
  107. gisdbase = grassenv['GISDBASE']
  108. tgtgisrc = os.environ['GISRC']
  109. srcgisrc = grass.tempfile()
  110. tmploc = 'temp_import_location_' + str(os.getpid())
  111. f = open(srcgisrc, 'w')
  112. f.write('MAPSET: PERMANENT\n')
  113. f.write('GISDBASE: %s\n' % gisdbase)
  114. f.write('LOCATION_NAME: %s\n' % tmploc);
  115. f.write('GUI: text\n')
  116. f.close()
  117. tgtsrs = grass.read_command('g.proj', flags = 'j', quiet = True)
  118. # create temp location from input without import
  119. grass.verbose(_("Creating temporary location for <%s>...") % OGRdatasource)
  120. if layers:
  121. vopts['layer'] = layers
  122. if output:
  123. vopts['output'] = output
  124. try:
  125. grass.run_command('v.in.ogr', input = OGRdatasource,
  126. location = tmploc, flags = 'i', quiet = True, **vopts)
  127. except CalledModuleError:
  128. grass.fatal(_("Unable to create location from OGR datasource <%s>") % OGRdatasource)
  129. # switch to temp location
  130. os.environ['GISRC'] = str(srcgisrc)
  131. # switch to target location
  132. os.environ['GISRC'] = str(tgtgisrc)
  133. # try v.in.ogr directly
  134. if grass.run_command('v.in.ogr', input=OGRdatasource, flags='j',
  135. errors='status', quiet=True) == 0:
  136. try:
  137. grass.run_command('v.in.ogr', input = OGRdatasource,
  138. flags = vflags, **vopts)
  139. grass.message(_("Input <%s> successfully imported without reprojection") % OGRdatasource)
  140. return 0
  141. except CalledModuleError as e:
  142. grass.fatal(_("Unable to import <%s>") % OGRdatasource)
  143. # make sure target is not xy
  144. if grass.parse_command('g.proj', flags = 'g')['name'] == 'xy_location_unprojected':
  145. grass.fatal(_("Coordinate reference system not available for current location <%s>") % tgtloc)
  146. # switch to temp location
  147. os.environ['GISRC'] = str(srcgisrc)
  148. # make sure input is not xy
  149. if grass.parse_command('g.proj', flags = 'g')['name'] == 'xy_location_unprojected':
  150. grass.fatal(_("Coordinate reference system not available for input <%s>") % GDALdatasource)
  151. if options['extent'] == 'region':
  152. # switch to target location
  153. os.environ['GISRC'] = str(tgtgisrc)
  154. # v.in.region in tgt
  155. vreg = 'vreg_' + str(os.getpid())
  156. grass.run_command('v.in.region', output = vreg, quiet = True)
  157. # reproject to src
  158. # switch to temp location
  159. os.environ['GISRC'] = str(srcgisrc)
  160. try:
  161. grass.run_command('v.proj', input = vreg, output = vreg,
  162. location = tgtloc, mapset = tgtmapset, quiet = True)
  163. except CalledModuleError:
  164. grass.fatal(_("Unable to reproject to source location"))
  165. # set region from region vector
  166. grass.run_command('g.region', res = '1')
  167. grass.run_command('g.region', vector = vreg)
  168. # import into temp location
  169. grass.message(_("Importing <%s> ...") % OGRdatasource)
  170. try:
  171. grass.run_command('v.in.ogr', input = OGRdatasource,
  172. flags = vflags, **vopts)
  173. except CalledModuleError:
  174. grass.fatal(_("Unable to import OGR datasource <%s>") % OGRdatasource)
  175. # if output is not define check source mapset
  176. if not output:
  177. output = grass.list_grouped('vector')['PERMANENT'][0]
  178. # switch to target location
  179. os.environ['GISRC'] = str(tgtgisrc)
  180. # check if map exists
  181. if not grass.overwrite() and \
  182. grass.find_file(output, element='vector', mapset='.')['mapset']:
  183. grass.fatal(_("option <%s>: <%s> exists.") % ('output', output))
  184. if options['extent'] == 'region':
  185. grass.run_command('g.remove', type = 'vector', name = vreg,
  186. flags = 'f', quiet = True)
  187. # v.proj
  188. grass.message(_("Reprojecting <%s>...") % output)
  189. try:
  190. grass.run_command('v.proj', location = tmploc,
  191. mapset = 'PERMANENT', input = output,
  192. quiet = True)
  193. except CalledModuleError:
  194. grass.fatal(_("Unable to to reproject vector <%s>") % output)
  195. return 0
  196. if __name__ == "__main__":
  197. options, flags = grass.parser()
  198. atexit.register(cleanup)
  199. sys.exit(main())