카카오맵 restapi 를 활용한 위도 경도 구하기 > IT 기술백서

IT 기술백서

직접 알아내거나 검색하기 귀찮아서 모아 둔 것

Go lang | 카카오맵 restapi 를 활용한 위도 경도 구하기

본문

카카오API를 이용해 위도(latitude) 경도(longitude) 구하기

 

.env

[code]

# 카카오 API

KAKAO_API_URL=https://dapi.kakao.com/v2/local/search/address.json?query=

KAKAO_API_KEY=카카오restapi키

[/code]

 


[code]

func GetLatLng(address string) (map[string]string, error) {

  url := fmt.Sprintf("%s%s", os.Getenv("KAKAO_API_URL"), url.QueryEscape(address))

  apikey := os.Getenv("KAKAO_API_KEY")

  req, _ := http.NewRequest("GET", url, nil)


  req.Header.Add("Authorization", fmt.Sprintf("KakaoAK %s", apikey))

  client := &http.Client{}

  resp, err := client.Do(req)

  if err != nil {

    return nil, err

  }

  defer resp.Body.Close()


  if resp.StatusCode != 200 {

    return nil, errors.New(resp.Status)

  }


  bytes, _ := ioutil.ReadAll(resp.Body)


  var result map[string]interface{}

  json.Unmarshal(bytes, &result)


  errMsg, _ := result["message"]

  if errMsg != nil {

    msg := result["message"].(string)

    return nil, errors.New(msg)

  }


  documents := result["documents"].([]interface{})

  if len(documents) <= 0 {

    return nil, errors.New("No Content")

  }

  mapdoc := documents[0].(map[string]interface{})

  x := mapdoc["x"].(string)

  y := mapdoc["y"].(string)


  return map[string]string{

    "lat": x,

    "lng": y,

  }, nil

}


func main() {

  _ = godotenv.Load()

  latlng, err := GetLatLng("판교역로 230")

  if err != nil {

    fmt.Println(err.Error())

    return

  }

  fmt.Printf("Lat: %s\n", latlng["lat"])

  fmt.Printf("Lng: %s\n", latlng["lng"])

}

[/code]

 

결과

[code]

 

 

Lat: 127.11045570879

Lng: 37.4012850380545

[/code]

댓글 0개

등록된 댓글이 없습니다.

Menu