Revision 596 org.gvsig.projection.jcrs/trunk/org.gvsig.projection.jcrs/org.gvsig.projection.jcrs.lib/src/main/java/org/gvsig/crs/Crs.java

View differences:

Crs.java
1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2006 Instituto de Desarrollo Regional and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   Instituto de Desarrollo Regional (Universidad de Castilla La-Mancha)
34
 *   Campus Universitario s/n
35
 *   02071 Alabacete
36
 *   Spain
37
 *
38
 *   +34 967 599 200
39
 */
40

  
41
package org.gvsig.crs;
42

  
43
import java.awt.Color;
44
import java.awt.Graphics2D;
45
import java.awt.geom.Point2D;
46
import java.awt.geom.Rectangle2D;
47
import java.text.MessageFormat;
48

  
49
import org.apache.commons.lang3.StringUtils;
50
import org.cresques.cts.ICRSFactory;
51
import org.cresques.cts.ICoordTrans;
52
import org.cresques.cts.IDatum;
53
import org.cresques.cts.IProjection;
54
import org.cresques.geo.ViewPortData;
55
import org.gdal.osr.SpatialReference;
56
import org.slf4j.Logger;
57
import org.slf4j.LoggerFactory;
58

  
59
import org.gvsig.crs.proj.CrsProj;
60
import org.gvsig.crs.proj.OperationCrsException;
61
import org.gvsig.fmap.crs.CRSFactory;
62

  
63
/**
64
 * Clase que construye el CRS a partir de la cadena WKT
65
 * @author Jos? Luis G?mez Mart?nez (jolugomar@gmail.com)
66
 * @author Diego Guerrero Sevilla (diego.guerrero@uclm.es)
67
 * @author Miguel Garc?a Jim?nez (garciajimenez.miguel@gmail.com)
68
 *
69
 */
70
public class Crs implements ICrs {
71

  
72
    private static final Logger logger = LoggerFactory.getLogger(Crs.class);
73

  
74
    private static final Color basicGridColor = new Color(64, 64, 64, 128);
75
    private Proj4 proj4;
76
    private String proj4String;
77
    private String trans;
78
    // private String transOrigin = "";
79
    private String abrev;
80
    private String name = "";
81
    private CrsProj crsProj;
82
    private CrsProj crsBase = null;
83
    private CrsWkt crsWkt;
84
    private int epsg_code = 0; //23030;
85
    String sourceTrParams = null;
86
    String targetTrParams = null;
87
    String wkt = null;
88
    Color gridColor = basicGridColor;
89
    CRSDatum datum = null;
90

  
91
    private SpatialReference spatialReference = null;
92

  
93

  
94
    /**
95
     * @param spatialReference
96
     *
97
     */
98
    public Crs(SpatialReference spatialReference) {
99
            initFromSpatialReference(spatialReference);
100
    }
101

  
102
    /**
103
     * @param spatialReference
104
     */
105
    private void initFromSpatialReference(SpatialReference spatialReference) {
106
        this.spatialReference = spatialReference;
107
        String authorityCode = this.spatialReference.GetAuthorityCode(null);
108
        String authorityName = this.spatialReference.GetAuthorityName(null);
109
        this.spatialReference.Fixup();
110
        if(authorityCode==null || authorityName==null){
111
            try {
112
                this.spatialReference.AutoIdentifyEPSG();
113
                authorityCode = this.spatialReference.GetAuthorityCode(null);
114
                authorityName = this.spatialReference.GetAuthorityName(null);
115
            } catch (Exception e) {
116
                logger.warn("Can't autoidentifyEPSG.", e);
117
            }
118
        }
119
        if(!StringUtils.isEmpty(authorityCode) && !StringUtils.isEmpty(authorityName)){
120
            name = authorityName+":"+authorityCode;
121
            epsg_code = Integer.parseInt(authorityCode);
122
        }
123
        abrev = name;
124

  
125
        datum = new CRSDatum(this.spatialReference.GetSemiMajor(), this.spatialReference.GetInvFlattening());
126
        try {
127
            proj4String = this.spatialReference.ExportToProj4();
128
        } catch (Exception e) {
129
            logger.warn("Can't get proj4 string from "+name, e);
130
        }
131
        crsWkt = new CrsWkt(this.spatialReference);
132
        setWKT(this.spatialReference.ExportToWkt());
133
    }
134

  
135
    /**
136
     * @param epsgCode
137
     * @param aut
138
     * @throws CrsException
139
     */
140
    public Crs(int epsgCode, int aut) throws CrsException {
141
        String strEpsgCode = "";
142
        if (aut == 1) {
143
            strEpsgCode = "EPSG:" + epsgCode;
144
        } else if (aut == 2) {
145
            strEpsgCode = "ESRI:" + epsgCode;
146
        } else if (aut == 3) {
147
            strEpsgCode = "IAU2000:" + epsgCode;
148
        } else if (aut == 4) {
149
            strEpsgCode = "USR:" + epsgCode;
150
        } else
151
            logger.warn("Error, invalid authority");
152
        crsWkt = new CrsWkt(strEpsgCode);
153
        setWKT(crsWkt.getWkt());
154
    }
155

  
156
    /**
157
     * Construye un CRS a partir del c?digo EPSG o de la cadena WKT.
158
     *
159
     * @param code
160
     * @throws CrsException
161
     */
162
    public Crs(String code) throws CrsException {
163
        String fullCode;
164
        setWKT(code);
165
        if (code.charAt(0) == 'E' || code.charAt(0) == 'G' || code.charAt(0) == 'P')
166
            fullCode = code;
167
        else
168
            fullCode = "EPSG:" + code;
169
        if (code.length() < 15) {
170
            code = code.substring(code.indexOf(":") + 1);
171
            try {
172
                // Creamos el objeto que tendra los diferentes parametros de la
173
                // cadena Wkt
174
                crsWkt = new CrsWkt(fullCode);
175
                setName(fullCode);
176
                setAbrev(fullCode);
177

  
178
            } catch (NumberFormatException e) {
179
                logger.error("Can't Wkt.", e);
180
            }
181
        } else {
182
            String aux;
183
            String code2 = "";
184
            for (int i = 0; i < code.length(); i++) {
185
                aux = "" + code.charAt(i);
186
                if (!aux.equals(" ")) {
187
                    code2 += aux;
188
                } else {
189
                    code2 += "";
190
                }
191
            }
192
            crsWkt = new CrsWkt(code2);
193

  
194
            setName(fullCode);
195
            // setAbrev(crsWkt.getName());
196
            setAbrev(crsWkt.getAuthority()[0] + ":" + crsWkt.getAuthority()[1]);
197

  
198
        }
199
        // Asignar el datum y el crs base (en el caso de ser projectado):
200
        if (!(crsWkt.getSpheroid()[1].equals("") || crsWkt.getSpheroid()[2].equals(""))) {
201
            double eSemiMajorAxis = Double.valueOf(crsWkt.getSpheroid()[1]).doubleValue();
202
            double eIFlattening = Double.valueOf(crsWkt.getSpheroid()[2]).doubleValue();
203
            datum = new CRSDatum(eSemiMajorAxis, eIFlattening);
204

  
205
            // crs base (en el caso de ser projectado):
206
            /*
207
             * if(this.isProjected()){
208
             * String proj4Base = "+proj=latlong +a=" + crsWkt.getSpheroid()[1]
209
             * + " +rf=" + crsWkt.getSpheroid()[2] ;
210
             * crsBase = new CrsProj(proj4Base);
211
             * }
212
             */
213
        }
214
    }
215

  
216
    /**
217
     * Construye un CRS a partir del c?digo EPSG o de la cadena WKT.
218
     *
219
     * @param epsg_cod
220
     * @param code
221
     * @throws CrsException
222
     */
223
    public Crs(int epsg_cod, String code) throws CrsException {
224
//        String fullCode;
225
        setWKT(code);
226
        setCode(epsg_cod);
227
//        if (code != null || code.charAt(0) == 'E' || code.charAt(0) == 'G' || code.charAt(0) == 'P')
228
//            fullCode = code;
229
//        else
230
//            fullCode = "EPSG:" + code;
231

  
232
        SpatialReference sr = new SpatialReference();
233
//        Vector<String> vector = new Vector<String>();
234
//        vector.add(code);
235
//        sr.ImportFromWkt(vector);
236
        sr.ImportFromWkt(code);
237
        initFromSpatialReference(sr);
238

  
239
//        String cod = "";
240
//        if (code.length() < 15) {
241
//            code = code.substring(code.indexOf(":") + 1);
242
//            try {
243
//                // Creamos el objeto que tendra los diferentes parametros de la
244
//                // cadena Wkt
245
//                crsWkt = new CrsWkt(fullCode);
246
//                setName(fullCode);
247
//                setAbrev(fullCode);
248
//
249
//            } catch (NumberFormatException e) {
250
//                logger.error("Can't get Wkt.", e);
251
//            }
252
//        } else {
253
//            String aux;
254
//            String code2 = "";
255
//            for (int i = 0; i < code.length(); i++) {
256
//                aux = "" + code.charAt(i);
257
//                if (!aux.equals(" ")) {
258
//                    code2 += aux;
259
//                } else {
260
//                    code2 += "";
261
//                }
262
//            }
263
//            crsWkt = new CrsWkt(code2);
264
//            /*
265
//             * Arreglo temporal para ver si funcionan de la iau2000 las
266
//             * proyecciones
267
//             * cilindrica equidistante y oblicua cilindrica equidistante
268
//             * que no estan en gdal, por lo que asignaremos directamente su
269
//             * cadena
270
//             * en proj4 para trabajar con ellas
271
//             */
272
//            if (!crsWkt.getProjection().equals("Equidistant_Cylindrical")
273
//                && !crsWkt.getProjection().equals("Oblique_Cylindrical_Equal_Area")) {
274
//                setName(fullCode);
275
//                // setAbrev(crsWkt.getName());
276
//                setAbrev(crsWkt.getAuthority()[0] + ":" + crsWkt.getAuthority()[1]);
277
//            } else if (crsWkt.getProjection().equals("Equidistant_Cylindrical")) {
278
//                String spheroid1 = crsWkt.getSpheroid()[1];
279
//                String spheroid2 = crsWkt.getSpheroid()[2];
280
//                String centralMeridian = "";
281
//                String falseNorthing = "";
282
//                String falseEasting = "";
283
//                String standardParallel1 = "0.0";
284
//                for (int i = 0; i < crsWkt.getParam_name().length; i++) {
285
//                    if (crsWkt.getParam_name()[i].equals("Central_Meridian"))
286
//                        centralMeridian = crsWkt.getParam_value()[i];
287
//                    if (crsWkt.getParam_name()[i].equals("False_Easting"))
288
//                        falseEasting = crsWkt.getParam_value()[i];
289
//                    if (crsWkt.getParam_name()[i].equals("False_Northing"))
290
//                        falseNorthing = crsWkt.getParam_value()[i];
291
//                    if (crsWkt.getParam_name()[i].equals("Standard_Parallel_1"))
292
//                        standardParallel1 = crsWkt.getParam_value()[i];
293
//                }
294
//                if (spheroid2.equals("0.0")) {
295
//                    proj4String =
296
//                        "+proj=eqc +a=" + spheroid1 + " +lon_0=" + centralMeridian + " +x_0=" + falseEasting + " +y_0="
297
//                            + falseNorthing + " +lat_ts=" + standardParallel1;
298
//                } else {
299
//                    proj4String =
300
//                        "+proj=eqc +a=" + spheroid1 + " +rf=" + spheroid2 + " +lon_0=" + centralMeridian + " +x_0="
301
//                            + falseEasting + " +y_0=" + falseNorthing + " +lat_ts=" + standardParallel1;
302
//                }
303
//                setName(fullCode);
304
//                // setAbrev(crsWkt.getName());
305
//                setAbrev(crsWkt.getAuthority()[0] + ":" + crsWkt.getAuthority()[1]);
306
//
307
//            } else if (crsWkt.getProjection().equals("Oblique_Cylindrical_Equal_Area")) {
308
//                String spheroid1 = crsWkt.getSpheroid()[1];
309
//                String spheroid2 = crsWkt.getSpheroid()[2];
310
//                String centralMeridian = "";
311
//                String falseNorthing = "";
312
//                String falseEasting = "";
313
//                String standardParallel1 = "";
314
//                String standardParallel2 = "0.0";
315
//                for (int i = 0; i < crsWkt.getParam_name().length; i++) {
316
//                    if (crsWkt.getParam_name()[i].equals("Central_Meridian"))
317
//                        centralMeridian = crsWkt.getParam_value()[i];
318
//                    if (crsWkt.getParam_name()[i].equals("False_Easting"))
319
//                        falseEasting = crsWkt.getParam_value()[i];
320
//                    if (crsWkt.getParam_name()[i].equals("False_Northing"))
321
//                        falseNorthing = crsWkt.getParam_value()[i];
322
//                    if (crsWkt.getParam_name()[i].equals("Standard_Parallel_1"))
323
//                        standardParallel1 = crsWkt.getParam_value()[i];
324
//                    if (crsWkt.getParam_name()[i].equals("Standard_Parallel_2"))
325
//                        standardParallel2 = crsWkt.getParam_value()[i];
326
//                }
327
//                if (spheroid2.equals("0.0")) {
328
//                    proj4String =
329
//                        "+proj=ocea +a=" + spheroid1 + " +lon_0=" + centralMeridian + " +x_0=" + falseEasting
330
//                            + " +y_0=" + falseNorthing + " +lat_1=" + standardParallel1 + " +lat_2="
331
//                            + standardParallel2 + " +lon_1=long_1" + " +lon_2=long_2 +no_defs";
332
//                } else {
333
//                    proj4String =
334
//                        "+proj=ocea +a=" + spheroid1 + " +rf=" + spheroid2 + " +lon_0=" + centralMeridian + " +x_0="
335
//                            + falseEasting + " +y_0=" + falseNorthing + " +lat_1=" + standardParallel1 + " +lat_2="
336
//                            + standardParallel2 + " +lon_1=long_1" + " +lon_2=long_2 +no_defs";
337
//                }
338
//                setName(fullCode);
339
//                // setAbrev(crsWkt.getName());
340
//                setAbrev(crsWkt.getAuthority()[0] + ":" + crsWkt.getAuthority()[1]);
341
//            }
342
//        }
343
//        // Asignar el datum:
344
//        if (!(crsWkt.getSpheroid()[1].equals("") || crsWkt.getSpheroid()[2].equals(""))) {
345
//            double eSemiMajorAxis = Double.valueOf(crsWkt.getSpheroid()[1]).doubleValue();
346
//            double eIFlattening = Double.valueOf(crsWkt.getSpheroid()[2]).doubleValue();
347
//            datum = new CRSDatum(eSemiMajorAxis, eIFlattening);
348
//
349
//            // Crs base (en el caso de ser projectado):
350
//            /*
351
//             * if(this.isProjected()){
352
//             * String proj4Base = "+proj=latlong +a=" + crsWkt.getSpheroid()[1]
353
//             * + " +rf=" + crsWkt.getSpheroid()[2] ;
354
//             * crsBase = new CrsProj(proj4Base);
355
//             * }
356
//             */
357
//        }
358
    }
359

  
360
    /**
361
     * Construye un CRS a partir del c?digo EPSG o de la cadena WKT.
362
     * En el caso de WKT le a?ade a la cadena proj4 el string params.
363
     *
364
     * @param epsg_cod
365
     * @param code
366
     * @param params
367
     * @throws CrsException
368
     */
369
    public Crs(int epsg_cod, String code, String params) throws CrsException {
370
        String fullCode;
371
        setCode(epsg_cod);
372
        setWKT(code);
373
        if (code.charAt(0) == 'E' || code.charAt(0) == 'G' || code.charAt(0) == 'P')
374
            fullCode = code;
375
        else
376
            fullCode = "EPSG:" + code;
377
        if (code.length() < 15) {
378
            code = code.substring(code.indexOf(":") + 1);
379
            try {
380
                // Creamos el objeto que tendra los diferentes parametros de la
381
                // cadena Wkt
382
                crsWkt = new CrsWkt(fullCode);
383

  
384
                setName(fullCode);
385
                setAbrev(fullCode);
386

  
387
            } catch (NumberFormatException e) {
388
                logger.error("Can't get Wkt.", e);
389
            }
390
        } else {
391
            String aux;
392
            String code2 = "";
393
            for (int i = 0; i < code.length(); i++) {
394
                aux = "" + code.charAt(i);
395
                if (!aux.equals(" ")) {
396
                    code2 += aux;
397
                } else {
398
                    code2 += "";
399
                }
400
            }
401
            crsWkt = new CrsWkt(code2);
402

  
403
            setName(fullCode);
404
            // setAbrev(crsWkt.getName());
405
            setAbrev(crsWkt.getAuthority()[0] + ":" + crsWkt.getAuthority()[1]);
406

  
407
        }
408
        // Asignar el datum:
409
        if (!(crsWkt.getSpheroid()[1].equals("") || crsWkt.getSpheroid()[2].equals(""))) {
410
            double eSemiMajorAxis = Double.valueOf(crsWkt.getSpheroid()[1]).doubleValue();
411
            double eIFlattening = Double.valueOf(crsWkt.getSpheroid()[2]).doubleValue();
412
            datum = new CRSDatum(eSemiMajorAxis, eIFlattening);
413

  
414
            // Crs base (en el caso de ser projectado):
415
            /*
416
             * if(this.isProjected()){
417
             * String proj4Base = "+proj=latlong +a=" + crsWkt.getSpheroid()[1]
418
             * + " +rf=" + crsWkt.getSpheroid()[2] ;
419
             * crsBase = new CrsProj(proj4Base);
420
             * }
421
             */
422
        }
423
    }
424

  
425
    /*
426
     * public Crs(CrsEpsg source) throws CrsException {
427
     * crsProj4 = source;
428
     * }
429
     */
430

  
431
    /**
432
     * @param code
433
     */
434
    public void setTrans(String code) {
435
        trans = code;
436
        changeTrans(trans);
437
    }
438

  
439
    /**
440
     *
441
     * @param code
442
     */
443
    public void changeTrans(String code) {
444
        getCrsProj().changeStrCrs(code);
445
    }
446

  
447
    /**
448
	 *
449
	 */
450
    public String getAbrev() {
451
        return abrev;
452
    }
453

  
454
    /**
455
     *
456
     * @param code
457
     */
458
    protected void setAbrev(String code) {
459
        abrev = code;
460
    }
461

  
462
    /**
463
     *
464
     * @param nom
465
     */
466
    public void setName(String nom) {
467
        name = nom;
468
    }
469

  
470
    /**
471
     * @return datum
472
     */
473
    public IDatum getDatum() {
474

  
475
        return datum;
476
    }
477

  
478
    /**
479
     * @return CrsWkt
480
     */
481
    public CrsWkt getCrsWkt() {
482
        return crsWkt;
483
    }
484

  
485
    /**
486
     *
487
     * @param wkt
488
     */
489
    public void setWKT(String wkt) {
490
        this.wkt = wkt;
491
    }
492

  
493
    /**
494
     * @return wkt
495
     */
496
    public String getWKT() {
497
        return this.wkt;
498
    }
499

  
500
    /**
501
     *
502
     * @param params
503
     */
504
    public void setTransformationParams(String sourceParams, String targetParams) {
505
        this.sourceTrParams = sourceParams;
506
        this.targetTrParams = targetParams;
507
    }
508

  
509
    /**
510
     * Devuelve los parametros de la transformacion del crs fuente
511
     *
512
     * @return source transformation parameters
513
     */
514
    public String getSourceTransformationParams() {
515
        return this.sourceTrParams;
516
    }
517

  
518
    /**
519
     * Devuelve los parametros de la transformacion del crs destino
520
     *
521
     * @return target transformation parameters
522
     */
523
    public String getTargetTransformationParams() {
524
        return this.targetTrParams;
525
    }
526

  
527
    /**
528
     * @return transformation parameters
529
     */
530
    public String getTransformationParams() {
531
        return this.sourceTrParams;
532
    }
533

  
534
    /**
535
     *
536
     * @return CrsProj
537
     */
538
    public CrsProj getCrsProj() {
539
        if (crsProj == null)
540
            try {
541
                crsProj = new CrsProj(getProj4String());
542
            } catch (CrsException e) {
543
                logger.error("Can't get proj4 string.", e);
544
            }
545
        return crsProj;
546
    }
547

  
548
    /**
549
     * @param x
550
     * @param y
551
     * @return a Point2D
552
     */
553
    public Point2D createPoint(double x, double y) {
554
        return new Point2D.Double(x, y);
555
    }
556

  
557
    /**
558
     * @param g
559
     * @param vp
560
     */
561
    public void drawGrid(Graphics2D g, ViewPortData vp) {
562
        // TODO Auto-generated method stub
563

  
564
    }
565

  
566
    /**
567
     * @param c
568
     */
569
    public void setGridColor(Color c) {
570
        gridColor = c;
571
    }
572

  
573
    /**
574
     * @return grid color
575
     */
576
    public Color getGridColor() {
577
        return gridColor;
578
    }
579

  
580
    /**
581
     * @param dest
582
     * @return Coordinate transformation
583
     */
584
    public ICoordTrans getCT(IProjection dest) {
585

  
586
        try {
587
            if (dest == this)
588
                return null;
589
            COperation operation = null;
590
            if (((ICrs) dest).getSourceTransformationParams() != null
591
                || ((ICrs) dest).getTargetTransformationParams() != null)
592
                operation =
593
                    new COperation(this, (ICrs) dest, ((ICrs) dest).getTargetTransformationParams(),
594
                        ((ICrs) dest).getSourceTransformationParams());
595
            else
596
                operation = new COperation(this, (ICrs) dest, sourceTrParams, targetTrParams);
597
            return operation;
598
        } catch (CrsException e) {
599
            logger.error("Can't get CoordTrans.", e);
600
            return null;
601
        }
602

  
603
        /*
604
         * try {
605
         * operation = new COperation(this, (ICrs)dest);
606
         * } catch (CrsException e) {
607
         * // TODO Auto-generated catch block
608
         * logger....
609
         * }
610
         *
611
         * if (getTransformationParams()!=null){
612
         * if (isTargetParams())
613
         * operation.setParamsCrsProj(new
614
         * CrsProj(crsDest.getProj4String()+getTransformationParams()), true);
615
         * else
616
         * operation.setParamsCrsProj(new
617
         * CrsProj(getProj4String()+getTransformationParams()), false);
618
         *
619
         * return operation;
620
         * }
621
         *
622
         * return operation;
623
         */
624
    }
625

  
626
    /**
627
     * @param pt
628
     * @return Point2D
629
     */
630
    public Point2D toGeo(Point2D pt) {
631
        if (isProjected()) {
632
            double x[] = { pt.getX() };
633
            double y[] = { pt.getY() };
634
            double z[] = { 0D };
635
            try {
636
                CrsProj.operate(x, y, z, getCrsProj(), crsBase);
637
            } catch (OperationCrsException e) {
638
                logger.error("Can't convert point to geo.", e);
639
            }
640
            return new Point2D.Double(x[0], y[0]);
641
        } else
642
            return pt;
643
    }
644

  
645
    /**
646
     * @param gPt
647
     * @param mPt
648
     * @return Point2D
649
     */
650
    public Point2D fromGeo(Point2D gPt, Point2D mPt) {
651
        // TODO Auto-generated method stub
652
        return null;
653
    }
654

  
655
    /**
656
     * @return true if is projected
657
     */
658
    public boolean isProjected() {
659
        return !getCrsProj().isLatlong();
660
    }
661

  
662
    /**
663
     * @param minX
664
     * @param maxX
665
     * @param width
666
     * @param dpi
667
     * @return scale
668
     */
669
    public double getScale(double minX, double maxX, double width, double dpi) {
670
        double scale = 0D;
671
        // Esto ahora se hace fuera
672
        // if (!isProjected()) { // Es geogr?fico; calcula la escala.
673
        // scale = ((maxX - minX) * // grados
674
        //
675
        // // 1852.0 metros x minuto de meridiano
676
        // (dpi / 2.54 * 100.0 * 1852.0 * 60.0)) / // px / metro
677
        // width; // pixels
678
        // }
679
        // else{
680
        scale = ((maxX - minX) * // metros
681
            (dpi / 2.54 * 100.0))
682
            / // px / metro
683
            width; // pixels
684
        // }
685
        return scale;
686
    }
687

  
688
    /**
689
     * @param minX
690
     * @param maxX
691
     * @param minY
692
     * @param maxY
693
     * @param width
694
     * @param dpi
695
     * @return scale
696
     */
697
    public double getScale(double minX, double maxX, double minY, double maxY, double width, double dpi) {
698

  
699
        double scale = 0D;
700
        double incX = (maxX - minX);
701

  
702
        if (!isProjected()) {
703
            double a = getDatum().getESemiMajorAxis();
704
            double invF = getDatum().getEIFlattening();
705
            double meanY = (minY + maxY) / 2.0;
706
            double radius = 0.0;
707

  
708
            if (invF == Double.POSITIVE_INFINITY) {
709
                radius = a;
710
            } else {
711
                double e2 = 2.0 / invF - Math.pow(1.0 / invF, 2.0);
712
                radius =
713
                    a / Math.sqrt(1.0 - e2 * Math.pow(Math.sin(meanY * Math.PI / 180.0), 2.0))
714
                        * Math.cos(meanY * Math.PI / 180.0);
715
            }
716
            incX *= Math.PI / 180.0 * radius;
717
        }
718

  
719
        scale = (incX * // metros
720
            (dpi / 2.54 * 100.0))
721
            / // px / metro
722
            width; // pixels
723

  
724
        return scale;
725
    }
726

  
727
    /**
728
     *
729
     * @param epsg_cod
730
     */
731
    public void setCode(int epsg_cod) {
732
        epsg_code = epsg_cod;
733
    }
734

  
735
    /**
736
     * @return espg code
737
     */
738
    public int getCode() {
739
        // TODO Auto-generated method stub
740
        return epsg_code;
741
    }
742

  
743
    public String getFullCode() {
744
        if (this.sourceTrParams == null && this.targetTrParams == null)
745
            return getAbrev();
746
        String sourceParams = "";
747
        String targetParams = "";
748
        if (sourceTrParams != null)
749
            sourceParams = sourceTrParams;
750
        if (targetTrParams != null)
751
            targetParams = targetTrParams;
752

  
753
        return getAbrev() + ":proj@" + sourceParams + "@" + targetParams;
754
    }
755

  
756
    public Rectangle2D getExtent(Rectangle2D extent, double scale, double wImage, double hImage, double mapUnits,
757
        double distanceUnits, double dpi) {
758
        double w = 0;
759
        double h = 0;
760
        double wExtent = 0;
761
        double hExtent = 0;
762
        // if (isProjected()) {
763
        w = ((wImage / dpi) * 2.54);
764
        h = ((hImage / dpi) * 2.54);
765
        wExtent = w * scale * distanceUnits / mapUnits;
766
        hExtent = h * scale * distanceUnits / mapUnits;
767

  
768
        // En las no proyectadas, ahora viene el calculo hecho
769
        // al haber incluido los grados en el array DISTANCETRANS2METER del
770
        // MapContext
771
        // }else {
772
        // w = ((wImage / dpi) * 2.54);
773
        // h = ((hImage / dpi) * 2.54);
774
        // wExtent =(w*scale*distanceUnits)/ (mapUnits*1852.0*60.0);
775
        // hExtent =(h*scale*distanceUnits)/ (mapUnits*1852.0*60.0);
776
        // }
777
        double xExtent = extent.getCenterX() - wExtent / 2;
778
        double yExtent = extent.getCenterY() - hExtent / 2;
779
        Rectangle2D rec = new Rectangle2D.Double(xExtent, yExtent, wExtent, hExtent);
780
        return rec;
781
    }
782

  
783
    private Proj4 getProj4() {
784
        if (proj4 == null)
785
            try {
786
                proj4 = new Proj4();
787
            } catch (CrsException e) {
788
                logger.error("Can't create Proj4 instance.", e);
789
            }
790
        return proj4;
791
    }
792

  
793
    /**
794
     *
795
     * @return Cadena proj4 Correspondiente al CRS.
796
     * @throws CrsException
797
     */
798
    public String getProj4String() throws CrsException {
799
        if (proj4String == null)
800
            proj4String = getProj4().exportToProj4(this);
801
        return proj4String;
802
    }
803

  
804
    public Object clone() throws CloneNotSupportedException {
805
        return CRSFactory.getCRS(this.getFullCode());
806
    }
807

  
808
    public String toString() {
809
        return this.getFullCode();
810
//        return MessageFormat.format("{0}({1},{2})",
811
//            new Object[] { this.getClass().getName(), this.hashCode(), this.getFullCode() });
812
    }
813

  
814
    /*
815
     * (non-Javadoc)
816
     *
817
     * @see org.cresques.cts.IProjection#export(java.lang.String)
818
     */
819
    public String export(String format) {
820
        if (this.spatialReference != null) {
821
            if (format.equalsIgnoreCase(ICRSFactory.FORMAT_PROJ4)) {
822
                return spatialReference.ExportToProj4();
823
            } else if (format.equalsIgnoreCase(ICRSFactory.FORMAT_WKT_ESRI)) {
824
                SpatialReference srESRI = spatialReference.Clone();
825
                //FIXME: Viendo que tenemos problemas para identificar la authority a partir de los WKT de ESRI
826
                // se ha decidido exportar siempre el WKT estandar. Si en alg?n momento se encuentra la manera
827
                // de hacerlo correctamente, bastar? con descomentarizar las l?neas siguientes.
828
//                if (srESRI.MorphToESRI() == 0) {
829
                    return srESRI.ExportToWkt();
830
//                }
831
//                return null;
832
            } else if (format.equalsIgnoreCase(ICRSFactory.FORMAT_WKT)) {
833
                return spatialReference.ExportToWkt();
834
            } else {
835
                return null;
836
            }
837
        } else {
838

  
839
            SpatialReference spatialReference = getCrsProj().getSpatialReference();
840
            SpatialReference auxSpatialReference = new SpatialReference();
841
            if (format.equalsIgnoreCase(ICRSFactory.FORMAT_PROJ4)) {
842
                String proj4 = spatialReference.ExportToProj4();
843
                auxSpatialReference.ImportFromProj4(proj4);
844
                if (auxSpatialReference.GetAuthorityName(null) != null) {
845
                    return proj4;
846
                }
847
                return null;
848
            } else if (format.equalsIgnoreCase(ICRSFactory.FORMAT_WKT_ESRI)) {
849
                return spatialReference.ExportToWkt();
850
                //FIXME: Viendo que tenemos problemas para identificar la authority a partir de los WKT de ESRI
851
                // se ha decidido exportar siempre el WKT estandar. Si en alg?n momento se encuentra la manera
852
                // de hacerlo correctamente, bastar? con descomentarizar las l?neas siguientes y eliminar la anterior.
853
//                if (spatialReference.MorphToESRI() == 0) {
854
//                    String esri = spatialReference.ExportToWkt();
855
//                    Vector<String> vector = new Vector<String>();
856
//                    vector.add(esri);
857
//                    auxSpatialReference.ImportFromESRI(vector);
858
//                    auxSpatialReference.MorphFromESRI();
859
//                    if (auxSpatialReference.GetAuthorityName(null) != null) {
860
//                        return esri;
861
//                    }
862
//                    return null;
863
//                }
864
//                return null;
865
            } else if (format.equalsIgnoreCase(ICRSFactory.FORMAT_WKT)) {
866
                String wkt = spatialReference.ExportToWkt();
867
                auxSpatialReference.ImportFromWkt(wkt);
868
                if (auxSpatialReference.GetAuthorityName(null) != null) {
869
                    return wkt;
870
                }
871
                return null;
872
            } else {
873
                return null;
874
            }
875
        }
876
    }
877

  
878
    @Override
879
    public boolean equals(Object obj) {
880
        if( this == obj ) {
881
            return true;
882
        }
883
        if( !(obj instanceof Crs) ) {
884
            return false;
885
        }
886
        return this.getFullCode().equalsIgnoreCase(((Crs)obj).getFullCode());
887
    }
888

  
889
    @Override
890
    public int hashCode() {
891
        return this.getFullCode().hashCode();
892
    }
893
}
1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2006 Instituto de Desarrollo Regional and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   Instituto de Desarrollo Regional (Universidad de Castilla La-Mancha)
34
 *   Campus Universitario s/n
35
 *   02071 Alabacete
36
 *   Spain
37
 *
38
 *   +34 967 599 200
39
 */
40

  
41
package org.gvsig.crs;
42

  
43
import java.awt.Color;
44
import java.awt.Graphics2D;
45
import java.awt.geom.Point2D;
46
import java.awt.geom.Rectangle2D;
47
import java.text.MessageFormat;
48

  
49
import org.apache.commons.lang3.StringUtils;
50
import org.cresques.cts.ICRSFactory;
51
import org.cresques.cts.ICoordTrans;
52
import org.cresques.cts.IDatum;
53
import org.cresques.cts.IProjection;
54
import org.cresques.geo.ViewPortData;
55
import org.gdal.osr.SpatialReference;
56
import org.slf4j.Logger;
57
import org.slf4j.LoggerFactory;
58

  
59
import org.gvsig.crs.proj.CrsProj;
60
import org.gvsig.crs.proj.OperationCrsException;
61
import org.gvsig.fmap.crs.CRSFactory;
62

  
63
/**
64
 * Clase que construye el CRS a partir de la cadena WKT
65
 * @author Jos? Luis G?mez Mart?nez (jolugomar@gmail.com)
66
 * @author Diego Guerrero Sevilla (diego.guerrero@uclm.es)
67
 * @author Miguel Garc?a Jim?nez (garciajimenez.miguel@gmail.com)
68
 *
69
 */
70
public class Crs implements ICrs {
71

  
72
    private static final Logger logger = LoggerFactory.getLogger(Crs.class);
73

  
74
    private static final Color basicGridColor = new Color(64, 64, 64, 128);
75
    private Proj4 proj4;
76
    private String proj4String;
77
    private String trans;
78
    // private String transOrigin = "";
79
    private String abrev;
80
    private String name = "";
81
    private CrsProj crsProj;
82
    private CrsProj crsBase = null;
83
    private CrsWkt crsWkt;
84
    private int epsg_code = 0; //23030;
85
    String sourceTrParams = null;
86
    String targetTrParams = null;
87
    String wkt = null;
88
    Color gridColor = basicGridColor;
89
    CRSDatum datum = null;
90

  
91
    private SpatialReference spatialReference = null;
92

  
93

  
94
    /**
95
     * @param spatialReference
96
     *
97
     */
98
    public Crs(SpatialReference spatialReference) {
99
            initFromSpatialReference(spatialReference);
100
    }
101

  
102
    /**
103
     * @param spatialReference
104
     */
105
    private void initFromSpatialReference(SpatialReference spatialReference) {
106
        this.spatialReference = spatialReference;
107
        String authorityCode = this.spatialReference.GetAuthorityCode(null);
108
        String authorityName = this.spatialReference.GetAuthorityName(null);
109
        this.spatialReference.Fixup();
110
        if(authorityCode==null || authorityName==null){
111
            try {
112
                this.spatialReference.AutoIdentifyEPSG();
113
                authorityCode = this.spatialReference.GetAuthorityCode(null);
114
                authorityName = this.spatialReference.GetAuthorityName(null);
115
            } catch (Exception e) {
116
                logger.warn("Can't autoidentifyEPSG.", e);
117
            }
118
        }
119
        if(!StringUtils.isEmpty(authorityCode) && !StringUtils.isEmpty(authorityName)){
120
            name = authorityName+":"+authorityCode;
121
            epsg_code = Integer.parseInt(authorityCode);
122
        }
123
        abrev = name;
124

  
125
        datum = new CRSDatum(this.spatialReference.GetSemiMajor(), this.spatialReference.GetInvFlattening());
126
        try {
127
        	//logger.info("Trying to export " + name + " to Proj4...");
128
        	SpatialReference sr2 = new SpatialReference();
129
        	sr2.ImportFromEPSG(epsg_code);
130
        	proj4String = sr2.ExportToProj4();
131
        	//proj4String = this.spatialReference.ExportToProj4();
132
        } catch (Exception e) {
133
            logger.warn("Can't get proj4 string from "+name, e);
134
        }
135
        crsWkt = new CrsWkt(this.spatialReference);
136
        setWKT(this.spatialReference.ExportToWkt());
137
    }
138

  
139
    /**
140
     * @param epsgCode
141
     * @param aut
142
     * @throws CrsException
143
     */
144
    public Crs(int epsgCode, int aut) throws CrsException {
145
        String strEpsgCode = "";
146
        if (aut == 1) {
147
            strEpsgCode = "EPSG:" + epsgCode;
148
        } else if (aut == 2) {
149
            strEpsgCode = "ESRI:" + epsgCode;
150
        } else if (aut == 3) {
151
            strEpsgCode = "IAU2000:" + epsgCode;
152
        } else if (aut == 4) {
153
            strEpsgCode = "USR:" + epsgCode;
154
        } else
155
            logger.warn("Error, invalid authority");
156
        crsWkt = new CrsWkt(strEpsgCode);
157
        setWKT(crsWkt.getWkt());
158
    }
159

  
160
    /**
161
     * Construye un CRS a partir del c?digo EPSG o de la cadena WKT.
162
     *
163
     * @param code
164
     * @throws CrsException
165
     */
166
    public Crs(String code) throws CrsException {
167
        String fullCode;
168
        setWKT(code);
169
        if (code.charAt(0) == 'E' || code.charAt(0) == 'G' || code.charAt(0) == 'P')
170
            fullCode = code;
171
        else
172
            fullCode = "EPSG:" + code;
173
        if (code.length() < 15) {
174
            code = code.substring(code.indexOf(":") + 1);
175
            try {
176
                // Creamos el objeto que tendra los diferentes parametros de la
177
                // cadena Wkt
178
                crsWkt = new CrsWkt(fullCode);
179
                setName(fullCode);
180
                setAbrev(fullCode);
181

  
182
            } catch (NumberFormatException e) {
183
                logger.error("Can't Wkt.", e);
184
            }
185
        } else {
186
            String aux;
187
            String code2 = "";
188
            for (int i = 0; i < code.length(); i++) {
189
                aux = "" + code.charAt(i);
190
                if (!aux.equals(" ")) {
191
                    code2 += aux;
192
                } else {
193
                    code2 += "";
194
                }
195
            }
196
            crsWkt = new CrsWkt(code2);
197

  
198
            setName(fullCode);
199
            // setAbrev(crsWkt.getName());
200
            setAbrev(crsWkt.getAuthority()[0] + ":" + crsWkt.getAuthority()[1]);
201

  
202
        }
203
        // Asignar el datum y el crs base (en el caso de ser projectado):
204
        if (!(crsWkt.getSpheroid()[1].equals("") || crsWkt.getSpheroid()[2].equals(""))) {
205
            double eSemiMajorAxis = Double.valueOf(crsWkt.getSpheroid()[1]).doubleValue();
206
            double eIFlattening = Double.valueOf(crsWkt.getSpheroid()[2]).doubleValue();
207
            datum = new CRSDatum(eSemiMajorAxis, eIFlattening);
208

  
209
            // crs base (en el caso de ser projectado):
210
            /*
211
             * if(this.isProjected()){
212
             * String proj4Base = "+proj=latlong +a=" + crsWkt.getSpheroid()[1]
213
             * + " +rf=" + crsWkt.getSpheroid()[2] ;
214
             * crsBase = new CrsProj(proj4Base);
215
             * }
216
             */
217
        }
218
    }
219

  
220
    /**
221
     * Construye un CRS a partir del c?digo EPSG o de la cadena WKT.
222
     *
223
     * @param epsg_cod
224
     * @param code
225
     * @throws CrsException
226
     */
227
    public Crs(int epsg_cod, String code) throws CrsException {
228
//        String fullCode;
229
        setWKT(code);
230
        setCode(epsg_cod);
231
//        if (code != null || code.charAt(0) == 'E' || code.charAt(0) == 'G' || code.charAt(0) == 'P')
232
//            fullCode = code;
233
//        else
234
//            fullCode = "EPSG:" + code;
235

  
236
        SpatialReference sr = new SpatialReference();
237
//        Vector<String> vector = new Vector<String>();
238
//        vector.add(code);
239
//        sr.ImportFromWkt(vector);
240
        sr.ImportFromWkt(code);
241
        initFromSpatialReference(sr);
242

  
243
//        String cod = "";
244
//        if (code.length() < 15) {
245
//            code = code.substring(code.indexOf(":") + 1);
246
//            try {
247
//                // Creamos el objeto que tendra los diferentes parametros de la
248
//                // cadena Wkt
249
//                crsWkt = new CrsWkt(fullCode);
250
//                setName(fullCode);
251
//                setAbrev(fullCode);
252
//
253
//            } catch (NumberFormatException e) {
254
//                logger.error("Can't get Wkt.", e);
255
//            }
256
//        } else {
257
//            String aux;
258
//            String code2 = "";
259
//            for (int i = 0; i < code.length(); i++) {
260
//                aux = "" + code.charAt(i);
261
//                if (!aux.equals(" ")) {
262
//                    code2 += aux;
263
//                } else {
264
//                    code2 += "";
265
//                }
266
//            }
267
//            crsWkt = new CrsWkt(code2);
268
//            /*
269
//             * Arreglo temporal para ver si funcionan de la iau2000 las
270
//             * proyecciones
271
//             * cilindrica equidistante y oblicua cilindrica equidistante
272
//             * que no estan en gdal, por lo que asignaremos directamente su
273
//             * cadena
274
//             * en proj4 para trabajar con ellas
275
//             */
276
//            if (!crsWkt.getProjection().equals("Equidistant_Cylindrical")
277
//                && !crsWkt.getProjection().equals("Oblique_Cylindrical_Equal_Area")) {
278
//                setName(fullCode);
279
//                // setAbrev(crsWkt.getName());
280
//                setAbrev(crsWkt.getAuthority()[0] + ":" + crsWkt.getAuthority()[1]);
281
//            } else if (crsWkt.getProjection().equals("Equidistant_Cylindrical")) {
282
//                String spheroid1 = crsWkt.getSpheroid()[1];
283
//                String spheroid2 = crsWkt.getSpheroid()[2];
284
//                String centralMeridian = "";
285
//                String falseNorthing = "";
286
//                String falseEasting = "";
287
//                String standardParallel1 = "0.0";
288
//                for (int i = 0; i < crsWkt.getParam_name().length; i++) {
289
//                    if (crsWkt.getParam_name()[i].equals("Central_Meridian"))
290
//                        centralMeridian = crsWkt.getParam_value()[i];
291
//                    if (crsWkt.getParam_name()[i].equals("False_Easting"))
292
//                        falseEasting = crsWkt.getParam_value()[i];
293
//                    if (crsWkt.getParam_name()[i].equals("False_Northing"))
294
//                        falseNorthing = crsWkt.getParam_value()[i];
295
//                    if (crsWkt.getParam_name()[i].equals("Standard_Parallel_1"))
296
//                        standardParallel1 = crsWkt.getParam_value()[i];
297
//                }
298
//                if (spheroid2.equals("0.0")) {
299
//                    proj4String =
300
//                        "+proj=eqc +a=" + spheroid1 + " +lon_0=" + centralMeridian + " +x_0=" + falseEasting + " +y_0="
301
//                            + falseNorthing + " +lat_ts=" + standardParallel1;
302
//                } else {
303
//                    proj4String =
304
//                        "+proj=eqc +a=" + spheroid1 + " +rf=" + spheroid2 + " +lon_0=" + centralMeridian + " +x_0="
305
//                            + falseEasting + " +y_0=" + falseNorthing + " +lat_ts=" + standardParallel1;
306
//                }
307
//                setName(fullCode);
308
//                // setAbrev(crsWkt.getName());
309
//                setAbrev(crsWkt.getAuthority()[0] + ":" + crsWkt.getAuthority()[1]);
310
//
311
//            } else if (crsWkt.getProjection().equals("Oblique_Cylindrical_Equal_Area")) {
312
//                String spheroid1 = crsWkt.getSpheroid()[1];
313
//                String spheroid2 = crsWkt.getSpheroid()[2];
314
//                String centralMeridian = "";
315
//                String falseNorthing = "";
316
//                String falseEasting = "";
317
//                String standardParallel1 = "";
318
//                String standardParallel2 = "0.0";
319
//                for (int i = 0; i < crsWkt.getParam_name().length; i++) {
320
//                    if (crsWkt.getParam_name()[i].equals("Central_Meridian"))
321
//                        centralMeridian = crsWkt.getParam_value()[i];
322
//                    if (crsWkt.getParam_name()[i].equals("False_Easting"))
323
//                        falseEasting = crsWkt.getParam_value()[i];
324
//                    if (crsWkt.getParam_name()[i].equals("False_Northing"))
325
//                        falseNorthing = crsWkt.getParam_value()[i];
326
//                    if (crsWkt.getParam_name()[i].equals("Standard_Parallel_1"))
327
//                        standardParallel1 = crsWkt.getParam_value()[i];
328
//                    if (crsWkt.getParam_name()[i].equals("Standard_Parallel_2"))
329
//                        standardParallel2 = crsWkt.getParam_value()[i];
330
//                }
331
//                if (spheroid2.equals("0.0")) {
332
//                    proj4String =
333
//                        "+proj=ocea +a=" + spheroid1 + " +lon_0=" + centralMeridian + " +x_0=" + falseEasting
334
//                            + " +y_0=" + falseNorthing + " +lat_1=" + standardParallel1 + " +lat_2="
335
//                            + standardParallel2 + " +lon_1=long_1" + " +lon_2=long_2 +no_defs";
336
//                } else {
337
//                    proj4String =
338
//                        "+proj=ocea +a=" + spheroid1 + " +rf=" + spheroid2 + " +lon_0=" + centralMeridian + " +x_0="
339
//                            + falseEasting + " +y_0=" + falseNorthing + " +lat_1=" + standardParallel1 + " +lat_2="
340
//                            + standardParallel2 + " +lon_1=long_1" + " +lon_2=long_2 +no_defs";
341
//                }
342
//                setName(fullCode);
343
//                // setAbrev(crsWkt.getName());
344
//                setAbrev(crsWkt.getAuthority()[0] + ":" + crsWkt.getAuthority()[1]);
345
//            }
346
//        }
347
//        // Asignar el datum:
348
//        if (!(crsWkt.getSpheroid()[1].equals("") || crsWkt.getSpheroid()[2].equals(""))) {
349
//            double eSemiMajorAxis = Double.valueOf(crsWkt.getSpheroid()[1]).doubleValue();
350
//            double eIFlattening = Double.valueOf(crsWkt.getSpheroid()[2]).doubleValue();
351
//            datum = new CRSDatum(eSemiMajorAxis, eIFlattening);
352
//
353
//            // Crs base (en el caso de ser projectado):
354
//            /*
355
//             * if(this.isProjected()){
356
//             * String proj4Base = "+proj=latlong +a=" + crsWkt.getSpheroid()[1]
357
//             * + " +rf=" + crsWkt.getSpheroid()[2] ;
358
//             * crsBase = new CrsProj(proj4Base);
359
//             * }
360
//             */
361
//        }
362
    }
363

  
364
    /**
365
     * Construye un CRS a partir del c?digo EPSG o de la cadena WKT.
366
     * En el caso de WKT le a?ade a la cadena proj4 el string params.
367
     *
368
     * @param epsg_cod
369
     * @param code
370
     * @param params
371
     * @throws CrsException
372
     */
373
    public Crs(int epsg_cod, String code, String params) throws CrsException {
374
        String fullCode;
375
        setCode(epsg_cod);
376
        setWKT(code);
377
        if (code.charAt(0) == 'E' || code.charAt(0) == 'G' || code.charAt(0) == 'P')
378
            fullCode = code;
379
        else
380
            fullCode = "EPSG:" + code;
381
        if (code.length() < 15) {
382
            code = code.substring(code.indexOf(":") + 1);
383
            try {
384
                // Creamos el objeto que tendra los diferentes parametros de la
385
                // cadena Wkt
386
                crsWkt = new CrsWkt(fullCode);
387

  
388
                setName(fullCode);
389
                setAbrev(fullCode);
390

  
391
            } catch (NumberFormatException e) {
392
                logger.error("Can't get Wkt.", e);
393
            }
394
        } else {
395
            String aux;
396
            String code2 = "";
397
            for (int i = 0; i < code.length(); i++) {
398
                aux = "" + code.charAt(i);
399
                if (!aux.equals(" ")) {
400
                    code2 += aux;
401
                } else {
402
                    code2 += "";
403
                }
404
            }
405
            crsWkt = new CrsWkt(code2);
406

  
407
            setName(fullCode);
408
            // setAbrev(crsWkt.getName());
409
            setAbrev(crsWkt.getAuthority()[0] + ":" + crsWkt.getAuthority()[1]);
410

  
411
        }
412
        // Asignar el datum:
413
        if (!(crsWkt.getSpheroid()[1].equals("") || crsWkt.getSpheroid()[2].equals(""))) {
414
            double eSemiMajorAxis = Double.valueOf(crsWkt.getSpheroid()[1]).doubleValue();
415
            double eIFlattening = Double.valueOf(crsWkt.getSpheroid()[2]).doubleValue();
416
            datum = new CRSDatum(eSemiMajorAxis, eIFlattening);
417

  
418
            // Crs base (en el caso de ser projectado):
419
            /*
420
             * if(this.isProjected()){
421
             * String proj4Base = "+proj=latlong +a=" + crsWkt.getSpheroid()[1]
422
             * + " +rf=" + crsWkt.getSpheroid()[2] ;
423
             * crsBase = new CrsProj(proj4Base);
424
             * }
425
             */
426
        }
427
    }
428

  
429
    /*
430
     * public Crs(CrsEpsg source) throws CrsException {
431
     * crsProj4 = source;
432
     * }
433
     */
434

  
435
    /**
436
     * @param code
437
     */
438
    public void setTrans(String code) {
439
        trans = code;
440
        changeTrans(trans);
441
    }
442

  
443
    /**
444
     *
445
     * @param code
446
     */
447
    public void changeTrans(String code) {
448
        getCrsProj().changeStrCrs(code);
449
    }
450

  
451
    /**
452
	 *
453
	 */
454
    public String getAbrev() {
455
        return abrev;
456
    }
457

  
458
    /**
459
     *
460
     * @param code
461
     */
462
    protected void setAbrev(String code) {
463
        abrev = code;
464
    }
465

  
466
    /**
467
     *
468
     * @param nom
469
     */
470
    public void setName(String nom) {
471
        name = nom;
472
    }
473

  
474
    /**
475
     * @return datum
476
     */
477
    public IDatum getDatum() {
478

  
479
        return datum;
480
    }
481

  
482
    /**
483
     * @return CrsWkt
484
     */
485
    public CrsWkt getCrsWkt() {
486
        return crsWkt;
487
    }
488

  
489
    /**
490
     *
491
     * @param wkt
492
     */
493
    public void setWKT(String wkt) {
494
        this.wkt = wkt;
495
    }
496

  
497
    /**
498
     * @return wkt
499
     */
500
    public String getWKT() {
501
        return this.wkt;
502
    }
503

  
504
    /**
505
     *
506
     * @param params
507
     */
508
    public void setTransformationParams(String sourceParams, String targetParams) {
509
        this.sourceTrParams = sourceParams;
510
        this.targetTrParams = targetParams;
511
    }
512

  
513
    /**
514
     * Devuelve los parametros de la transformacion del crs fuente
515
     *
516
     * @return source transformation parameters
517
     */
518
    public String getSourceTransformationParams() {
519
        return this.sourceTrParams;
520
    }
521

  
522
    /**
523
     * Devuelve los parametros de la transformacion del crs destino
524
     *
525
     * @return target transformation parameters
526
     */
527
    public String getTargetTransformationParams() {
528
        return this.targetTrParams;
529
    }
530

  
531
    /**
532
     * @return transformation parameters
533
     */
534
    public String getTransformationParams() {
535
        return this.sourceTrParams;
536
    }
537

  
538
    /**
539
     *
540
     * @return CrsProj
541
     */
542
    public CrsProj getCrsProj() {
543
        if (crsProj == null)
544
            try {
545
                crsProj = new CrsProj(getProj4String());
546
            } catch (CrsException e) {
547
                logger.error("Can't get proj4 string.", e);
548
            }
549
        return crsProj;
550
    }
551

  
552
    /**
553
     * @param x
554
     * @param y
555
     * @return a Point2D
556
     */
557
    public Point2D createPoint(double x, double y) {
558
        return new Point2D.Double(x, y);
559
    }
560

  
561
    /**
562
     * @param g
563
     * @param vp
564
     */
565
    public void drawGrid(Graphics2D g, ViewPortData vp) {
566
        // TODO Auto-generated method stub
567

  
568
    }
569

  
570
    /**
571
     * @param c
572
     */
573
    public void setGridColor(Color c) {
574
        gridColor = c;
575
    }
576

  
577
    /**
578
     * @return grid color
579
     */
580
    public Color getGridColor() {
581
        return gridColor;
582
    }
583

  
584
    /**
585
     * @param dest
586
     * @return Coordinate transformation
587
     */
588
    public ICoordTrans getCT(IProjection dest) {
589

  
590
        try {
591
            if (dest == this)
592
                return null;
593
            COperation operation = null;
594
            if (((ICrs) dest).getSourceTransformationParams() != null
595
                || ((ICrs) dest).getTargetTransformationParams() != null)
596
                operation =
597
                    new COperation(this, (ICrs) dest, ((ICrs) dest).getTargetTransformationParams(),
598
                        ((ICrs) dest).getSourceTransformationParams());
599
            else
600
                operation = new COperation(this, (ICrs) dest, sourceTrParams, targetTrParams);
601
            return operation;
602
        } catch (CrsException e) {
603
            logger.error("Can't get CoordTrans.", e);
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff