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