-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathh3.go
More file actions
1475 lines (1221 loc) · 44.5 KB
/
h3.go
File metadata and controls
1475 lines (1221 loc) · 44.5 KB
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
// Package h3 is the go binding for Uber's H3 Geo Index system.
// It uses cgo to link with a statically compiled h3 library
package h3
/*
* Copyright 2018 Uber Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
#cgo CFLAGS: -std=c99
#cgo CFLAGS: -DH3_HAVE_VLA=1
#cgo LDFLAGS: -lm
#include <stdlib.h>
#include <h3_h3api.h>
#include <h3_h3Index.h>
#include <h3_polygon.h>
#include <h3_polyfill.h>
*/
import "C"
import (
"encoding"
"errors"
"fmt"
"math"
"strconv"
"strings"
"unsafe"
)
const (
// MaxCellBndryVerts is the maximum number of vertices that can be used
// to represent the shape of a cell.
MaxCellBndryVerts = C.MAX_CELL_BNDRY_VERTS
// MaxResolution is the maximum H3 resolution a LatLng can be indexed to.
MaxResolution = C.MAX_H3_RES
// NumIcosaFaces is the number of faces on an icosahedron.
NumIcosaFaces = C.NUM_ICOSA_FACES
// NumBaseCells is the number of H3 base cells.
NumBaseCells = C.NUM_BASE_CELLS
// NumPentagons is the number of H3 pentagon cells (same at every resolution).
NumPentagons = C.NUM_PENTAGONS
// InvalidH3Index is a sentinel value for an invalid H3 index.
InvalidH3Index = C.H3_NULL
base16 = 16
bitSize = 64
numCellEdges = 6
numEdgeCells = 2
numCellVertexes = 6
// DegsToRads converts degrees to radians by multiplying degrees by this constant.
DegsToRads = math.Pi / 180.0
// RadsToDegs converts radians to degrees by multiplying radians by this constant.
RadsToDegs = 180.0 / math.Pi
)
const (
latLngFloatPrecision = 5
// latLngStringSize is the size to pre-allocate the buffer for.
// Given latLngFloatPrecision, a typical string is "(DD.DDDDD, -DDD.DDDDD)"
// which is ~25-30 bytes. 32 is a safe and efficient capacity to start with
// to avoid re-allocation.
latLngStringSize = 32
)
var (
// pow7 holds precomputed powers of 7: pow7[i] == 7^i for i in [0, MaxResolution].
pow7 = [16]int{
1,
7,
49,
343,
2401,
16807,
117649,
823543,
5764801,
40353607,
282475249,
1977326743,
13841287201,
96889010407,
678223072849,
4747561509943,
}
// compile-time check: pow7 must have exactly MaxResolution+1 entries.
_ = pow7[MaxResolution]
)
// PolygonToCells containment modes
const (
ContainmentCenter ContainmentMode = C.CONTAINMENT_CENTER // Cell center is contained in the shape
ContainmentFull ContainmentMode = C.CONTAINMENT_FULL // Cell is fully contained in the shape
ContainmentOverlapping ContainmentMode = C.CONTAINMENT_OVERLAPPING // Cell overlaps the shape at any point
ContainmentOverlappingBbox ContainmentMode = C.CONTAINMENT_OVERLAPPING_BBOX // Cell bounding box overlaps shape
ContainmentInvalid ContainmentMode = C.CONTAINMENT_INVALID // This mode is invalid and should not be used
)
// Error codes.
var (
ErrFailed = errors.New("the operation failed")
ErrDomain = errors.New("argument was outside of acceptable range")
ErrLatLngDomain = errors.New("latitude or longitude arguments were outside of acceptable range")
ErrResolutionDomain = errors.New("resolution argument was outside of acceptable range")
ErrCellInvalid = errors.New("H3Index cell argument was not valid")
ErrDirectedEdgeInvalid = errors.New("H3Index directed edge argument was not valid")
ErrUndirectedEdgeInvalid = errors.New("H3Index undirected edge argument was not valid")
ErrVertexInvalid = errors.New("H3Index vertex argument was not valid")
ErrPentagon = errors.New("pentagon distortion was encountered")
ErrDuplicateInput = errors.New("duplicate input was encountered in the arguments")
ErrNotNeighbors = errors.New("H3Index cell arguments were not neighbors")
ErrRsolutionMismatch = errors.New("H3Index cell arguments had incompatible resolutions")
ErrMemoryAlloc = errors.New("necessary memory allocation failed")
ErrMemoryBounds = errors.New("bounds of provided memory were not large enough")
ErrOptionInvalid = errors.New("mode or flags argument was not valid")
ErrIndexInvalid = errors.New("index argument was not valid")
ErrBaseCellDomain = errors.New("base cell number was outside of acceptable range")
ErrDigitDomain = errors.New("child digits invalid")
ErrDeletedDigit = errors.New("deleted subsequence indicates invalid index")
errMap = map[C.uint32_t]error{
0: nil, // Success error code.
1: ErrFailed,
2: ErrDomain,
3: ErrLatLngDomain,
4: ErrResolutionDomain,
5: ErrCellInvalid,
6: ErrDirectedEdgeInvalid,
7: ErrUndirectedEdgeInvalid,
8: ErrVertexInvalid,
9: ErrPentagon,
10: ErrDuplicateInput,
11: ErrNotNeighbors,
12: ErrRsolutionMismatch,
13: ErrMemoryAlloc,
14: ErrMemoryBounds,
15: ErrOptionInvalid,
16: ErrIndexInvalid,
17: ErrBaseCellDomain,
18: ErrDigitDomain,
19: ErrDeletedDigit,
}
)
type (
// Cell is an Index that identifies a single hexagon cell at a resolution.
Cell int64
// DirectedEdge is an Index that identifies a directed edge between two cells.
DirectedEdge int64
// Vertex is an Index that identifies a single topological vertex, shared by three cells.
// A vertex is arbitrarily assigned one of the three neighboring cells as its "owner", which is used to calculate
// the canonical index and geographic coordinates for the vertex.
Vertex int64
// Index refers to an [H3 index], which may be one of multiple modes to indicate the concept being indexed.
//
// [H3 index]: https://h3geo.org/docs/core-library/h3Indexing
Index interface {
Cell | DirectedEdge | Vertex
}
// CoordIJ IJ hexagon coordinates
//
// Each axis is spaced 120 degrees apart.
CoordIJ struct {
I, J int
}
// CellBoundary is a slice of LatLng. Note, len(CellBoundary) will never
// exceed MaxCellBndryVerts.
CellBoundary []LatLng
// GeoLoop is a slice of LatLng points that make up a loop.
GeoLoop []LatLng
// LatLng is a struct for geographic coordinates in degrees.
LatLng struct {
Lat, Lng float64
}
// GeoPolygon is a GeoLoop with 0 or more GeoLoop holes.
GeoPolygon struct {
GeoLoop GeoLoop
Holes []GeoLoop
}
// ContainmentMode is an int for specifying PolygonToCell containment behavior.
ContainmentMode C.uint32_t
)
// compile time checks that ensure interface implementation
var (
_ encoding.TextMarshaler = (*Cell)(nil)
_ encoding.TextUnmarshaler = (*Cell)(nil)
_ encoding.TextMarshaler = (*Vertex)(nil)
_ encoding.TextUnmarshaler = (*Vertex)(nil)
_ encoding.TextMarshaler = (*DirectedEdge)(nil)
_ encoding.TextUnmarshaler = (*DirectedEdge)(nil)
)
// NewLatLng is a helper function to create a LatLng.
func NewLatLng(lat, lng float64) LatLng {
return LatLng{lat, lng}
}
// LatLngToCell returns the Cell at resolution for a geographic coordinate.
func LatLngToCell(latLng LatLng, resolution int) (Cell, error) {
var i C.H3Index
cLatLng := latLng.toC()
errC := C.latLngToCell(&cLatLng, C.int(resolution), &i)
return Cell(i), toErr(errC)
}
// Cell returns the Cell at resolution for a geographic coordinate.
func (g LatLng) Cell(resolution int) (Cell, error) {
return LatLngToCell(g, resolution)
}
// CellToLatLng returns the geographic centerpoint of a Cell.
func CellToLatLng(c Cell) (LatLng, error) {
var g C.LatLng
errC := C.cellToLatLng(C.H3Index(c), &g)
return latLngFromC(g), toErr(errC)
}
// LatLng returns the Cell at resolution for a geographic coordinate.
func (c Cell) LatLng() (LatLng, error) {
return CellToLatLng(c)
}
// CellToBoundary returns a CellBoundary of the Cell.
func CellToBoundary(c Cell) (CellBoundary, error) {
var cb C.CellBoundary
errC := C.cellToBoundary(C.H3Index(c), &cb)
return cellBndryFromC(&cb), toErr(errC)
}
// Boundary returns a CellBoundary of the Cell.
func (c Cell) Boundary() (CellBoundary, error) {
return CellToBoundary(c)
}
// GridDisk produces cells within grid distance k of the origin cell.
//
// k-ring 0 is defined as the origin cell, k-ring 1 is defined as k-ring 0 and
// all neighboring cells, and so on.
//
// Output is placed in an array in no particular order. Elements of the output
// array may be left zero, as can happen when crossing a pentagon.
func GridDisk(origin Cell, k int) ([]Cell, error) {
out := make([]C.H3Index, maxGridDiskSize(k))
errC := C.gridDisk(C.H3Index(origin), C.int(k), &out[0])
// QUESTION: should we prune zeroes from the output?
return cellsFromC(out, true, false), toErr(errC)
}
// GridDisk produces cells within grid distance k of the origin cell.
//
// k-ring 0 is defined as the origin cell, k-ring 1 is defined as k-ring 0 and
// all neighboring cells, and so on.
//
// Output is placed in an array in no particular order. Elements of the output
// array may be left zero, as can happen when crossing a pentagon.
func (c Cell) GridDisk(k int) ([]Cell, error) {
return GridDisk(c, k)
}
// GridDisksUnsafe produces cells within grid distance k of all provided origin
// cells.
//
// k-ring 0 is defined as the origin cell, k-ring 1 is defined as k-ring 0 and
// all neighboring cells, and so on.
//
// Outer slice is ordered in the same order origins were passed in. Inner slices
// are in no particular order.
func GridDisksUnsafe(origins []Cell, k int) ([][]Cell, error) {
if len(origins) == 0 {
return nil, nil
}
gridDiskSize := maxGridDiskSize(k)
flat := make([]C.H3Index, len(origins)*gridDiskSize)
cin := cellsToC(origins)
errC := C.gridDisksUnsafe(&cin[0], C.int(len(origins)), C.int(k), &flat[0])
if err := toErr(errC); err != nil {
return nil, err
}
out := make([][]Cell, len(origins))
for i := range origins {
out[i] = cellsFromC(flat[i*gridDiskSize:(i+1)*gridDiskSize], true, false)
}
return out, nil
}
// GridDiskDistances produces cells within grid distance k of the origin cell.
// This method optimistically tries the faster GridDiskDistancesUnsafe first.
// If a cell was a pentagon or was in the pentagon distortion area, it falls
// back to GridDiskDistancesSafe.
//
// k-ring 0 is defined as the origin cell, k-ring 1 is defined as k-ring 0 and
// all neighboring cells, and so on.
//
// Outer slice is ordered from origin outwards. Inner slices are in no
// particular order. Elements of the output array may be left zero, as can
// happen when crossing a pentagon.
func GridDiskDistances(origin Cell, k int) ([][]Cell, error) {
rsz := maxGridDiskSize(k)
outHexes := make([]C.H3Index, rsz)
outDists := make([]C.int, rsz)
if err := toErr(C.gridDiskDistances(C.H3Index(origin), C.int(k), &outHexes[0], &outDists[0])); err != nil {
return nil, err
}
ret := make([][]Cell, k+1)
for i := 0; i <= k; i++ {
ret[i] = make([]Cell, 0, ringSize(i))
}
for i, d := range outDists {
ret[d] = append(ret[d], Cell(outHexes[i]))
}
return ret, nil
}
// GridDiskDistances produces cells within grid distance k of the origin cell.
// This method optimistically tries the faster GridDiskDistancesUnsafe first.
// If a cell was a pentagon or was in the pentagon distortion area, it falls
// back to GridDiskDistancesSafe.
//
// k-ring 0 is defined as the origin cell, k-ring 1 is defined as k-ring 0 and
// all neighboring cells, and so on.
//
// Outer slice is ordered from origin outwards. Inner slices are in no
// particular order. Elements of the output array may be left zero, as can
// happen when crossing a pentagon.
func (c Cell) GridDiskDistances(k int) ([][]Cell, error) {
return GridDiskDistances(c, k)
}
// GridDiskDistancesUnsafe produces cells within grid distance k of the origin cell.
// Output behavior is undefined when one of the cells returned by this
// function is a pentagon or is in the pentagon distortion area.
//
// k-ring 0 is defined as the origin cell, k-ring 1 is defined as k-ring 0 and
// all neighboring cells, and so on.
//
// Outer slice is ordered from origin outwards. Inner slices are in no
// particular order. Elements of the output array may be left zero, as can
// happen when crossing a pentagon.
func GridDiskDistancesUnsafe(origin Cell, k int) ([][]Cell, error) {
rsz := maxGridDiskSize(k)
outHexes := make([]C.H3Index, rsz)
outDists := make([]C.int, rsz)
if err := toErr(C.gridDiskDistancesUnsafe(C.H3Index(origin), C.int(k), &outHexes[0], &outDists[0])); err != nil {
return nil, err
}
ret := make([][]Cell, k+1)
for i := 0; i <= k; i++ {
ret[i] = make([]Cell, 0, ringSize(i))
}
for i, d := range outDists {
ret[d] = append(ret[d], Cell(outHexes[i]))
}
return ret, nil
}
// GridDiskDistancesUnsafe produces cells within grid distance k of the origin cell.
// Output behavior is undefined when one of the cells returned by this
// function is a pentagon or is in the pentagon distortion area.
//
// k-ring 0 is defined as the origin cell, k-ring 1 is defined as k-ring 0 and
// all neighboring cells, and so on.
//
// Outer slice is ordered from origin outwards. Inner slices are in no
// particular order. Elements of the output array may be left zero, as can
// happen when crossing a pentagon.
func (c Cell) GridDiskDistancesUnsafe(k int) ([][]Cell, error) {
return GridDiskDistancesUnsafe(c, k)
}
// GridDiskDistancesSafe produces cells within grid distance k of the origin cell.
// This is the safe, but slow version of GridDiskDistances.
//
// k-ring 0 is defined as the origin cell, k-ring 1 is defined as k-ring 0 and
// all neighboring cells, and so on.
//
// Outer slice is ordered from origin outwards. Inner slices are in no
// particular order. Elements of the output array may be left zero, as can
// happen when crossing a pentagon.
func GridDiskDistancesSafe(origin Cell, k int) ([][]Cell, error) {
rsz := maxGridDiskSize(k)
outHexes := make([]C.H3Index, rsz)
outDists := make([]C.int, rsz)
if err := toErr(C.gridDiskDistancesSafe(C.H3Index(origin), C.int(k), &outHexes[0], &outDists[0])); err != nil {
return nil, err
}
ret := make([][]Cell, k+1)
for i := 0; i <= k; i++ {
ret[i] = make([]Cell, 0, ringSize(i))
}
for i, d := range outDists {
ret[d] = append(ret[d], Cell(outHexes[i]))
}
return ret, nil
}
// GridDiskDistancesSafe produces cells within grid distance k of the origin cell.
// This is the safe, but slow version of GridDiskDistances.
//
// k-ring 0 is defined as the origin cell, k-ring 1 is defined as k-ring 0 and
// all neighboring cells, and so on.
//
// Outer slice is ordered from origin outwards. Inner slices are in no
// particular order. Elements of the output array may be left zero, as can
// happen when crossing a pentagon.
func (c Cell) GridDiskDistancesSafe(k int) ([][]Cell, error) {
return GridDiskDistancesSafe(c, k)
}
// GridRing produces the "hollow" ring of cells at exactly grid distance k from the origin cell.
//
// k-ring 0 returns just the origin hexagon.
//
// Elements of the output array may be left zero, as can happen when crossing a pentagon.
func GridRing(origin Cell, k int) ([]Cell, error) {
if k < 0 {
return nil, ErrDomain
}
out := make([]C.H3Index, ringSize(k))
errC := C.gridRing(C.H3Index(origin), C.int(k), &out[0])
return cellsFromC(out, true, false), toErr(errC)
}
// GridRing produces the "hollow" ring of cells at exactly grid distance k from the origin cell.
//
// k-ring 0 returns just the origin hexagon.
//
// Elements of the output array may be left zero, as can happen when crossing a pentagon.
func (c Cell) GridRing(k int) ([]Cell, error) {
return GridRing(c, k)
}
// GridRingUnsafe produces the "hollow" ring of cells at exactly grid distance k from the origin cell.
//
// k-ring 0 returns just the origin hexagon.
func GridRingUnsafe(origin Cell, k int) ([]Cell, error) {
if k < 0 {
return nil, ErrDomain
}
out := make([]C.H3Index, ringSize(k))
errC := C.gridRingUnsafe(C.H3Index(origin), C.int(k), &out[0])
return cellsFromC(out, true, false), toErr(errC)
}
// GridRingUnsafe produces the "hollow" ring of cells at exactly grid distance k from the origin cell.
//
// k-ring 0 returns just the origin hexagon.
func (c Cell) GridRingUnsafe(k int) ([]Cell, error) {
return GridRingUnsafe(c, k)
}
// PolygonToCells takes a given GeoJSON-like data structure fills it with the
// hexagon cells that are contained by the GeoJSON-like data structure.
//
// This implementation traces the GeoJSON geoloop(s) in cartesian space with
// hexagons, tests them and their neighbors to be contained by the geoloop(s),
// and then any newly found hexagons are used to test again until no new
// hexagons are found.
func PolygonToCells(polygon GeoPolygon, resolution int) ([]Cell, error) {
if len(polygon.GeoLoop) == 0 {
return nil, nil
}
cpoly := allocCGeoPolygon(polygon)
defer freeCGeoPolygon(&cpoly)
maxLen := new(C.int64_t)
if err := toErr(C.maxPolygonToCellsSize(&cpoly, C.int(resolution), 0, maxLen)); err != nil {
return nil, err
}
out := make([]C.H3Index, *maxLen)
errC := C.polygonToCells(&cpoly, C.int(resolution), 0, &out[0])
return cellsFromC(out, true, false), toErr(errC)
}
// PolygonToCellsExperimental takes a given GeoJSON-like data structure fills it with the
// hexagon cells that are contained by the GeoJSON-like data structure.
//
// This implementation traces the GeoJSON geoloop(s) in cartesian space with
// hexagons, tests them and their neighbors to be contained by the geoloop(s),
// and then any newly found hexagons are used to test again until no new
// hexagons are found.
func PolygonToCellsExperimental(polygon GeoPolygon, resolution int, mode ContainmentMode, maxNumCellsReturn ...int64) ([]Cell, error) {
maxNumCells := int64(math.MaxInt64)
if len(maxNumCellsReturn) > 0 {
maxNumCells = maxNumCellsReturn[0]
}
if len(polygon.GeoLoop) == 0 {
return nil, nil
}
cpoly := allocCGeoPolygon(polygon)
defer freeCGeoPolygon(&cpoly)
maxLen := new(C.int64_t)
if err := toErr(C.maxPolygonToCellsSizeExperimental(&cpoly, C.int(resolution), C.uint32_t(mode), maxLen)); err != nil {
return nil, err
}
out := make([]C.H3Index, *maxLen)
errC := C.polygonToCellsExperimental(&cpoly, C.int(resolution), C.uint32_t(mode), C.int64_t(maxNumCells), &out[0])
return cellsFromC(out, true, false), toErr(errC)
}
// Cells takes a given GeoJSON-like data structure fills it with the
// hexagon cells that are contained by the GeoJSON-like data structure.
//
// This implementation traces the GeoJSON geoloop(s) in cartesian space with
// hexagons, tests them and their neighbors to be contained by the geoloop(s),
// and then any newly found hexagons are used to test again until no new
// hexagons are found.
func (p GeoPolygon) Cells(resolution int) ([]Cell, error) {
return PolygonToCells(p, resolution)
}
// CellsToMultiPolygon takes a set of cells and creates GeoPolygon(s)
// describing the outline(s) of a set of hexagons. Polygon outlines will follow
// GeoJSON MultiPolygon order: Each polygon will have one outer loop, which is first in
// the list, followed by any holes.
//
// It is expected that all hexagons in the set have the same resolution and that the set
// contains no duplicates. Behavior is undefined if duplicates or multiple resolutions are
// present, and the algorithm may produce unexpected or invalid output.
func CellsToMultiPolygon(cells []Cell) ([]GeoPolygon, error) {
if len(cells) == 0 {
return nil, nil
}
h3Indexes := cellsToC(cells)
cLinkedGeoPolygon := new(C.LinkedGeoPolygon)
if err := toErr(C.cellsToLinkedMultiPolygon(&h3Indexes[0], C.int(len(h3Indexes)), cLinkedGeoPolygon)); err != nil {
return nil, err
}
currPoly := cLinkedGeoPolygon
var countPoly int
for currPoly != nil {
countPoly++
currPoly = currPoly.next
}
ret := make([]GeoPolygon, countPoly)
// traverse polygons for linked list of polygons
currPoly = cLinkedGeoPolygon
countPoly = 0
for currPoly != nil {
currLoop := currPoly.first
var countLoop int
for currLoop != nil {
countLoop++
currLoop = currLoop.next
}
loops := make([]GeoLoop, countLoop)
// traverse loops for a polygon
currLoop = currPoly.first
countLoop = 0
for currLoop != nil {
currPt := currLoop.first
var countPt int
for currPt != nil {
countPt++
currPt = currPt.next
}
loop := make([]LatLng, countPt)
// traverse points for a loop
currPt = currLoop.first
countPt = 0
for currPt != nil {
loop[countPt] = latLngFromC(currPt.vertex)
countPt++
currPt = currPt.next
}
loops[countLoop] = loop
countLoop++
currLoop = currLoop.next
}
ret[countPoly] = GeoPolygon{GeoLoop: loops[0], Holes: loops[1:]}
countPoly++
currPoly = currPoly.next
}
C.destroyLinkedMultiPolygon(cLinkedGeoPolygon)
return ret, nil
}
// GreatCircleDistanceRads returns the "great circle" or "haversine" distance between
// pairs of LatLng points (lat/lng pairs) in radians.
func GreatCircleDistanceRads(a, b LatLng) float64 {
ca, cb := a.toC(), b.toC()
return float64(C.greatCircleDistanceRads(&ca, &cb))
}
// GreatCircleDistanceKm returns the "great circle" or "haversine" distance between pairs
// of LatLng points (lat/lng pairs) in kilometers.
func GreatCircleDistanceKm(a, b LatLng) float64 {
ca, cb := a.toC(), b.toC()
return float64(C.greatCircleDistanceKm(&ca, &cb))
}
// GreatCircleDistanceM returns the "great circle" or "haversine" distance between pairs
// of LatLng points (lat/lng pairs) in meters.
func GreatCircleDistanceM(a, b LatLng) float64 {
ca, cb := a.toC(), b.toC()
return float64(C.greatCircleDistanceM(&ca, &cb))
}
// HexagonAreaAvgKm2 returns the average hexagon area in square kilometers at the given
// resolution.
func HexagonAreaAvgKm2(resolution int) (float64, error) {
var out C.double
errC := C.getHexagonAreaAvgKm2(C.int(resolution), &out)
return float64(out), toErr(errC)
}
// HexagonAreaAvgM2 returns the average hexagon area in square meters at the given
// resolution.
func HexagonAreaAvgM2(resolution int) (float64, error) {
var out C.double
errC := C.getHexagonAreaAvgM2(C.int(resolution), &out)
return float64(out), toErr(errC)
}
// CellAreaRads2 returns the exact area of specific cell in square radians.
func CellAreaRads2(c Cell) (float64, error) {
var out C.double
errC := C.cellAreaRads2(C.H3Index(c), &out)
return float64(out), toErr(errC)
}
// CellAreaKm2 returns the exact area of specific cell in square kilometers.
func CellAreaKm2(c Cell) (float64, error) {
var out C.double
errC := C.cellAreaKm2(C.H3Index(c), &out)
return float64(out), toErr(errC)
}
// CellAreaM2 returns the exact area of specific cell in square meters.
func CellAreaM2(c Cell) (float64, error) {
var out C.double
errC := C.cellAreaM2(C.H3Index(c), &out)
return float64(out), toErr(errC)
}
// HexagonEdgeLengthAvgKm returns the average hexagon edge length in kilometers
// at the given resolution.
func HexagonEdgeLengthAvgKm(resolution int) (float64, error) {
var out C.double
errC := C.getHexagonEdgeLengthAvgKm(C.int(resolution), &out)
return float64(out), toErr(errC)
}
// HexagonEdgeLengthAvgM returns the average hexagon edge length in meters at
// the given resolution.
func HexagonEdgeLengthAvgM(resolution int) (float64, error) {
var out C.double
errC := C.getHexagonEdgeLengthAvgM(C.int(resolution), &out)
return float64(out), toErr(errC)
}
// EdgeLengthRads returns the exact edge length of specific unidirectional edge
// in radians.
func EdgeLengthRads(e DirectedEdge) (float64, error) {
var out C.double
errC := C.edgeLengthRads(C.H3Index(e), &out)
return float64(out), toErr(errC)
}
// EdgeLengthKm returns the exact edge length of specific unidirectional
// edge in kilometers.
func EdgeLengthKm(e DirectedEdge) (float64, error) {
var out C.double
errC := C.edgeLengthKm(C.H3Index(e), &out)
return float64(out), toErr(errC)
}
// EdgeLengthM returns the exact edge length of specific unidirectional
// edge in meters.
func EdgeLengthM(e DirectedEdge) (float64, error) {
var out C.double
errC := C.edgeLengthM(C.H3Index(e), &out)
return float64(out), toErr(errC)
}
// NumCells returns the number of cells at the given resolution.
func NumCells(resolution int) int {
// NOTE: this is a mathematical operation, no need to call into H3 library.
// See h3api.h for formula derivation.
return 2 + 120*pow7[resolution] //nolint:mnd // math formula
}
// Res0Cells returns all the cells at resolution 0.
func Res0Cells() ([]Cell, error) {
out := make([]C.H3Index, C.res0CellCount())
errC := C.getRes0Cells(&out[0])
return cellsFromC(out, false, false), toErr(errC)
}
// Pentagons returns all the pentagons at resolution.
func Pentagons(resolution int) ([]Cell, error) {
out := make([]C.H3Index, NumPentagons)
errC := C.getPentagons(C.int(resolution), &out[0])
return cellsFromC(out, false, false), toErr(errC)
}
// Resolution returns the resolution of the cell.
func (c Cell) Resolution() int {
return resolution(c)
}
// Resolution returns the resolution of the edge.
func (e DirectedEdge) Resolution() int {
return resolution(e)
}
// Resolution returns the resolution of the vertex.
func (v Vertex) Resolution() int {
return resolution(v)
}
// BaseCellNumber returns the integer ID (0-121) of the base cell the H3Index h
// belongs to.
func BaseCellNumber(h Cell) int {
return int(C.getBaseCellNumber(C.H3Index(h)))
}
// BaseCellNumber returns the integer ID (0-121) of the base cell the H3Index h
// belongs to.
func (c Cell) BaseCellNumber() int {
return BaseCellNumber(c)
}
// IndexFromString returns an uint64 from a string. Should call c.IsValid() to check
// if the Cell is valid before using it.
func IndexFromString(s string) uint64 {
if len(s) > 2 && strings.ToLower(s[:2]) == "0x" {
s = s[2:]
}
c, _ := strconv.ParseUint(s, base16, bitSize)
return c
}
// IndexToString returns a string from a Cell.
func IndexToString(i uint64) string {
return strconv.FormatUint(i, base16)
}
// CellFromString returns a Cell from a string. Should call c.IsValid() to check
// if the Cell is valid before using it.
func CellFromString(s string) Cell {
return Cell(IndexFromString(s))
}
// CellToString returns a string from a Cell.
func CellToString(c Cell) string {
return IndexToString(uint64(c))
}
// VertexFromString returns a Vertex from a string. Should call v.IsValid() to check
// if the Vertex is valid before using it.
func VertexFromString(s string) Vertex {
return Vertex(IndexFromString(s))
}
// DirectedEdgeFromString returns a DirectedEdge from a string. Should call e.IsValid() to check
// if the DirectedEdge is valid before using it.
func DirectedEdgeFromString(s string) DirectedEdge {
return DirectedEdge(IndexFromString(s))
}
// String returns the string representation of the H3Index h.
func (c Cell) String() string {
return indexToString(c)
}
// MarshalText implements the encoding.TextMarshaler interface.
func (c Cell) MarshalText() ([]byte, error) {
return marshalText(c)
}
// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (c *Cell) UnmarshalText(text []byte) error {
*c = CellFromString(string(text))
if !c.IsValid() {
return errors.New("invalid cell index")
}
return nil
}
// IsValid returns if a Cell is a valid cell (hexagon or pentagon).
func (c Cell) IsValid() bool {
return c != 0 && C.isValidCell(C.H3Index(c)) == 1
}
// Parent returns the parent or grandparent Cell of this Cell.
func (c Cell) Parent(resolution int) (Cell, error) {
var out C.H3Index
errC := C.cellToParent(C.H3Index(c), C.int(resolution), &out)
return Cell(out), toErr(errC)
}
// ImmediateParent returns the immediate parent of the cell.
func (c Cell) ImmediateParent() (Cell, error) {
return c.Parent(c.Resolution() - 1)
}
// Children returns the children or grandchildren cells of this Cell.
func (c Cell) Children(resolution int) ([]Cell, error) {
var outsz C.int64_t
if err := toErr(C.cellToChildrenSize(C.H3Index(c), C.int(resolution), &outsz)); err != nil {
return nil, err
}
out := make([]C.H3Index, outsz)
// Seems like this function always returns E_SUCCESS.
errC := C.cellToChildren(C.H3Index(c), C.int(resolution), &out[0])
return cellsFromC(out, false, false), toErr(errC)
}
// ImmediateChildren returns the children or grandchildren cells of this Cell.
func (c Cell) ImmediateChildren() ([]Cell, error) {
return c.Children(c.Resolution() + 1)
}
// CenterChild returns the center child Cell of this Cell.
func (c Cell) CenterChild(resolution int) (Cell, error) {
var out C.H3Index
errC := C.cellToCenterChild(C.H3Index(c), C.int(resolution), &out)
return Cell(out), toErr(errC)
}
// IsResClassIII returns true if this is a class III index. If false, this is a
// class II index.
func (c Cell) IsResClassIII() bool {
return C.isResClassIII(C.H3Index(c)) == 1
}
// IsPentagon returns true if this is a pentagon.
func (c Cell) IsPentagon() bool {
return C.isPentagon(C.H3Index(c)) == 1
}
// IcosahedronFaces finds all icosahedron faces (0-19) intersected by this Cell.
func (c Cell) IcosahedronFaces() ([]int, error) {
var outsz C.int
// Seems like this function always returns E_SUCCESS.
C.maxFaceCount(C.H3Index(c), &outsz)
out := make([]C.int, outsz)
errC := C.getIcosahedronFaces(C.H3Index(c), &out[0])
return intsFromC(out), toErr(errC)
}
// IsNeighbor returns true if this Cell is a neighbor of the other Cell.
func (c Cell) IsNeighbor(other Cell) (bool, error) {
var out C.int
errC := C.areNeighborCells(C.H3Index(c), C.H3Index(other), &out)
return out == 1, toErr(errC)
}
// IndexDigit returns an [indexing digit] of the cell.
//
// [indexing digit]: https://h3geo.org/docs/library/index/cell
func (c Cell) IndexDigit(resolution int) (int, error) {
return indexDigit(c, resolution)
}
// DirectedEdge returns a DirectedEdge from this Cell to other.
func (c Cell) DirectedEdge(other Cell) (DirectedEdge, error) {
var out C.H3Index
errC := C.cellsToDirectedEdge(C.H3Index(c), C.H3Index(other), &out)
return DirectedEdge(out), toErr(errC)
}
// DirectedEdges returns 6 directed edges with h as the origin.
func (c Cell) DirectedEdges() ([]DirectedEdge, error) {
out := make([]C.H3Index, numCellEdges) // always 6 directed edges
// Seems like this function always returns E_SUCCESS.
errC := C.originToDirectedEdges(C.H3Index(c), &out[0])
return edgesFromC(out), toErr(errC)
}
// IsValid determines if the directed edge is valid.
func (e DirectedEdge) IsValid() bool {
return C.isValidDirectedEdge(C.H3Index(e)) == 1
}
// Origin returns the origin cell of this directed edge.
func (e DirectedEdge) Origin() (Cell, error) {
var out C.H3Index
errC := C.getDirectedEdgeOrigin(C.H3Index(e), &out)
return Cell(out), toErr(errC)
}
// Destination returns the destination cell of this directed edge.
func (e DirectedEdge) Destination() (Cell, error) {
var out C.H3Index
errC := C.getDirectedEdgeDestination(C.H3Index(e), &out)
return Cell(out), toErr(errC)
}
// Cells returns the origin and destination cells in that order.
func (e DirectedEdge) Cells() ([]Cell, error) {
out := make([]C.H3Index, numEdgeCells)
if err := toErr(C.directedEdgeToCells(C.H3Index(e), &out[0])); err != nil {
return nil, err
}
return cellsFromC(out, false, false), nil
}