github.com/jimpick/sp-kyc-checks@v0.0.0-20230201194251-fa84fca72da8/checks/geoip/google_geocode.go (about)

     1  package geoip
     2  
     3  import (
     4  	"context"
     5  	"log"
     6  	"os"
     7  
     8  	"github.com/jftuga/geodist"
     9  	"googlemaps.github.io/maps"
    10  )
    11  
    12  func getGeocodeClient() (*maps.Client, error) {
    13  	key := os.Getenv("GOOGLE_MAPS_API_KEY")
    14  	if key == "" {
    15  		log.Fatalf("Missing GOOGLE_MAPS_API_KEY")
    16  	}
    17  	if key == "skip" {
    18  		log.Println("Warning: GOOGLE_MAPS_API_KEY set to 'skip'")
    19  		return nil, nil
    20  	}
    21  	return maps.NewClient(maps.WithAPIKey(key))
    22  }
    23  
    24  func geocodeAddress(ctx context.Context, client *maps.Client,
    25  	address string) ([]geodist.Coord, []maps.GeocodingResult, error) {
    26  	if client == nil {
    27  		return []geodist.Coord{}, []maps.GeocodingResult{}, nil
    28  	}
    29  
    30  	r := &maps.GeocodingRequest{
    31  		Address: address,
    32  	}
    33  	resp, err := client.Geocode(ctx, r)
    34  	if err != nil {
    35  		return []geodist.Coord{}, resp, err
    36  	}
    37  
    38  	var locations []geodist.Coord
    39  	for _, r := range resp {
    40  		location := geodist.Coord{
    41  			Lat: r.Geometry.Location.Lat,
    42  			Lon: r.Geometry.Location.Lng,
    43  		}
    44  		locations = append(locations, location)
    45  	}
    46  
    47  	return locations, resp, nil
    48  }