Skip to content

Commit e3be6fa

Browse files
mologiesams96
authored andcommitted
Make ReverseGeocode thread-safe
The query object is cheap to create but internally uses iterators which are not thread-safe. Create a new one with for every lookup.
1 parent 0db6cf0 commit e3be6fa

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

rgeo.go

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,6 @@ type Location struct {
8181
type Rgeo struct {
8282
index *s2.ShapeIndex
8383
locs map[s2.Shape]Location
84-
query *s2.ContainsPointQuery
8584
}
8685

8786
// Go generate commands to regenerate the included datasets, this assumes you
@@ -146,18 +145,24 @@ func New(datasets ...func() []byte) (*Rgeo, error) {
146145
ret.locs[p] = getLocationStrings(c.Properties)
147146
}
148147

149-
ret.query = s2.NewContainsPointQuery(ret.index, s2.VertexModelOpen)
150-
151148
return ret, nil
152149
}
153150

151+
// Build builds the underlying shape index. This ensures that future calls to
152+
// ReverseGeocode will be fast. If Build is not called, then the first lookup
153+
// will build the index implicitly and experience a 1s+ delay.
154+
func (r *Rgeo) Build() {
155+
r.index.Build()
156+
}
157+
154158
// ReverseGeocode returns the country in which the given coordinate is located.
155159
//
156160
// The input is a geom.Coord, which is just a []float64 with the longitude
157161
// in the zeroth position and the latitude in the first position
158162
// (i.e. []float64{lon, lat}).
159163
func (r *Rgeo) ReverseGeocode(loc geom.Coord) (Location, error) {
160-
res := r.query.ContainingShapes(pointFromCoord(loc))
164+
query := s2.NewContainsPointQuery(r.index, s2.VertexModelOpen)
165+
res := query.ContainingShapes(pointFromCoord(loc))
161166
if len(res) == 0 {
162167
return Location{}, ErrLocationNotFound
163168
}

0 commit comments

Comments
 (0)