Skip to content

Instantly share code, notes, and snippets.

@cgansen
Last active December 26, 2015 04:39
Show Gist options
  • Save cgansen/7095145 to your computer and use it in GitHub Desktop.
Save cgansen/7095145 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strconv"
"time"
)
type School struct {
Name string
Address string
Lat float64
Lon float64
}
var gmaps = "http://maps.googleapis.com/maps/api/geocode/json"
func main() {
f, err := os.Open("./data.csv")
if err != nil {
log.Fatalf("%s", err)
}
defer f.Close()
o, err := os.Create("./output.csv")
if err != nil {
log.Fatalf("%s", err)
}
defer o.Close()
reader := csv.NewReader(f)
records, err := reader.ReadAll()
if err != nil {
log.Fatalf("error loading csv: %s", err)
}
var schools []School
for _, item := range records {
s := School{Name: item[0], Address: item[1]}
url := gmaps + "?address=" + url.QueryEscape(s.Address) + "&sensor=false"
// log.Printf("%s", url)
resp, err := http.Get(url)
if err != nil {
log.Fatalf("gmaps error: %s", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalf("resp read error: %s", err)
}
var jsn map[string]interface{}
if err := json.Unmarshal(body, &jsn); err != nil {
log.Fatalf("json unmarshal error: %s", err)
}
if jsn["status"].(string) != "OK" {
break
}
s.Lat = jsn["results"].([]interface{})[0].(map[string]interface{})["geometry"].(map[string]interface{})["location"].(map[string]interface{})["lat"].(float64)
s.Lon = jsn["results"].([]interface{})[0].(map[string]interface{})["geometry"].(map[string]interface{})["location"].(map[string]interface{})["lng"].(float64)
schools = append(schools, s)
// 0.5 sec delay in querying google
time.Sleep(500 * time.Millisecond)
fmt.Printf("%#v\n", s)
}
writer := csv.NewWriter(o)
for _, s := range schools {
writer.Write([]string{s.Name,
s.Address,
strconv.FormatFloat(s.Lat, 'f', -1, 64),
strconv.FormatFloat(s.Lon, 'f', -1, 64),
})
}
writer.Flush()
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment