convert.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  1. /*!
  2. \file lib/proj/convert.c
  3. \brief GProj Library - Functions for manipulating co-ordinate
  4. system representations
  5. (C) 2003-2018 by the GRASS Development Team
  6. This program is free software under the GNU General Public License
  7. (>=v2). Read the file COPYING that comes with GRASS for details.
  8. \author Paul Kelly, Frank Warmerdam, Markus Metz
  9. */
  10. #include <grass/config.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <math.h>
  15. #include <grass/gis.h>
  16. #include <grass/gprojects.h>
  17. #include <grass/glocale.h>
  18. #ifdef HAVE_OGR
  19. #include <cpl_csv.h>
  20. #include "local_proto.h"
  21. /* GRASS relative location of OGR co-ordinate system lookup tables */
  22. #define CSVDIR "/etc/proj/ogr_csv"
  23. static void DatumNameMassage(char **);
  24. #endif
  25. /* from proj-5.0.0/src/pj_units.c */
  26. struct gpj_units {
  27. char *id; /* units keyword */
  28. char *to_meter; /* multiply by value to get meters */
  29. char *name; /* comments */
  30. double factor; /* to_meter factor in actual numbers */
  31. };
  32. struct gpj_units
  33. gpj_units[] = {
  34. {"km", "1000.", "Kilometer", 1000.0},
  35. {"m", "1.", "Meter", 1.0},
  36. {"dm", "1/10", "Decimeter", 0.1},
  37. {"cm", "1/100", "Centimeter", 0.01},
  38. {"mm", "1/1000", "Millimeter", 0.001},
  39. {"kmi", "1852.0", "International Nautical Mile", 1852.0},
  40. {"in", "0.0254", "International Inch", 0.0254},
  41. {"ft", "0.3048", "International Foot", 0.3048},
  42. {"yd", "0.9144", "International Yard", 0.9144},
  43. {"mi", "1609.344", "International Statute Mile", 1609.344},
  44. {"fath", "1.8288", "International Fathom", 1.8288},
  45. {"ch", "20.1168", "International Chain", 20.1168},
  46. {"link", "0.201168", "International Link", 0.201168},
  47. {"us-in", "1./39.37", "U.S. Surveyor's Inch", 0.0254},
  48. {"us-ft", "0.304800609601219", "U.S. Surveyor's Foot", 0.304800609601219},
  49. {"us-yd", "0.914401828803658", "U.S. Surveyor's Yard", 0.914401828803658},
  50. {"us-ch", "20.11684023368047", "U.S. Surveyor's Chain", 20.11684023368047},
  51. {"us-mi", "1609.347218694437", "U.S. Surveyor's Statute Mile", 1609.347218694437},
  52. {"ind-yd", "0.91439523", "Indian Yard", 0.91439523},
  53. {"ind-ft", "0.30479841", "Indian Foot", 0.30479841},
  54. {"ind-ch", "20.11669506", "Indian Chain", 20.11669506},
  55. {NULL, NULL, NULL, 0.0}
  56. };
  57. static char *grass_to_wkt(const struct Key_Value *proj_info,
  58. const struct Key_Value *proj_units,
  59. const struct Key_Value *proj_epsg,
  60. int esri_style, int prettify)
  61. {
  62. #ifdef HAVE_OGR
  63. OGRSpatialReferenceH hSRS;
  64. char *wkt, *local_wkt;
  65. hSRS = GPJ_grass_to_osr2(proj_info, proj_units, proj_epsg);
  66. if (hSRS == NULL)
  67. return NULL;
  68. if (esri_style)
  69. OSRMorphToESRI(hSRS);
  70. if (prettify)
  71. OSRExportToPrettyWkt(hSRS, &wkt, 0);
  72. else
  73. OSRExportToWkt(hSRS, &wkt);
  74. local_wkt = G_store(wkt);
  75. CPLFree(wkt);
  76. OSRDestroySpatialReference(hSRS);
  77. return local_wkt;
  78. #else
  79. G_warning(_("GRASS is not compiled with OGR support"));
  80. return NULL;
  81. #endif
  82. }
  83. /*!
  84. * \brief Converts a GRASS co-ordinate system representation to WKT style.
  85. *
  86. * Takes a GRASS co-ordinate system as specified by two sets of
  87. * key/value pairs derived from the PROJ_INFO and PROJ_UNITS files,
  88. * and converts it to the 'Well Known Text' format.
  89. *
  90. * \param proj_info Set of GRASS PROJ_INFO key/value pairs
  91. * \param proj_units Set of GRASS PROJ_UNIT key/value pairs
  92. * \param esri_style boolean Output ESRI-style WKT (Use OSRMorphToESRI()
  93. * function provided by OGR library)
  94. * \param prettify boolean Use linebreaks and indents to 'prettify' output
  95. * WKT string (Use OSRExportToPrettyWkt() function in OGR)
  96. *
  97. * \return Pointer to a string containing the co-ordinate system in
  98. * WKT format
  99. * \return NULL on error
  100. */
  101. char *GPJ_grass_to_wkt(const struct Key_Value *proj_info,
  102. const struct Key_Value *proj_units,
  103. int esri_style, int prettify)
  104. {
  105. return grass_to_wkt(proj_info, proj_units, NULL, esri_style, prettify);
  106. }
  107. /*!
  108. * \brief Converts a GRASS co-ordinate system representation to WKT
  109. * style. EPSG code is preferred if available.
  110. *
  111. * Takes a GRASS co-ordinate system as specified key/value pairs
  112. * derived from the PROJ_EPSG file. TOWGS84 parameter is scanned
  113. * from PROJ_INFO file and appended to co-ordinate system definition
  114. * imported from EPSG code by GDAL library. PROJ_UNITS file is
  115. * ignored. The function converts it to the 'Well Known Text' format.
  116. *
  117. * \todo Merge with GPJ_grass_to_wkt() in GRASS 8.
  118. *
  119. * \param proj_info Set of GRASS PROJ_INFO key/value pairs
  120. * \param proj_units Set of GRASS PROJ_UNIT key/value pairs
  121. * \param proj_epsg Set of GRASS PROJ_EPSG key/value pairs
  122. * \param esri_style boolean Output ESRI-style WKT (Use OSRMorphToESRI()
  123. * function provided by OGR library)
  124. * \param prettify boolean Use linebreaks and indents to 'prettify' output
  125. * WKT string (Use OSRExportToPrettyWkt() function in OGR)
  126. *
  127. * \return Pointer to a string containing the co-ordinate system in
  128. * WKT format
  129. * \return NULL on error
  130. */
  131. char *GPJ_grass_to_wkt2(const struct Key_Value *proj_info,
  132. const struct Key_Value *proj_units,
  133. const struct Key_Value *proj_epsg,
  134. int esri_style, int prettify)
  135. {
  136. return grass_to_wkt(proj_info, proj_units, proj_epsg, esri_style, prettify);
  137. }
  138. #ifdef HAVE_OGR
  139. /*!
  140. * \brief Converts a GRASS co-ordinate system to an OGRSpatialReferenceH object.
  141. *
  142. * \param proj_info Set of GRASS PROJ_INFO key/value pairs
  143. * \param proj_units Set of GRASS PROJ_UNIT key/value pairs
  144. *
  145. * \return OGRSpatialReferenceH object representing the co-ordinate system
  146. * defined by proj_info and proj_units or NULL if it fails
  147. */
  148. OGRSpatialReferenceH GPJ_grass_to_osr(const struct Key_Value * proj_info,
  149. const struct Key_Value * proj_units)
  150. {
  151. struct pj_info pjinfo;
  152. char *proj4, *proj4mod, *wkt, *modwkt, *startmod, *lastpart;
  153. OGRSpatialReferenceH hSRS, hSRS2;
  154. OGRErr errcode;
  155. struct gpj_datum dstruct;
  156. struct gpj_ellps estruct;
  157. size_t len;
  158. const char *ellpskv, *unit, *unfact;
  159. char *ellps, *ellpslong, *datum, *params, *towgs84, *datumlongname,
  160. *start, *end;
  161. const char *sysname, *osrunit, *osrunfact;
  162. double a, es, rf;
  163. int haveparams = 0;
  164. if ((proj_info == NULL) || (proj_units == NULL))
  165. return NULL;
  166. hSRS = OSRNewSpatialReference(NULL);
  167. /* create PROJ structure from GRASS key/value pairs */
  168. if (pj_get_kv(&pjinfo, proj_info, proj_units) < 0) {
  169. G_warning(_("Unable parse GRASS PROJ_INFO file"));
  170. return NULL;
  171. }
  172. /* fetch the PROJ definition */
  173. /* TODO: get the PROJ definition as used by pj_get_kv() */
  174. if ((proj4 = pjinfo.def) == NULL) {
  175. G_warning(_("Unable get PROJ.4-style parameter string"));
  176. return NULL;
  177. }
  178. #ifdef HAVE_PROJ_H
  179. proj_destroy(pjinfo.pj);
  180. #else
  181. pj_free(pjinfo.pj);
  182. #endif
  183. unit = G_find_key_value("unit", proj_units);
  184. unfact = G_find_key_value("meters", proj_units);
  185. if (unfact != NULL && (strcmp(pjinfo.proj, "ll") != 0))
  186. G_asprintf(&proj4mod, "%s +to_meter=%s", proj4, unfact);
  187. else
  188. proj4mod = G_store(proj4);
  189. /* create GDAL OSR from proj string */
  190. if ((errcode = OSRImportFromProj4(hSRS, proj4mod)) != OGRERR_NONE) {
  191. G_warning(_("OGR can't parse PROJ.4-style parameter string: "
  192. "%s (OGR Error code was %d)"), proj4mod, errcode);
  193. return NULL;
  194. }
  195. G_free(proj4mod);
  196. /* this messes up PROJCS versus GEOGCS!
  197. sysname = G_find_key_value("name", proj_info);
  198. if (sysname)
  199. OSRSetProjCS(hSRS, sysname);
  200. */
  201. if ((errcode = OSRExportToWkt(hSRS, &wkt)) != OGRERR_NONE) {
  202. G_warning(_("OGR can't get WKT-style parameter string "
  203. "(OGR Error code was %d)"), errcode);
  204. return NULL;
  205. }
  206. ellpskv = G_find_key_value("ellps", proj_info);
  207. GPJ__get_ellipsoid_params(proj_info, &a, &es, &rf);
  208. haveparams = GPJ__get_datum_params(proj_info, &datum, &params);
  209. if (ellpskv != NULL)
  210. ellps = G_store(ellpskv);
  211. else
  212. ellps = NULL;
  213. if ((datum == NULL) || (GPJ_get_datum_by_name(datum, &dstruct) < 0)) {
  214. datumlongname = G_store("unknown");
  215. if (ellps == NULL)
  216. ellps = G_store("unnamed");
  217. }
  218. else {
  219. datumlongname = G_store(dstruct.longname);
  220. if (ellps == NULL)
  221. ellps = G_store(dstruct.ellps);
  222. GPJ_free_datum(&dstruct);
  223. }
  224. G_debug(3, "GPJ_grass_to_osr: datum: <%s>", datum);
  225. G_free(datum);
  226. if (GPJ_get_ellipsoid_by_name(ellps, &estruct) > 0) {
  227. ellpslong = G_store(estruct.longname);
  228. DatumNameMassage(&ellpslong);
  229. GPJ_free_ellps(&estruct);
  230. }
  231. else
  232. ellpslong = G_store(ellps);
  233. startmod = strstr(wkt, "GEOGCS");
  234. lastpart = strstr(wkt, "PRIMEM");
  235. len = strlen(wkt) - strlen(startmod);
  236. wkt[len] = '\0';
  237. if (haveparams == 2) {
  238. /* Only put datum params into the WKT if they were specifically
  239. * specified in PROJ_INFO */
  240. char *paramkey, *paramvalue;
  241. paramkey = strtok(params, "=");
  242. paramvalue = params + strlen(paramkey) + 1;
  243. if (G_strcasecmp(paramkey, "towgs84") == 0)
  244. G_asprintf(&towgs84, ",TOWGS84[%s]", paramvalue);
  245. else
  246. towgs84 = G_store("");
  247. G_free(params);
  248. }
  249. else
  250. towgs84 = G_store("");
  251. sysname = OSRGetAttrValue(hSRS, "PROJCS", 0);
  252. if (sysname == NULL) {
  253. /* Not a projected co-ordinate system */
  254. start = G_store("");
  255. end = G_store("");
  256. }
  257. else {
  258. if ((strcmp(sysname, "unnamed") == 0) &&
  259. (G_find_key_value("name", proj_info) != NULL))
  260. G_asprintf(&start, "PROJCS[\"%s\",",
  261. G_find_key_value("name", proj_info));
  262. else
  263. start = G_store(wkt);
  264. osrunit = OSRGetAttrValue(hSRS, "UNIT", 0);
  265. osrunfact = OSRGetAttrValue(hSRS, "UNIT", 1);
  266. if ((unfact == NULL) || (G_strcasecmp(osrunit, "unknown") != 0))
  267. end = G_store("");
  268. else {
  269. char *buff;
  270. double unfactf = atof(unfact);
  271. G_asprintf(&buff, ",UNIT[\"%s\",", osrunit);
  272. startmod = strstr(lastpart, buff);
  273. len = strlen(lastpart) - strlen(startmod);
  274. lastpart[len] = '\0';
  275. G_free(buff);
  276. if (unit == NULL)
  277. unit = "unknown";
  278. G_asprintf(&end, ",UNIT[\"%s\",%.16g]]", unit, unfactf);
  279. }
  280. }
  281. OSRDestroySpatialReference(hSRS);
  282. G_asprintf(&modwkt,
  283. "%sGEOGCS[\"%s\",DATUM[\"%s\",SPHEROID[\"%s\",%.16g,%.16g]%s],%s%s",
  284. start, ellps, datumlongname, ellpslong, a, rf, towgs84,
  285. lastpart, end);
  286. hSRS2 = OSRNewSpatialReference(modwkt);
  287. G_free(modwkt);
  288. CPLFree(wkt);
  289. G_free(start);
  290. G_free(ellps);
  291. G_free(datumlongname);
  292. G_free(ellpslong);
  293. G_free(towgs84);
  294. G_free(end);
  295. return hSRS2;
  296. }
  297. /*!
  298. * \brief Converts a GRASS co-ordinate system to an
  299. * OGRSpatialReferenceH object. EPSG code is preferred if available.
  300. *
  301. * The co-ordinate system definition is imported from EPSG (by GDAL)
  302. * definition if available. TOWGS84 parameter is scanned from
  303. * PROJ_INFO file and appended to co-ordinate system definition. If
  304. * EPSG code is not available, PROJ_INFO file is used as
  305. * GPJ_grass_to_osr() does.
  306. * \todo Merge with GPJ_grass_to_osr() in GRASS 8.
  307. *
  308. * \param proj_info Set of GRASS PROJ_INFO key/value pairs
  309. * \param proj_units Set of GRASS PROJ_UNIT key/value pairs
  310. * \param proj_epsg Set of GRASS PROJ_EPSG key/value pairs
  311. *
  312. * \return OGRSpatialReferenceH object representing the co-ordinate system
  313. * defined by proj_info and proj_units or NULL if it fails
  314. */
  315. OGRSpatialReferenceH GPJ_grass_to_osr2(const struct Key_Value * proj_info,
  316. const struct Key_Value * proj_units,
  317. const struct Key_Value * proj_epsg)
  318. {
  319. int epsgcode = 0;
  320. if (proj_epsg) {
  321. const char *epsgstr = G_find_key_value("epsg", proj_epsg);
  322. if (epsgstr)
  323. epsgcode = atoi(epsgstr);
  324. }
  325. if (epsgcode) {
  326. const char *towgs84;
  327. OGRSpatialReferenceH hSRS;
  328. hSRS = OSRNewSpatialReference(NULL);
  329. OSRImportFromEPSG(hSRS, epsgcode);
  330. /* take +towgs84 from projinfo file if defined */
  331. towgs84 = G_find_key_value("towgs84", proj_info);
  332. if (towgs84) {
  333. char **tokens;
  334. int i;
  335. double df[] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
  336. tokens = G_tokenize(towgs84, ",");
  337. for (i = 0; i < G_number_of_tokens(tokens); i++)
  338. df[i] = atof(tokens[i]);
  339. G_free_tokens(tokens);
  340. OSRSetTOWGS84(hSRS, df[0], df[1], df[2], df[3], df[4], df[5], df[6]);
  341. }
  342. return hSRS;
  343. }
  344. return GPJ_grass_to_osr(proj_info, proj_units);
  345. }
  346. /*!
  347. * \brief Converts an OGRSpatialReferenceH object to a GRASS co-ordinate system.
  348. *
  349. * \param cellhd Pointer to a GRASS Cell_head structure that will have its
  350. * projection-related members populated with appropriate values
  351. * \param projinfo Pointer to a pointer which will have a GRASS Key_Value
  352. * structure allocated containing a set of GRASS PROJ_INFO values
  353. * \param projunits Pointer to a pointer which will have a GRASS Key_Value
  354. * structure allocated containing a set of GRASS PROJ_UNITS values
  355. * \param hSRS OGRSpatialReferenceH object containing the co-ordinate
  356. * system to be converted
  357. * \param datumtrans Index number of datum parameter set to use, 0 to leave
  358. * unspecified
  359. *
  360. * \return 2 if a projected or lat/long co-ordinate system has been
  361. * defined
  362. * \return 1 if an unreferenced XY co-ordinate system has
  363. * been defined
  364. */
  365. int GPJ_osr_to_grass(struct Cell_head *cellhd, struct Key_Value **projinfo,
  366. struct Key_Value **projunits, OGRSpatialReferenceH hSRS1,
  367. int datumtrans)
  368. {
  369. struct Key_Value *temp_projinfo;
  370. char *pszProj4 = NULL, *pszRemaining;
  371. char *pszProj = NULL;
  372. const char *pszProjCS = NULL;
  373. char *datum = NULL;
  374. char *proj4_unit = NULL;
  375. struct gpj_datum dstruct;
  376. const char *ograttr;
  377. OGRSpatialReferenceH hSRS;
  378. *projinfo = NULL;
  379. *projunits = NULL;
  380. hSRS = hSRS1;
  381. if (hSRS == NULL)
  382. goto default_to_xy;
  383. /* Set finder function for locating OGR csv co-ordinate system tables */
  384. /* SetCSVFilenameHook(GPJ_set_csv_loc); */
  385. /* Hopefully this doesn't do any harm if it wasn't in ESRI format
  386. * to start with... */
  387. OSRMorphFromESRI(hSRS);
  388. *projinfo = G_create_key_value();
  389. /* use proj4 definition from EXTENSION attribute if existing */
  390. ograttr = OSRGetAttrValue(hSRS, "EXTENSION", 0);
  391. if (ograttr && *ograttr && strcmp(ograttr, "PROJ4") == 0) {
  392. ograttr = OSRGetAttrValue(hSRS, "EXTENSION", 1);
  393. G_debug(3, "proj4 extension:");
  394. G_debug(3, "%s", ograttr);
  395. if (ograttr && *ograttr) {
  396. char *proj4ext;
  397. OGRSpatialReferenceH hSRS2;
  398. hSRS2 = OSRNewSpatialReference(NULL);
  399. proj4ext = G_store(ograttr);
  400. /* test */
  401. if (OSRImportFromProj4(hSRS2, proj4ext) != OGRERR_NONE) {
  402. G_warning(_("Updating spatial reference with embedded proj4 definition failed. "
  403. "Proj4 definition: <%s>"), proj4ext);
  404. OSRDestroySpatialReference(hSRS2);
  405. }
  406. else {
  407. /* use new OGR spatial reference defined with embedded proj4 string */
  408. /* TODO: replace warning with important_message once confirmed working */
  409. G_warning(_("Updating spatial reference with embedded proj4 definition"));
  410. /* -------------------------------------------------------------------- */
  411. /* Derive the user name for the coordinate system. */
  412. /* -------------------------------------------------------------------- */
  413. pszProjCS = OSRGetAttrValue(hSRS, "PROJCS", 0);
  414. if (!pszProjCS)
  415. pszProjCS = OSRGetAttrValue(hSRS, "GEOGCS", 0);
  416. if (pszProjCS) {
  417. G_set_key_value("name", pszProjCS, *projinfo);
  418. }
  419. else if (pszProj) {
  420. char path[4095];
  421. char name[80];
  422. /* use name of the projection as name for the coordinate system */
  423. sprintf(path, "%s/etc/proj/projections", G_gisbase());
  424. if (G_lookup_key_value_from_file(path, pszProj, name, sizeof(name)) >
  425. 0)
  426. G_set_key_value("name", name, *projinfo);
  427. else
  428. G_set_key_value("name", pszProj, *projinfo);
  429. }
  430. /* the original hSRS1 is left as is, ok? */
  431. hSRS = hSRS2;
  432. }
  433. G_free(proj4ext);
  434. }
  435. }
  436. /* -------------------------------------------------------------------- */
  437. /* Set cellhd for well known coordinate systems. */
  438. /* -------------------------------------------------------------------- */
  439. if (!OSRIsGeographic(hSRS) && !OSRIsProjected(hSRS))
  440. goto default_to_xy;
  441. if (cellhd) {
  442. int bNorth;
  443. if (OSRIsGeographic(hSRS)) {
  444. cellhd->proj = PROJECTION_LL;
  445. cellhd->zone = 0;
  446. }
  447. else if (OSRGetUTMZone(hSRS, &bNorth) != 0) {
  448. cellhd->proj = PROJECTION_UTM;
  449. cellhd->zone = OSRGetUTMZone(hSRS, &bNorth);
  450. if (!bNorth)
  451. cellhd->zone *= -1;
  452. }
  453. else {
  454. cellhd->proj = PROJECTION_OTHER;
  455. cellhd->zone = 0;
  456. }
  457. }
  458. /* -------------------------------------------------------------------- */
  459. /* Get the coordinate system definition in PROJ.4 format. */
  460. /* -------------------------------------------------------------------- */
  461. if (OSRExportToProj4(hSRS, &pszProj4) != OGRERR_NONE)
  462. goto default_to_xy;
  463. /* -------------------------------------------------------------------- */
  464. /* Parse the PROJ.4 string into key/value pairs. Do a bit of */
  465. /* extra work to "GRASSify" the result. */
  466. /* -------------------------------------------------------------------- */
  467. temp_projinfo = G_create_key_value();
  468. /* Create "local" copy of proj4 string so we can modify and free it
  469. * using GRASS functions */
  470. pszRemaining = G_store(pszProj4);
  471. CPLFree(pszProj4);
  472. pszProj4 = pszRemaining;
  473. while ((pszRemaining = strstr(pszRemaining, "+")) != NULL) {
  474. char *pszToken, *pszValue;
  475. pszRemaining++;
  476. /* Advance pszRemaining to end of this token[=value] pair */
  477. pszToken = pszRemaining;
  478. while (*pszRemaining != ' ' && *pszRemaining != '\0')
  479. pszRemaining++;
  480. if (*pszRemaining == ' ') {
  481. *pszRemaining = '\0';
  482. pszRemaining++;
  483. }
  484. /* parse token, and value */
  485. if (strstr(pszToken, "=") != NULL) {
  486. pszValue = strstr(pszToken, "=");
  487. *pszValue = '\0';
  488. pszValue++;
  489. }
  490. else
  491. pszValue = "defined";
  492. /* projection name */
  493. if (G_strcasecmp(pszToken, "proj") == 0) {
  494. /* The ll projection is known as longlat in PROJ.4 */
  495. if (G_strcasecmp(pszValue, "longlat") == 0)
  496. pszValue = "ll";
  497. pszProj = pszValue;
  498. }
  499. /* discard @null nadgrids */
  500. if (G_strcasecmp(pszToken, "nadgrids") == 0 &&
  501. G_strcasecmp(pszValue, "@null") == 0)
  502. continue;
  503. /* Ellipsoid and datum handled separately below */
  504. if (G_strcasecmp(pszToken, "ellps") == 0
  505. || G_strcasecmp(pszToken, "a") == 0
  506. || G_strcasecmp(pszToken, "b") == 0
  507. || G_strcasecmp(pszToken, "es") == 0
  508. || G_strcasecmp(pszToken, "rf") == 0
  509. || G_strcasecmp(pszToken, "datum") == 0)
  510. continue;
  511. /* We will handle units separately */
  512. if (G_strcasecmp(pszToken, "to_meter") == 0)
  513. continue;
  514. if (G_strcasecmp(pszToken, "units") == 0) {
  515. proj4_unit = G_store(pszValue);
  516. continue;
  517. }
  518. G_set_key_value(pszToken, pszValue, temp_projinfo);
  519. }
  520. if (!pszProj)
  521. G_warning(_("No projection name! Projection parameters likely to be meaningless."));
  522. /* -------------------------------------------------------------------- */
  523. /* Derive the user name for the coordinate system. */
  524. /* -------------------------------------------------------------------- */
  525. if (!G_find_key_value("name", *projinfo)) {
  526. pszProjCS = OSRGetAttrValue(hSRS, "PROJCS", 0);
  527. if (!pszProjCS)
  528. pszProjCS = OSRGetAttrValue(hSRS, "GEOGCS", 0);
  529. if (pszProjCS) {
  530. G_set_key_value("name", pszProjCS, *projinfo);
  531. }
  532. else if (pszProj) {
  533. char path[4095];
  534. char name[80];
  535. /* use name of the projection as name for the coordinate system */
  536. sprintf(path, "%s/etc/proj/projections", G_gisbase());
  537. if (G_lookup_key_value_from_file(path, pszProj, name, sizeof(name)) >
  538. 0)
  539. G_set_key_value("name", name, *projinfo);
  540. else
  541. G_set_key_value("name", pszProj, *projinfo);
  542. }
  543. }
  544. /* -------------------------------------------------------------------- */
  545. /* Find the GRASS datum name and choose parameters either */
  546. /* interactively or not. */
  547. /* -------------------------------------------------------------------- */
  548. {
  549. const char *pszDatumNameConst = OSRGetAttrValue(hSRS, "DATUM", 0);
  550. struct datum_list *list, *listhead;
  551. char *dum1, *dum2, *pszDatumName;
  552. int paramspresent =
  553. GPJ__get_datum_params(temp_projinfo, &dum1, &dum2);
  554. if (pszDatumNameConst) {
  555. /* Need to make a new copy of the string so we don't mess
  556. * around with the memory inside the OGRSpatialReferenceH? */
  557. pszDatumName = G_store(pszDatumNameConst);
  558. DatumNameMassage(&pszDatumName);
  559. G_debug(3, "GPJ_osr_to_grass: pszDatumNameConst: <%s>", pszDatumName);
  560. list = listhead = read_datum_table();
  561. while (list != NULL) {
  562. if (G_strcasecmp(pszDatumName, list->longname) == 0) {
  563. datum = G_store(list->name);
  564. break;
  565. }
  566. list = list->next;
  567. }
  568. free_datum_list(listhead);
  569. if (datum == NULL) {
  570. if (paramspresent < 2)
  571. /* Only give warning if no parameters present */
  572. G_warning(_("Datum <%s> not recognised by GRASS and no parameters found"),
  573. pszDatumName);
  574. }
  575. else {
  576. G_set_key_value("datum", datum, *projinfo);
  577. if (paramspresent < 2) {
  578. /* If no datum parameters were imported from the OSR
  579. * object then we should use the set specified by datumtrans */
  580. char *params, *chosenparams = NULL;
  581. int paramsets;
  582. paramsets =
  583. GPJ_get_default_datum_params_by_name(datum, &params);
  584. if (paramsets < 0)
  585. G_warning(_("Datum <%s> apparently recognised by GRASS but no parameters found. "
  586. "You may want to look into this."), datum);
  587. else if (datumtrans > paramsets) {
  588. G_warning(_("Invalid transformation number %d; valid range is 1 to %d. "
  589. "Leaving datum transform parameters unspecified."),
  590. datumtrans, paramsets);
  591. datumtrans = 0;
  592. }
  593. if (paramsets > 0) {
  594. struct gpj_datum_transform_list *tlist, *old;
  595. tlist = GPJ_get_datum_transform_by_name(datum);
  596. if (tlist != NULL) {
  597. do {
  598. if (tlist->count == datumtrans)
  599. chosenparams = G_store(tlist->params);
  600. old = tlist;
  601. tlist = tlist->next;
  602. GPJ_free_datum_transform(old);
  603. } while (tlist != NULL);
  604. }
  605. }
  606. if (chosenparams != NULL) {
  607. char *paramkey, *paramvalue;
  608. paramkey = strtok(chosenparams, "=");
  609. paramvalue = chosenparams + strlen(paramkey) + 1;
  610. G_set_key_value(paramkey, paramvalue, *projinfo);
  611. G_free(chosenparams);
  612. }
  613. if (paramsets > 0)
  614. G_free(params);
  615. }
  616. }
  617. G_free(pszDatumName);
  618. }
  619. }
  620. /* -------------------------------------------------------------------- */
  621. /* Determine an appropriate GRASS ellipsoid name if possible, or */
  622. /* else just put a and es values into PROJ_INFO */
  623. /* -------------------------------------------------------------------- */
  624. if ((datum != NULL) && (GPJ_get_datum_by_name(datum, &dstruct) > 0)) {
  625. /* Use ellps name associated with datum */
  626. G_set_key_value("ellps", dstruct.ellps, *projinfo);
  627. GPJ_free_datum(&dstruct);
  628. G_free(datum);
  629. }
  630. else {
  631. /* If we can't determine the ellipsoid from the datum, derive it
  632. * directly from "SPHEROID" parameters in WKT */
  633. const char *pszSemiMajor = OSRGetAttrValue(hSRS, "SPHEROID", 1);
  634. const char *pszInvFlat = OSRGetAttrValue(hSRS, "SPHEROID", 2);
  635. if (pszSemiMajor != NULL && pszInvFlat != NULL) {
  636. char *ellps = NULL;
  637. struct ellps_list *list, *listhead;
  638. double a = atof(pszSemiMajor), invflat = atof(pszInvFlat), flat;
  639. double es;
  640. /* Allow for incorrect WKT describing a sphere where InvFlat
  641. * is given as 0 rather than inf */
  642. if (invflat > 0)
  643. flat = 1 / invflat;
  644. else
  645. flat = 0;
  646. es = flat * (2.0 - flat);
  647. list = listhead = read_ellipsoid_table(0);
  648. while (list != NULL) {
  649. /* Try and match a and es against GRASS defined ellipsoids;
  650. * accept first one that matches. These numbers were found
  651. * by trial and error and could be fine-tuned, or possibly
  652. * a direct comparison of IEEE floating point values used. */
  653. if ((a == list->a || fabs(a - list->a) < 0.1 || fabs(1 - a / list->a) < 0.0000001) &&
  654. ((es == 0 && list->es == 0) ||
  655. /* Special case for sphere */
  656. (invflat == list->rf || fabs(invflat - list->rf) < 0.0000001))) {
  657. ellps = G_store(list->name);
  658. break;
  659. }
  660. list = list->next;
  661. }
  662. if (listhead != NULL)
  663. free_ellps_list(listhead);
  664. if (ellps == NULL) {
  665. /* If we weren't able to find a matching ellps name, set
  666. * a and es values directly from WKT-derived data */
  667. char es_str[100];
  668. G_set_key_value("a", (char *)pszSemiMajor, *projinfo);
  669. sprintf(es_str, "%.16g", es);
  670. G_set_key_value("es", es_str, *projinfo);
  671. }
  672. else {
  673. /* else specify the GRASS ellps name for readability */
  674. G_set_key_value("ellps", ellps, *projinfo);
  675. G_free(ellps);
  676. }
  677. }
  678. }
  679. /* -------------------------------------------------------------------- */
  680. /* Finally append the detailed projection parameters to the end */
  681. /* -------------------------------------------------------------------- */
  682. {
  683. int i;
  684. for (i = 0; i < temp_projinfo->nitems; i++)
  685. G_set_key_value(temp_projinfo->key[i],
  686. temp_projinfo->value[i], *projinfo);
  687. G_free_key_value(temp_projinfo);
  688. }
  689. G_free(pszProj4);
  690. /* -------------------------------------------------------------------- */
  691. /* Set the linear units. */
  692. /* -------------------------------------------------------------------- */
  693. *projunits = G_create_key_value();
  694. if (OSRIsGeographic(hSRS)) {
  695. /* We assume degrees ... someday we will be wrong! */
  696. G_set_key_value("unit", "degree", *projunits);
  697. G_set_key_value("units", "degrees", *projunits);
  698. G_set_key_value("meters", "1.0", *projunits);
  699. }
  700. else {
  701. char szFormatBuf[256];
  702. char *pszUnitsName = NULL;
  703. double dfToMeters;
  704. char *pszUnitsPlural, *pszStringEnd;
  705. dfToMeters = OSRGetLinearUnits(hSRS, &pszUnitsName);
  706. /* the unit name can be arbitrary: the following can be the same
  707. * us-ft (proj.4 keyword)
  708. * U.S. Surveyor's Foot (proj.4 name)
  709. * US survey foot (WKT)
  710. * Foot_US (WKT)
  711. */
  712. /* Workaround for the most obvious case when unit name is unknown */
  713. if ((G_strcasecmp(pszUnitsName, "unknown") == 0) &&
  714. (dfToMeters == 1.))
  715. G_asprintf(&pszUnitsName, "meter");
  716. if ((G_strcasecmp(pszUnitsName, "metre") == 0))
  717. G_asprintf(&pszUnitsName, "meter");
  718. if ((G_strcasecmp(pszUnitsName, "kilometre") == 0))
  719. G_asprintf(&pszUnitsName, "kilometer");
  720. if (dfToMeters != 1. && proj4_unit) {
  721. int i;
  722. i = 0;
  723. while (gpj_units[i].id != NULL) {
  724. if (strcmp(proj4_unit, gpj_units[i].id) == 0) {
  725. G_asprintf(&pszUnitsName, "%s", gpj_units[i].name);
  726. break;
  727. }
  728. i++;
  729. }
  730. }
  731. G_set_key_value("unit", pszUnitsName, *projunits);
  732. /* Attempt at plural formation (WKT format doesn't store plural
  733. * form of unit name) */
  734. pszUnitsPlural = G_malloc(strlen(pszUnitsName) + 3);
  735. strcpy(pszUnitsPlural, pszUnitsName);
  736. pszStringEnd = pszUnitsPlural + strlen(pszUnitsPlural) - 4;
  737. if (G_strcasecmp(pszStringEnd, "foot") == 0) {
  738. /* Special case for foot - change two o's to e's */
  739. pszStringEnd[1] = 'e';
  740. pszStringEnd[2] = 'e';
  741. }
  742. else if (G_strcasecmp(pszStringEnd, "inch") == 0) {
  743. /* Special case for inch - add es */
  744. pszStringEnd[4] = 'e';
  745. pszStringEnd[5] = 's';
  746. pszStringEnd[6] = '\0';
  747. }
  748. else {
  749. /* For anything else add an s at the end */
  750. pszStringEnd[4] = 's';
  751. pszStringEnd[5] = '\0';
  752. }
  753. G_set_key_value("units", pszUnitsPlural, *projunits);
  754. G_free(pszUnitsPlural);
  755. sprintf(szFormatBuf, "%.16g", dfToMeters);
  756. G_set_key_value("meters", szFormatBuf, *projunits);
  757. }
  758. if (hSRS != hSRS1)
  759. OSRDestroySpatialReference(hSRS);
  760. return 2;
  761. /* -------------------------------------------------------------------- */
  762. /* Fallback to returning an ungeoreferenced definition. */
  763. /* -------------------------------------------------------------------- */
  764. default_to_xy:
  765. if (cellhd != NULL) {
  766. cellhd->proj = PROJECTION_XY;
  767. cellhd->zone = 0;
  768. }
  769. if (*projinfo)
  770. G_free_key_value(*projinfo);
  771. *projinfo = NULL;
  772. *projunits = NULL;
  773. if (hSRS != NULL && hSRS != hSRS1)
  774. OSRDestroySpatialReference(hSRS);
  775. return 1;
  776. }
  777. #endif
  778. /*!
  779. * \brief Converts a WKT projection description to a GRASS co-ordinate system.
  780. *
  781. * \param cellhd Pointer to a GRASS Cell_head structure that will have its
  782. * projection-related members populated with appropriate values
  783. * \param projinfo Pointer to a pointer which will have a GRASS Key_Value
  784. * structure allocated containing a set of GRASS PROJ_INFO values
  785. * \param projunits Pointer to a pointer which will have a GRASS Key_Value
  786. * structure allocated containing a set of GRASS PROJ_UNITS values
  787. * \param wkt Well-known Text (WKT) description of the co-ordinate
  788. * system to be converted
  789. * \param datumtrans Index number of datum parameter set to use, 0 to leave
  790. * unspecified
  791. *
  792. * \return 2 if a projected or lat/long co-ordinate system has been
  793. * defined
  794. * \return 1 if an unreferenced XY co-ordinate system has
  795. * been defined
  796. * \return -1 on error
  797. */
  798. int GPJ_wkt_to_grass(struct Cell_head *cellhd, struct Key_Value **projinfo,
  799. struct Key_Value **projunits, const char *wkt,
  800. int datumtrans)
  801. {
  802. #ifdef HAVE_OGR
  803. int retval;
  804. if (wkt == NULL)
  805. retval =
  806. GPJ_osr_to_grass(cellhd, projinfo, projunits, NULL, datumtrans);
  807. else {
  808. OGRSpatialReferenceH hSRS;
  809. /* Set finder function for locating OGR csv co-ordinate system tables */
  810. /* SetCSVFilenameHook(GPJ_set_csv_loc); */
  811. hSRS = OSRNewSpatialReference(wkt);
  812. retval =
  813. GPJ_osr_to_grass(cellhd, projinfo, projunits, hSRS, datumtrans);
  814. OSRDestroySpatialReference(hSRS);
  815. }
  816. return retval;
  817. #else
  818. return -1;
  819. #endif
  820. }
  821. #ifdef HAVE_OGR
  822. /* GPJ_set_csv_loc()
  823. * 'finder function' for use with OGR SetCSVFilenameHook() function */
  824. const char *GPJ_set_csv_loc(const char *name)
  825. {
  826. const char *gisbase = G_gisbase();
  827. static char *buf = NULL;
  828. if (buf != NULL)
  829. G_free(buf);
  830. G_asprintf(&buf, "%s%s/%s", gisbase, CSVDIR, name);
  831. return buf;
  832. }
  833. /* The list below is only for files that use a non-standard name for a
  834. * datum that is already supported in GRASS. The number of entries must be even;
  835. * they are all in pairs. The first one in the pair is the non-standard name;
  836. * the second is the GRASS/GDAL name. If a name appears more than once (as for
  837. * European_Terrestrial_Reference_System_1989) then it means there was more
  838. * than one non-standard name for it that needs to be accounted for.
  839. *
  840. * N.B. The order of these pairs is different from that in
  841. * ogr/ogrfromepsg.cpp in the GDAL source tree! GRASS uses the EPSG
  842. * names in its WKT representation except WGS_1984 and WGS_1972 as
  843. * these shortened versions seem to be standard.
  844. * Below order:
  845. * the equivalent name comes first in the pair, and
  846. * the EPSG name (as used in the GRASS datum.table file) comes second.
  847. *
  848. * The datum parameters are stored in
  849. * ../gis/datum.table # 3 parameters
  850. * ../gis/datumtransform.table # 7 parameters (requires entry in datum.table)
  851. *
  852. * Hint: use GDAL's "testepsg" to identify the canonical name, e.g.
  853. * testepsg epsg:4674
  854. */
  855. static const char *papszDatumEquiv[] = {
  856. "Militar_Geographische_Institute",
  857. "Militar_Geographische_Institut",
  858. "World_Geodetic_System_1984",
  859. "WGS_1984",
  860. "World_Geodetic_System_1972",
  861. "WGS_1972",
  862. "European_Terrestrial_Reference_System_89",
  863. "European_Terrestrial_Reference_System_1989",
  864. "European_Reference_System_1989",
  865. "European_Terrestrial_Reference_System_1989",
  866. "ETRS_1989",
  867. "European_Terrestrial_Reference_System_1989",
  868. "ETRS89",
  869. "European_Terrestrial_Reference_System_1989",
  870. "ETRF_1989",
  871. "European_Terrestrial_Reference_System_1989",
  872. "NZGD_2000",
  873. "New_Zealand_Geodetic_Datum_2000",
  874. "Monte_Mario_Rome",
  875. "Monte_Mario",
  876. "MONTROME",
  877. "Monte_Mario",
  878. "Campo_Inchauspe_1969",
  879. "Campo_Inchauspe",
  880. "S_JTSK",
  881. "System_Jednotne_Trigonometricke_Site_Katastralni",
  882. "S_JTSK_Ferro",
  883. "Militar_Geographische_Institut",
  884. "Potsdam_Datum_83",
  885. "Deutsches_Hauptdreiecksnetz",
  886. "South_American_1969",
  887. "South_American_Datum_1969",
  888. "ITRF_1992",
  889. "ITRF92",
  890. NULL
  891. };
  892. /************************************************************************/
  893. /* OGREPSGDatumNameMassage() */
  894. /* */
  895. /* Massage an EPSG datum name into WMT format. Also transform */
  896. /* specific exception cases into WKT versions. */
  897. /************************************************************************/
  898. static void DatumNameMassage(char **ppszDatum)
  899. {
  900. int i, j;
  901. char *pszDatum = *ppszDatum;
  902. G_debug(3, "DatumNameMassage: Raw string found <%s>", (char *)pszDatum);
  903. /* -------------------------------------------------------------------- */
  904. /* Translate non-alphanumeric values to underscores. */
  905. /* -------------------------------------------------------------------- */
  906. for (i = 0; pszDatum[i] != '\0'; i++) {
  907. if (!(pszDatum[i] >= 'A' && pszDatum[i] <= 'Z')
  908. && !(pszDatum[i] >= 'a' && pszDatum[i] <= 'z')
  909. && !(pszDatum[i] >= '0' && pszDatum[i] <= '9')) {
  910. pszDatum[i] = '_';
  911. }
  912. }
  913. /* -------------------------------------------------------------------- */
  914. /* Remove repeated and trailing underscores. */
  915. /* -------------------------------------------------------------------- */
  916. for (i = 1, j = 0; pszDatum[i] != '\0'; i++) {
  917. if (pszDatum[j] == '_' && pszDatum[i] == '_')
  918. continue;
  919. pszDatum[++j] = pszDatum[i];
  920. }
  921. if (pszDatum[j] == '_')
  922. pszDatum[j] = '\0';
  923. else
  924. pszDatum[j + 1] = '\0';
  925. /* -------------------------------------------------------------------- */
  926. /* Search for datum equivalences. Specific massaged names get */
  927. /* mapped to OpenGIS specified names. */
  928. /* -------------------------------------------------------------------- */
  929. G_debug(3, "DatumNameMassage: Search for datum equivalences of <%s>", (char *)pszDatum);
  930. for (i = 0; papszDatumEquiv[i] != NULL; i += 2) {
  931. if (EQUAL(*ppszDatum, papszDatumEquiv[i])) {
  932. G_free(*ppszDatum);
  933. *ppszDatum = G_store(papszDatumEquiv[i + 1]);
  934. break;
  935. }
  936. }
  937. }
  938. #endif /* HAVE_OGR */