Skip to content

Commit

Permalink
feat: getLatLng
Browse files Browse the repository at this point in the history
  • Loading branch information
nanami69 committed Apr 25, 2023
1 parent 9554212 commit 8410553
Showing 1 changed file with 57 additions and 1 deletion.
58 changes: 57 additions & 1 deletion backend/main.go
@@ -1,7 +1,10 @@
package main

import (
"encoding/json"
"net/http"
"net/url"
"fmt"

"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
Expand All @@ -26,11 +29,64 @@ func getUser(c echo.Context) error {

func registerCinema(c echo.Context) error {
// データベースの登録と緯度経度算出処理
var req struct {
Address string `json:"address"`
}
if err := c.Bind(&req); err != nil {
return err
}

lat, lng, err := getLatLng(req.Address)
if err != nil {
return err
}

return c.JSON(http.StatusOK, map[string]string{
"message": "test",
"lat": lat,
"lng": lng,
})
}

func getLatLng(address string) (string, string, error) {
// APIに送信するリクエストを作成
apiURL := "https://msearch.gsi.go.jp/address-search/AddressSearch?q=" + url.QueryEscape(address)
// values := make(url.Values)
// values.Set("q", address)
req, err := http.NewRequest("GET", apiURL, nil)
if err != nil {
return "", "", err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

// リクエストを送信
client := new(http.Client)
resp, err := client.Do(req)
if err != nil {
return "", "", err
}
defer resp.Body.Close()

// レスポンスをパース
var res []struct {
Geometry struct {
Coordinates []float64 `json:"coordinates"`
} `json:"geometry"`
}
err = json.NewDecoder(resp.Body).Decode(&res)
if err != nil {
return "", "", err
}

// レスポンスから緯度経度を取得
if len(res) == 0 {
return "", "", fmt.Errorf("no result")
}
longitude := fmt.Sprintf("%f", res[0].Geometry.Coordinates[0])
latitude := fmt.Sprintf("%f", res[0].Geometry.Coordinates[1])

return latitude, longitude, nil
}

func main() {
e := echo.New()

Expand Down

0 comments on commit 8410553

Please sign in to comment.