72 lines
1.4 KiB
Go
72 lines
1.4 KiB
Go
package cmd
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
|
|
"golang.org/x/time/rate"
|
|
"googlemaps.github.io/maps"
|
|
)
|
|
|
|
func Run(ctx context.Context) error {
|
|
rps := 2
|
|
limit := 100
|
|
|
|
limiter := rate.NewLimiter(rate.Limit(rps), 1)
|
|
|
|
c, err := maps.NewClient(maps.WithAPIKey(os.Getenv("GOOGLE_PLACES_API_KEY")))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
resp, err := c.TextSearch(ctx, &maps.TextSearchRequest{
|
|
Query: os.Args[1],
|
|
Location: nil,
|
|
Radius: uint(0),
|
|
})
|
|
if err != nil {
|
|
return err
|
|
} else if len(resp.Results) < 1 {
|
|
return fmt.Errorf("no results for %q", os.Args[1])
|
|
}
|
|
origin := resp.Results[0].Geometry.Location
|
|
|
|
type Result struct {
|
|
Name string
|
|
Lat float64
|
|
Lng float64
|
|
Address string
|
|
}
|
|
results := []Result{}
|
|
var nextToken string
|
|
for len(results) < limit {
|
|
limiter.Wait(ctx)
|
|
resp, err := c.TextSearch(ctx, &maps.TextSearchRequest{
|
|
Query: os.Args[2],
|
|
Location: &origin,
|
|
Radius: uint(50),
|
|
PageToken: nextToken,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
nextToken = resp.NextPageToken
|
|
for _, result := range resp.Results {
|
|
results = append(results, Result{
|
|
Name: result.Name,
|
|
Lat: result.Geometry.Location.Lat,
|
|
Lng: result.Geometry.Location.Lng,
|
|
Address: result.FormattedAddress,
|
|
})
|
|
}
|
|
log.Printf("%d...", len(resp.Results))
|
|
}
|
|
b, _ := json.Marshal(results)
|
|
fmt.Printf("%s\n", b)
|
|
|
|
return ctx.Err()
|
|
}
|