Skip to content

Instantly share code, notes, and snippets.

@cdlhub
Created Dec 28, 2017
Embed
What would you like to do?
Sample code for URL signing to query Google Maps API
// See: https://developers.google.com/maps/documentation/static-maps/get-api-key
//
// WARNING: Unfinised work...
package main
// const (
// gmapsHost = "https://maps.googleapis.com"
// gmapsURL = "/maps/api/geocode/json"
// )
type Geocoder struct {
clientID string
apiKey string
Channel string
}
func NewGeocoder(id string, key string) Geocoder {
return Geocoder{clientID: id, apiKey: key}
}
func (Geocoder) SendQuery(clientID string, apiKey string, address string) (err error) {
c, err := maps.NewClient(maps.ClID WithAPIKey("Insert-API-Key-Here"))
}
func (coder Geocoder) encodeURL(address string) string {
u, err := url.Parse(gmapsHost)
if err != nil {
panic("url module cannot parse https://maps.googleapis.com")
}
u.Path += gmapsURL
params := url.Values{}
params.Add("address", address)
params.Add("client", coder.clientID)
params.Add("channel", coder.channel)
u.RawQuery = params.Encode()
return u.Path + "?" + u.RawQuery
}
// str: u.Path + "?" + u.RawQuery
func (coder Geocoder) signURL(u string) (sig string) {
key, err := base64.URLEncoding.DecodeString(coder.apiKey)
if err != nil {
panic("base64 module cannot encode API key")
}
h := hmac.New(sha1.New, key)
h.Write([]byte(u))
sig = base64.URLEncoding.EncodeToString(h.Sum(nil))
return sig
}
func queryURL(u *url.URL, sig string) {
params := u.Query()
params.Add("signature", sig)
u.RawQuery += "&signature=" + sig
}
func (coder Geocoder) Request(address string) {
u := coder.encodeURL(address)
fmt.Printf("url: %s\n", u)
sig := coder.signURL(u)
fmt.Printf("sig: %s\n", sig)
urlStr := gmapsHost + u + "&signature=" + sig
fmt.Println(urlStr)
client, _ := maps.NewClient(
maps.WithClientIDAndSignature(coder.clientID, coder.apiKey),
// maps.WithClientIDAndSignature(coder.clientID, sig),
maps.WithChannel(coder.channel),
)
r := &maps.GeocodingRequest{
Address: address,
}
resp, err := client.Geocode(context.Background(), r)
if err != nil {
log.Fatalln(err)
}
pretty.Println(resp[0].Geometry.Location.Lat)
pretty.Println(resp[0].Geometry.Location.Lng)
// pretty.Println(resp)
// if err != nil {
// log.Fatalf("fatal error: %s", err)
// }
// r := &maps.DirectionsRequest{
// Origin: "Sydney",
// Destination: "Perth",
// }
// route, _, err := c.Directions(context.Background(), r)
// if err != nil {
// log.Fatalf("fatal error: %s", err)
// }
// pretty.Println(route)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment