Add endpoint for fetching address from coordinates

This commit is contained in:
2019-03-02 11:43:58 +01:00
parent 4ccc2fc98e
commit 141db083a8
+32 -1
View File
@@ -8,6 +8,7 @@ import (
"googlemaps.github.io/maps"
"log"
"net/http"
"strconv"
"strings"
)
@@ -21,6 +22,10 @@ type location struct {
Long float64 `json:"longitude"`
}
type address struct {
Address string `json:"address"`
}
type distance struct {
Text string `json:"text"`
Value int `json:"value"`
@@ -60,6 +65,7 @@ func main() {
}
http.HandleFunc("/latlong/", makeHandler(handleLatLongRequest, client))
http.HandleFunc("/address/", makeHandler(handleAddressRequest, client))
http.HandleFunc("/distance/", makeHandler(handleDistanceMatrixRequest, client))
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", cfg.Port), nil))
}
@@ -82,7 +88,7 @@ func handleDistanceMatrixRequest(w http.ResponseWriter, r *http.Request, client
}
if result, err := client.DistanceMatrix(context.Background(), req); err != nil {
log.Fatalf("fatal error: %s", err)
log.Fatalf("matrix fatal error: %s", err)
w.WriteHeader(400)
} else {
res := distanceResponse{}
@@ -114,6 +120,31 @@ func handleDistanceMatrixRequest(w http.ResponseWriter, r *http.Request, client
}
}
func handleAddressRequest(w http.ResponseWriter, r *http.Request, client *maps.Client) {
p := strings.Split(r.URL.Path[len("/address/"):], ",")
lat, _ := strconv.ParseFloat(p[0], 64)
lng, _ := strconv.ParseFloat(p[1], 64)
req := &maps.GeocodingRequest{
LatLng: &maps.LatLng{Lat: lat, Lng: lng},
}
if result, err := client.Geocode(context.Background(), req); err != nil {
log.Fatalf("fatal error: %s", err)
w.WriteHeader(400)
} else {
if len(result) > 0 {
l := address{
Address: result[0].FormattedAddress,
}
if response, err := json.Marshal(l); err != nil {
log.Fatalf("fatal error: %s", err)
w.WriteHeader(404)
} else {
_, _ = w.Write(response)
}
}
}
}
func handleLatLongRequest(w http.ResponseWriter, r *http.Request, client *maps.Client) {
req := &maps.GeocodingRequest{
Address: r.URL.Path[len("/latlong/"):],