forked from the42/cartconvert
/
cartconvert.go
1080 lines (873 loc) · 29 KB
/
cartconvert.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2011,2012 Johann Höchtl. All rights reserved.
// Use of this source code is governed by a Modified BSD License
// that can be found in the LICENSE file.
// This package provides a series of functions to deal with
// conversion, transformation and projection of coordinate systems.
package cartconvert
import (
"bytes"
"errors"
"fmt"
"math"
"strconv"
"strings"
)
// Cartography Errors
var ErrRange = errors.New("value out of range")
var ErrSyntax = errors.New("invalid syntax")
// A CartographyError is yielded when a literal can not be parsed as a bearing specifier.
// In this case the following values may be set and carry the meaning:
type CartographyError struct {
Coord string // a fragment of the coordinate literal containing the error.
Val float64 // The value parsed so far
Index int // Position at which the error occured
Err error // inherited error from an attempt of strconv to parse a number
}
func (ce CartographyError) Error() string {
return fmt.Sprintf("unable to parse fragment \"%s\". Partial value: %f. The additional error was: %s", ce.Coord, ce.Val, ce.Err.Error())
}
// Set of common ellipsoidal models regularly found in cartography
var (
Bessel1841MGIEllipsoid = NewEllipsoid(6377397.155, 6356078.965, "Bessel1841MGI")
Bessel1841Ellipsoid = NewEllipsoid(6377397.155, 6356078.962822, "Bessel1841")
GRS80Ellipsoid = NewEllipsoid(6378137, 6356752.31414, "GRS80")
WGS84Ellipsoid = NewEllipsoid(6378137, 6356752.31425, "WGS84")
Airy1830Ellipsoid = NewEllipsoid(6377563.396, 6356256.909, "Airy1830")
DefaultEllipsoid = WGS84Ellipsoid
)
type Ellipsoid struct {
a, b float64
CommonName string
}
// Holds latitude, longitude and ellipsoidal height, relative to El, the reference ellipsoid
type PolarCoord struct {
Latitude, Longitude, Height float64
El *Ellipsoid
}
// specifier for the string representation of a polar coordinate
type LatLongFormat int
const (
LLFUnknown LatLongFormat = iota
LLFdeg // format a lat/long coordinate in degrees using leading sign for negative bearings
LLFdms // format a lat/long coordinate in degrees, minutes and seconds with prepended main directions N, S, E, W
)
func (spec LatLongFormat) String() string {
switch spec {
case LLFdeg:
return "LLFdeg"
case LLFdms:
return "LLFdms"
}
return "#unknown"
}
func f64toa(val float64, prec int) string {
sval := fmt.Sprintf("%.*f", prec, val)
n := len(sval)
for n > 0 && sval[n-1] == '0' {
n--
}
if n > 0 && sval[n-1] == '.' {
n--
}
return sval[:n]
}
func LatLongToString(pc *PolarCoord, format LatLongFormat) (string, string) {
var lat, long, latrem, longrem, latmin, longmin, latsec, longsec float64
var latitude, longitude string
switch format {
case LLFdeg:
latitude = f64toa(pc.Latitude, 6)
longitude = f64toa(pc.Longitude, 6)
case LLFdms:
lat, latrem = math.Modf(pc.Latitude)
if lat < 0 {
lat *= -1
latrem *= -1
}
long, longrem = math.Modf(pc.Longitude)
if long < 0 {
long *= -1
longrem *= -1
}
latmin, latrem = math.Modf(latrem / 100 * 6000)
longmin, longrem = math.Modf(longrem / 100 * 6000)
latsec = latrem / 100 * 6000
longsec = longrem / 100 * 6000
if pc.Latitude < 0 {
latitude = "S "
} else {
latitude = "N "
}
latitude += fmt.Sprintf("%d°", int(lat))
if latmin != 0.0 || latsec != 0.0 {
latitude += fmt.Sprintf("%d'", int(latmin))
}
if latsec != 0.0 {
latitude += fmt.Sprintf("%s''", f64toa(latsec, 2))
}
if pc.Longitude < 0 {
longitude = "W "
} else {
longitude = "E "
}
longitude += fmt.Sprintf("%d°", int(long))
if longmin != 0.0 || longsec != 0.0 {
longitude += fmt.Sprintf("%d'", int(longmin))
}
if longsec != 0.0 {
longitude += fmt.Sprintf("%s''", f64toa(longsec, 2))
}
}
return latitude, longitude
}
// Canonical representation of a lat/long bearing
func (pc *PolarCoord) String() string {
lat, long := LatLongToString(pc, LLFdeg)
return "lat: " + lat + "°, long: " + long + "°"
}
// A generic representation of easting (right, Y) and northing (Height,X) of a 2D projection
// relative to Ellipsoid El. The height H at Point X,Y is above defining ellipsoid
type GeoPoint struct {
X, Y, H float64
El *Ellipsoid
}
// A generic Cartesian, geocentric point. For ease of conversion between polar and Cartesian
// coordinates, the ellipsis might be included
type CartPoint struct {
X, Y, Z float64
El *Ellipsoid
}
func degtorad(deg float64) float64 {
return math.Pi * deg / 180
}
func radtodeg(rad float64) float64 {
return 180 * rad / math.Pi
}
func removeblank(input string) string {
var accu string
for _, token := range input {
switch token {
case ' ':
continue
default:
accu += string(token)
}
}
return accu
}
// The function accepts a string representing a bearing in degree, minute and second.
// Minute and second are booth optional and the second may contain fractions.
// The bearing may be prepended by the literal 'N', 'E', 'S', 'W', representing the
// four main directions. 'S' and 'W' denotes negative bearing. Instead of the main directions,
// the signs '+' or '-' may be used.
//
// [N|E|S|W|+|-]ddd°[dd'[dd'']]
func ADegMMSSToNum(DegMMSS string) (float64, error) {
var accu string
var i, position int
var token rune
var tf, degf float64
var err error
degree := strings.ToUpper(removeblank(DegMMSS))
slen := len(degree)
negate := false
// parse the degree
L2:
for i, token = range degree {
switch token {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
accu += string(token)
case 'S', 'W', '-':
negate = true
case 'N', 'E', '+':
continue
case '°':
degf, err = strconv.ParseFloat(accu, 64)
if err != nil {
return degf, err
}
i += len("°")
degree = degree[i:]
position += i
accu = ""
break L2
default:
return 0, CartographyError{Val: degf, Index: i, Coord: degree, Err: ErrSyntax}
}
}
L4:
// parse the minute
for i, token = range degree {
switch token {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
accu += string(token)
case '\'':
tf, err = strconv.ParseFloat(accu, 64)
if err != nil {
return tf, err
}
degf += tf / 60.0
i += len("'")
degree = degree[i:]
position += i
accu = ""
break L4
default:
return 0, CartographyError{Val: degf, Index: i, Coord: degree, Err: ErrSyntax}
}
}
// parse the second
L6:
for i, token = range degree {
switch token {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.':
accu += string(token)
case '\'':
tf, err = strconv.ParseFloat(accu, 64)
if err != nil {
return tf, err
}
degf += tf / (60.0 * 60.0)
i += len("'")
degree = degree[i:]
position += i
if !(position < slen && degree[0] == '\'') {
return 0, CartographyError{Val: degf, Index: i, Coord: degree, Err: ErrSyntax}
}
break L6
default:
return 0, CartographyError{Val: degf, Index: i, Coord: degree, Err: ErrSyntax}
}
}
if negate {
degf = -degf
}
return degf, nil
}
// The function accepts a string literal representing a bearing
// denoted as decimal degrees. The suffix is optional.
// The literal value must end with the degree mark '°'
// The bearing may be prepended by the literal 'N', 'E', 'S', 'W', representing the
// four main directions. 'S' and 'W' denotes negative bearing. Instead of the main directions,
// the signs '+' or '-' may be used.
//
// [N|E|S|W|+|-]ddd[.suffix]°
func ADegCommaToNum(DegComma string) (float64, error) {
var accu string
var i int
var token rune
var degf, tf float64
var err error
degree := strings.ToUpper(removeblank(DegComma))
negate := false
// parse the degree
L2:
for i, token = range degree {
switch token {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
accu += string(token)
case 'S', 'W', '-':
negate = true
case 'N', 'E', '+':
continue
case '.', '°':
degf, err = strconv.ParseFloat(accu, 64)
if err != nil {
return degf, err
}
degree = degree[i+len(string(token)):]
accu = ""
break L2
default:
return 0, CartographyError{Val: degf, Index: i, Coord: degree, Err: ErrSyntax}
}
}
L4:
// parse the suffix
for i, token = range degree {
switch token {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
accu += string(token)
case '°':
tf, err = strconv.ParseFloat("0."+accu, 64)
if err != nil {
return tf, err
}
degf += tf
accu = ""
break L4
default:
return 0, CartographyError{Val: degf, Index: i, Coord: degree, Err: ErrSyntax}
}
}
if len(accu) > 0 {
return 0, CartographyError{Val: degf, Index: i, Coord: degree, Err: ErrSyntax}
}
if negate {
degf = -degf
}
return degf, nil
}
// ## Polar to Cartesian coordinate conversion and vice-versa
// Function accepts two bearing datum as Deg°MM'SS'' (typically northing and easting)
// and height at bearing relative to reference ellipsoid and returns a polar coordinate type.
// If the reference ellipsoid is nil, the DefaultEllipsoid will be set in the resulting polar coordinate.
func ADegMMSSToPolar(Northing, Easting string, Height float64, El *Ellipsoid) (*PolarCoord, error) {
northing, err := ADegMMSSToNum(Northing)
if err == nil {
easting, err := ADegMMSSToNum(Easting)
if err == nil {
el := El
if el == nil {
el = DefaultEllipsoid
}
return &PolarCoord{Latitude: northing, Longitude: easting, Height: Height, El: el}, nil
}
}
return nil, err
}
// Convert polar coordinates to Cartesian. The polar coordinates must be in decimal degrees.
// The reference ellipsoid is copied verbatim to the result.
// Inspired by http://www.movable-type.co.uk/scripts/latlong-convert-coords.html
func PolarToCartesian(gc *PolarCoord) *CartPoint {
var p CartPoint
el := gc.El
lat := degtorad(gc.Latitude)
long := degtorad(gc.Longitude)
esq := (el.a*el.a - el.b*el.b) / (el.a * el.a)
u := el.a / math.Sqrt(1-esq*math.Pow(math.Sin(lat), 2))
p.X = (gc.Height + u) * math.Cos(lat) * math.Cos(long)
p.Y = (gc.Height + u) * math.Cos(lat) * math.Sin(long)
p.Z = ((1-esq)*u + gc.Height) * math.Sin(lat)
p.El = el
return &p
}
// Convert Cartesian coordinates to polar.
// The reference ellipsoid is copied verbatim to the result.
// The resulting polar coordinates are in decimal degrees.
// Inspired by http://www.movable-type.co.uk/scripts/latlong-convert-coords.html
func CartesianToPolar(pt *CartPoint) *PolarCoord {
var gc PolarCoord
el := pt.El
esq := (el.a*el.a - el.b*el.b) / (el.a * el.a)
p := math.Hypot(pt.X, pt.Y)
lat := math.Atan2(pt.Z, p*(1-esq))
lat0 := 2.0 * math.Pi
precision := 4.0 / el.a
var v float64
for math.Abs(lat-lat0) > precision {
v = el.a / math.Sqrt(1-esq*math.Pow(math.Sin(lat), 2))
lat0 = lat
lat = math.Atan2(pt.Z+esq*v*math.Sin(lat), p)
}
gc.Height = p/math.Cos(lat) - v
gc.Latitude = radtodeg(lat)
gc.Longitude = radtodeg(math.Atan2(pt.Y, pt.X))
gc.El = el
return &gc
}
// ## Transverse Mercator Projection
// Direct transverse mercator projection: Projection of an ellipsoid onto the surface of
// of a cylinder. Also known as Gauss-Krüger projection. Input parameters:
//
// gc *PolarCoord: Latitude and Longitude or point to be projected; in decimal degrees
// latO, longO: Shifted origin of latitude and longitude in decimal degrees
// fe, fn: False easting and northing respectively in meters
// scale: Projection scaling; Dimensionless, typically 1 or little bellow
//
// This algorithm uses the algorithm described by Redfearn
// http://en.wikipedia.org/wiki/Transverse_Mercator:_Redfearn_series
//
// Taken from "OGP Publication 373-7-2 – Surveying and Positioning Guidance Note number 7, part 2 – November 2010",
// pp. 48 - 51
func DirectTransverseMercator(gc *PolarCoord, latO, longO, scale, fe, fn float64) *GeoPoint {
var pt GeoPoint
el := gc.El
latOrad := degtorad(latO)
longOrad := degtorad(longO)
latrad := degtorad(gc.Latitude)
longrad := degtorad(gc.Longitude)
f := 1 - el.b/el.a
esq := math.Sqrt(2.0*f - f*f)
n := f / (2.0 - f)
B := (el.a / (1 + n)) * (1 + n*n/4.0 + n*n*n*n/64.0)
h1 := n/2.0 - (2.0/3.0)*(n*n) + (5.0/16.0)*(n*n*n) + (41.0/180.0)*(n*n*n*n)
h2 := (13.0/48.0)*(n*n) - (3.0/5.0)*(n*n*n) + (557.0/1440.0)*(n*n*n*n)
h3 := (61.0/240.0)*(n*n*n) - (103.0/140.0)*(n*n*n*n)
h4 := (49561.0 / 161280.0) * (n * n * n * n)
var SO float64
if latOrad != 0.0 {
QO := math.Asinh(math.Tan(latOrad)) - (esq * math.Atanh(esq*math.Sin(latOrad)))
bO := math.Atan(math.Sinh(QO))
xiO0 := bO // math.Asin(math.Sin(bO))
xiO1 := h1 * math.Sin(2.0*xiO0)
xiO2 := h2 * math.Sin(4.0*xiO0)
xiO3 := h3 * math.Sin(6.0*xiO0)
xiO4 := h4 * math.Sin(8.0*xiO0)
xiO := xiO0 + xiO1 + xiO2 + xiO3 + xiO4
SO = B * xiO
}
Q := math.Asinh(math.Tan(latrad)) - (esq * math.Atanh(esq*math.Sin(latrad)))
b := math.Atan(math.Sinh(Q))
eta0 := math.Atanh(math.Cos(b) * math.Sin(longrad-longOrad))
xi0 := math.Asin(math.Sin(b) * math.Cosh(eta0))
xi1 := h1 * math.Sin(2*xi0) * math.Cosh(2*eta0)
xi2 := h2 * math.Sin(4*xi0) * math.Cosh(4*eta0)
xi3 := h3 * math.Sin(6*xi0) * math.Cosh(6*eta0)
xi4 := h4 * math.Sin(8*xi0) * math.Cosh(8*eta0)
xi := xi0 + xi1 + xi2 + xi3 + xi4
eta1 := h1 * math.Cos(2*xi0) * math.Sinh(2*eta0)
eta2 := h2 * math.Cos(4*xi0) * math.Sinh(4*eta0)
eta3 := h3 * math.Cos(6*xi0) * math.Sinh(6*eta0)
eta4 := h4 * math.Cos(8*xi0) * math.Sinh(8*eta0)
eta := eta0 + eta1 + eta2 + eta3 + eta4
pt.X = fe + scale*B*eta
pt.Y = fn + scale*(B*xi-SO)
pt.El = el
return &pt
}
// Inverse transverse mercator projection: Projection of an cylinder onto the surface of
// of an ellipsoid. Also known as reverse Gauss-Krüger projection. Input parameters:
//
// pt *GeoPoint: Easting(Y) and Northing(X) of map point to be projected; in meters
// latO, longO: Shifted origin of latitude and longitude in decimal degrees
// fe, fn: False easting and northing respectively in meters
// scale: Projection scaling; Dimensionless, typically 1 or little bellow
//
// This algorithm uses the algorithm described by Redfearn
// http://en.wikipedia.org/wiki/Transverse_Mercator:_Redfearn_series
//
// Taken from "OGP Publication 373-7-2 – Surveying and Positioning Guidance Note number 7, part 2 – November 2010",
// pp. 48 - 51
//
// More accurate, iterative but slower algorithmic implementation
func InverseTransverseMercator(pt *GeoPoint, latO, longO, scale, fe, fn float64) *PolarCoord {
var gc PolarCoord
el := pt.El
latOrad := degtorad(latO)
longOrad := degtorad(longO)
f := 1 - el.b/el.a
esq := math.Sqrt(2.0*f - f*f)
n := f / (2.0 - f)
B := (el.a / (1 + n)) * (1 + n*n/4.0 + n*n*n*n/64.0)
var SO float64
if latOrad != 0.0 {
h1 := n/2.0 - (2.0/3.0)*n*n + (5.0/16.0)*n*n*n + (41.0/180.0)*n*n*n*n
h2 := (13.0/48.0)*n*n - (3.0/5.0)*n*n*n + (557.0/1440.0)*n*n*n*n
h3 := (61.0/240.0)*n*n*n - (103.0/140.0)*n*n*n*n
h4 := (49561.0 / 161280.0) * n * n * n * n
QO := math.Asinh(math.Tan(latOrad)) - (esq * math.Atanh(esq*math.Sin(latOrad)))
bO := math.Atan(math.Sinh(QO))
xiO0 := bO // math.Asin(math.Sin(bO))
xiO1 := h1 * math.Sin(2.0*xiO0)
xiO2 := h2 * math.Sin(4.0*xiO0)
xiO3 := h3 * math.Sin(6.0*xiO0)
xiO4 := h4 * math.Sin(8.0*xiO0)
xiO := xiO0 + xiO1 + xiO2 + xiO3 + xiO4
SO = B * xiO
}
h1i := n/2.0 - (2.0/3.0)*n*n + (37.0/96.0)*n*n*n - (1.0/360.0)*n*n*n*n
h2i := (1.0/48.0)*n*n + (1.0/15.0)*n*n*n - (437.0/1440.0)*n*n*n*n
h3i := (17.0/480.0)*n*n*n - (37.0/840.0)*n*n*n*n
h4i := (4397.0 / 161280.0) * n * n * n * n
etai := (pt.X - fe) / (B * scale)
xii := ((pt.Y - fn) + scale*SO) / (B * scale)
xi1i := h1i * math.Sin(2*xii) * math.Cosh(2*etai)
xi2i := h2i * math.Sin(4*xii) * math.Cosh(4*etai)
xi3i := h3i * math.Sin(6*xii) * math.Cosh(6*etai)
xi4i := h4i * math.Sin(8*xii) * math.Cosh(8*etai)
eta1i := h1i * math.Cos(2*xii) * math.Sinh(2*etai)
eta2i := h2i * math.Cos(4*xii) * math.Sinh(4*etai)
eta3i := h3i * math.Cos(6*xii) * math.Sinh(6*etai)
eta4i := h4i * math.Cos(8*xii) * math.Sinh(8*etai)
xi0i := xii - (xi1i + xi2i + xi3i + xi4i)
eta0i := etai - (eta1i + eta2i + eta3i + eta4i)
bi := math.Asin(math.Sin(xi0i) / math.Cosh(eta0i))
Qi := math.Asinh(math.Tan(bi))
Qiiold := Qi + (esq * math.Atanh(esq*math.Tanh(Qi)))
Qii := Qi + (esq * math.Atanh(esq*math.Tanh(Qiiold)))
for math.Abs(Qiiold-Qii) > 1e-12 {
Qiiold = Qii
Qii = Qi + (esq * math.Atanh(esq*math.Tanh(Qiiold)))
}
gc.Latitude = radtodeg(math.Atan(math.Sinh(Qii)))
gc.Longitude = radtodeg(longOrad + math.Asin(math.Tanh(eta0i)/math.Cos(bi)))
gc.El = el
return &gc
}
// ## UTM coordinate functions for parsing and conversion
// A UTM coordinate defined by Northin, Easting and relative origin by Zone
// The reference ellipsoid is typically the GRS80Ellipsoid or the WGS84Ellipsoid
type UTMCoord struct {
Northing, Easting float64
Zone string
El *Ellipsoid
}
// Canonical representation of an UTM coordinate
func (utm *UTMCoord) String() string {
return fmt.Sprintf("%s %.0f %.0f", utm.Zone, utm.Easting, utm.Northing)
}
// This function parses a string UTM coordinate literal of the format
//
// "ZONE EASTING NORTHING"
//
// Zone is the UTM meridian zone specifier and must be specified in the unambiguous
// way of zone number and latitude band. Easting and northing are specified as decimal meters.
// If the reference ellipsoid is nil, the DefaultEllipsoid is assumed.
func AUTMToStruct(utmcoord string, el *Ellipsoid) (*UTMCoord, error) {
var zone, northing, easting string
var north, east float64
var err error
compact := strings.TrimSpace(utmcoord)
L1:
for i, index := 0, 0; i < 3; i++ {
index = strings.Index(compact, " ")
if index == -1 {
index = len(compact)
}
switch i {
case 0:
zone = compact[:index]
case 1:
easting = compact[:index]
case 2:
northing = compact[:index]
break L1
}
compact = compact[index+len(" "):]
compact = strings.TrimLeft(compact, " ")
}
north, err = strconv.ParseFloat(northing, 64)
if err != nil {
return nil, err
}
east, err = strconv.ParseFloat(easting, 64)
if err != nil {
return nil, err
}
if el == nil {
el = DefaultEllipsoid
}
return &UTMCoord{Northing: north, Easting: east, Zone: zone, El: el}, nil
}
// Convert from UTM 2D projection to 3D polar. If the UTM coordinates do not contain a
// reference ellipsoid, the WGS84Ellipsoid is assumed and copied to the resulting polar coordinates.
//
// Inspired by http://www.gpsy.com/gpsinfo/geotoutm/gantz/LatLong-UTMconversion.cpp.txt
func UTMToLatLong(coord *UTMCoord) (*PolarCoord, error) {
zonelength := len(coord.Zone)
utmLetter := int8(coord.Zone[zonelength-1:][0])
zonenumber, err := strconv.ParseUint(coord.Zone[:zonelength-1], 10, 0)
if err != nil {
return nil, err
}
pt := &GeoPoint{Y: coord.Northing, X: coord.Easting, El: coord.El}
if utmLetter-'N' < 0 {
pt.Y -= 10000000.0
}
if pt.El == nil {
pt.El = DefaultEllipsoid
}
gc := InverseTransverseMercator(pt, 0, (float64(zonenumber)-1)*6-180+3, 0.9996, 500000, 0)
return gc, nil
}
// Convert from 3D polar to UTM 2D projection. If the polar coordinates do not contain a
// reference ellipsoid, the WGS84Ellipsoid is assumed and copied to the resulting UTM coordinates.
//
// Inspired by http://www.gpsy.com/gpsinfo/geotoutm/gantz/LatLong-UTMconversion.cpp.txt
func LatLongToUTM(gcin *PolarCoord) *UTMCoord {
var utm UTMCoord
gc := *gcin // Make a copy as we might set the ellipsoid and we will not alter the input values
zonenumber := uint((gc.Longitude+180)/6) + 1
if gc.Latitude >= 56.0 && gc.Latitude < 64.0 && gc.Longitude >= 3.0 && gc.Longitude < 12.0 {
zonenumber = 32
}
if gc.Latitude >= 72.0 && gc.Latitude < 84.0 {
switch {
case gc.Longitude >= 0.0 && gc.Longitude < 9.0:
zonenumber = 31
case gc.Longitude >= 9.0 && gc.Longitude < 21.0:
zonenumber = 33
case gc.Longitude >= 21.0 && gc.Longitude < 33.0:
zonenumber = 35
case gc.Longitude >= 33.0 && gc.Longitude < 42.0:
zonenumber = 37
}
}
if gc.El == nil {
gc.El = DefaultEllipsoid
}
pt := DirectTransverseMercator(&gc, 0, (float64(zonenumber)-1)*6-180+3, 0.9996, 500000, 0)
utm.Zone = strconv.FormatUint(uint64(zonenumber), 10) + string(utmLetterDesignator(gc.Latitude))
utm.Northing = pt.Y
utm.Easting = pt.X
if gc.Latitude < 0 {
utm.Northing += 10000000
}
utm.El = pt.El
return &utm
}
// This routine determines the correct UTM letter designator for the given latitude
// returns 'Z' if latitude is outside the UTM limits of 84N to 80S
func utmLetterDesignator(Lat float64) (LetterDesignator byte) {
switch {
case 84 >= Lat && Lat >= 72:
LetterDesignator = 'X'
case 72 > Lat && Lat >= 64:
LetterDesignator = 'W'
case 64 > Lat && Lat >= 56:
LetterDesignator = 'V'
case 56 > Lat && Lat >= 48:
LetterDesignator = 'U'
case 48 > Lat && Lat >= 40:
LetterDesignator = 'T'
case 40 > Lat && Lat >= 32:
LetterDesignator = 'S'
case 32 > Lat && Lat >= 24:
LetterDesignator = 'R'
case 24 > Lat && Lat >= 16:
LetterDesignator = 'Q'
case 16 > Lat && Lat >= 8:
LetterDesignator = 'P'
case 8 > Lat && Lat >= 0:
LetterDesignator = 'N'
case 0 > Lat && Lat >= -8:
LetterDesignator = 'M'
case -8 > Lat && Lat >= -16:
LetterDesignator = 'L'
case -16 > Lat && Lat >= -24:
LetterDesignator = 'K'
case -24 > Lat && Lat >= -32:
LetterDesignator = 'J'
case -32 > Lat && Lat >= -40:
LetterDesignator = 'H'
case -40 > Lat && Lat >= -48:
LetterDesignator = 'G'
case -48 > Lat && Lat >= -56:
LetterDesignator = 'F'
case -56 > Lat && Lat >= -64:
LetterDesignator = 'E'
case -64 > Lat && Lat >= -72:
LetterDesignator = 'D'
case -72 > Lat && Lat >= -80:
LetterDesignator = 'C'
default:
LetterDesignator = 'Z' // error flag to show that the Latitude is outside the UTM limits
}
return
}
// Base32 codeset for geohash as described in http://en.wikipedia.org/wiki/Geohash
var Base32GeohashCode = []byte("0123456789bcdefghjkmnpqrstuvwxyz")
// The following functions deal with geohash encoding & decoding as described in http://en.wikipedia.org/wiki/Geohash
// Inspiration taken from
// - http://code.google.com/p/geospatialweb/source/browse/trunk/geohash/src/Geohash.java
// - http://blog.dixo.net/downloads/geohash-php-class/
// - https://github.com/kungfoo/geohsh-java/blob/master/src/main/java/ch/hsr/geohash/GeoHash.java
// - https://github.com/broady/gogeohash/blob/master/geohash.go
// Return latitude & longitude from a geohash-encoded string.
// If the reference ellipsoid is nil, the default Ellipsoid will be returned.
// If the string is not a geohash, err will be set to ERRRANGE.
func GeoHashToLatLong(geohash string, el *Ellipsoid) (*PolarCoord, error) {
latrange := [2]float64{-90, 90}
longrange := [2]float64{-180, 180}
errlat := latrange[1]
errlong := longrange[1]
bytehash := []byte(geohash)
even := true
for _, r := range bytehash {
i := bytes.IndexByte(Base32GeohashCode, r)
if i < 0 {
return nil, ErrRange
}
for j := 16; j != 0; j >>= 1 {
var index int
if i&j == 0 {
index = 1
} else {
index = 0
}
if even {
longrange[index] = (longrange[0] + longrange[1]) / 2.0
errlong /= 2
} else {
latrange[index] = (latrange[0] + latrange[1]) / 2.0
errlat /= 2
}
even = !even
}
}
if el == nil {
el = DefaultEllipsoid
}
return &PolarCoord{
Latitude: round((latrange[0]+latrange[1])/2.0, int(math.Max(1.0, -round(math.Log10(errlat), 0))-1)),
Longitude: round((longrange[0]+longrange[1])/2.0, int(math.Max(1.0, -round(math.Log10(errlong), 0))-1)),
El: el},
nil
}
// a general purpose round
func round(x float64, prec int) float64 {
var rounder float64
pow := math.Pow(10, float64(prec))
intermed := x * pow
_, frac := math.Modf(intermed)
x = .5
if frac < 0.0 {
x = -.5
}
if frac >= x {
rounder = math.Ceil(intermed)
} else {
rounder = math.Floor(intermed)
}
return rounder / pow
}
// Returns precision of number.
// precision of 42 is 0.5
// precision of 42.4 is 0.05
// precision of 42.41 is 0.005 etc
func precision(val float64) float64 {
str := strconv.FormatFloat(val, 'f', -1, 64)
pos := strings.IndexRune(str, '.')
if pos == -1 {
return 0.5
}
pos = len(str) - pos - 1
return math.Pow(10, -float64(pos)) / 2
}
// Return a geohased representation of a latitude & longitude bearing point.
func LatLongToGeoHash(pc *PolarCoord) string {
// the suffix of a float64 may not be accurately representable as a string value due to
// IEEE bit representation. Geohash-Encoding supports only 6 digits remainder either
preclat := precision(pc.Latitude)
preclong := precision(pc.Longitude)
bits := byte(1)
for laterr, longerr := 45.0, 90.0; laterr > preclat || longerr > preclong; {
longerr /= 2.0
laterr /= 2.0
bits++
}
// precision is for latitude and longitude so multiply by two
bits *= 2
// assure that once bits is not a multiple of five it will be rounded towards the next integer
bits = (bits-1)/5 + 1
return LatLongToGeoHashBits(pc, bits)
}
// Return a geohased representation of a latitude & longitude bearing point using bits precision.
// If bits is 0 or larger than 30, it is set to a maximum of 30 bits
func LatLongToGeoHashBits(pc *PolarCoord, precision byte) string {
if precision == 0 || precision > 30 {
precision = 30
}
latrange := [2]float64{-90, 90}
longrange := [2]float64{-180, 180}
even := true
bit := 0
n := 0
var mid float64
var geohash string
for byte(len(geohash)) < precision {
n <<= 1
if even {
mid = (longrange[0] + longrange[1]) / 2
if pc.Longitude >= mid {
longrange[0] = mid
n ^= 1
} else {
longrange[1] = mid
n ^= 0
}
} else {
mid = (latrange[0] + latrange[1]) / 2
if pc.Latitude >= mid {
latrange[0] = mid
n ^= 1
} else {
latrange[1] = mid
n ^= 0
}
}
if bit == 4 {
geohash += string(Base32GeohashCode[n])
bit = 0
n = 0
} else {
bit++
}
even = !even
}
return geohash
}
// HELMERT Transformation - http://en.wikipedia.org/wiki/Helmert_transformation
// Returns a new ellipsoid by the given major axis a and major axis b in meters.
func NewEllipsoid(a, b float64, CommonName string) *Ellipsoid {
return &Ellipsoid{a: a, b: b, CommonName: CommonName}
}
// ## Helmert transformation
type transformer struct {
dx, dy, dz, dM, drx, dry, drz float64