회사에서 프로젝트 진행중 gps 정보를 주소가 찍히게끔 변경해달라는 요구를 받았다.
그래서 알아보았다.
우선 google에 접속하여 api key를 발급받고 사용하고자 하는 api를 등록해야 한다.
https://cloud.google.com/maps-platform/
Google Maps Platform - Location and Mapping Solutions
Create real world and real time experiences for your customers with dynamic maps, routes & places APIs from Google Maps Platform’s location solutions.
mapsplatform.google.com
위의 주소에서

좌측 상단의 프로젝트 선택 > 새 프로젝트

API 및 서비스 > 라이브러리

검색 창에 geocode 입력 후 검색

이후 geocoding API 를 클릭해서 '사용' 버튼을 누르시면 됩니다.
위의 과정이 완료되면

사용자 인증 정보에 들어가서

사용자 인증 정보 만들기 > API 키 클릭 후 API 키를 생성하여 발급받으시면 됩니다.
이후 실제 사용 방법을 알려드리겠습니다.
<%@ page import="addr_api.*" %> <% double latitude = 37.48096906347303; double longitude = 127.01033847341384; GpsToAddress gps = new GpsToAddress(latitude, longitude); System.out.println(gps.getAddress()); %> <!-- test.jsp 위의 좌표값은 서초 예술의 전당 gps 위도 경도입니다. -->
package addr_api; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; public class GpsToAddress { double latitude; double longitude; String regionAddress; public GpsToAddress(double latitude, double longitude) throws Exception { this.latitude = latitude; this.longitude = longitude; this.regionAddress = getRegionAddress(getJSONData(getApiAddress())); } private String getApiAddress() { String apiURL = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "&language=ko&key=YOUR_KEY"; return apiURL; } private String getJSONData(String apiURL) throws Exception { String jsonString = new String(); String buf; URL url = new URL(apiURL); URLConnection conn = url.openConnection(); BufferedReader br = new BufferedReader(new InputStreamReader( conn.getInputStream(), "UTF-8")); while ((buf = br.readLine()) != null) { jsonString += buf; } return jsonString; } private String getRegionAddress(String jsonString) { JSONObject jObj = (JSONObject) JSONValue.parse(jsonString); JSONArray jArray = (JSONArray) jObj.get("results"); jObj = (JSONObject) jArray.get(0); return (String) jObj.get("formatted_address"); } public String getAddress() { return regionAddress; } }
jsp에서 GpsToAddress를 호출하여 사용하였습니다.
test.jsp 에서 System.out.println(gps.getAddress()); 해서 나온 결과 값은
대한민국 서울특별시 서초구 서초3동 1471-16 입니다.
'Language > Java' 카테고리의 다른 글
[JAVA] HashMap 사용 (0) | 2022.08.03 |
---|---|
[JAVA] 배열에서 일치하는 문자열 찾기 (0) | 2022.07.21 |
[JAVA] 날짜 계산 (날짜 더하기, 날짜 빼기) (0) | 2022.07.15 |
[JAVA] Int to String, String to Int 형 변환 (0) | 2022.07.01 |
[JAVA] 에러 String index out of range (0) | 2022.05.31 |
댓글