#37 java: kakao map api

This commit is contained in:
haerong22
2023-05-25 21:33:59 +09:00
parent 1b4d16c421
commit 34a783b0be
3 changed files with 83 additions and 0 deletions

View File

@@ -21,6 +21,9 @@ dependencies {
implementation 'com.itextpdf:itext7-core:8.0.0'
implementation 'com.squareup.okhttp3:okhttp:4.11.0'
implementation 'org.apache.httpcomponents:httpclient:4.5.14'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}

View File

@@ -0,0 +1,49 @@
package kr.kakao.map;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URLEncoder;
public class KakaoApi {
private static String API_KEY = "";
private static final String API_BASE_URL = "https://dapi.kakao.com/v2/local/search/address.json";
private static final Gson gson = new Gson();
public static double[] getAddressCoordinate(String address) throws IOException {
String encodedAddress = URLEncoder.encode(address, "UTF-8");
String requestUrl = API_BASE_URL + "?query=" + encodedAddress;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(requestUrl);
httpGet.setHeader("Authorization", "KakaoAK " + API_KEY);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
String responseBody = EntityUtils.toString(response.getEntity());
JsonObject jsonObject = gson.fromJson(responseBody, JsonObject.class);
JsonArray documents = jsonObject.getAsJsonArray("documents");
if (documents.size() > 0) {
JsonObject document = documents.get(0).getAsJsonObject();
double latitude = document.get("y").getAsDouble();
double longitude = document.get("x").getAsDouble();
return new double[]{latitude, longitude};
} else {
return null;
}
}
}
public static void setApiKey(String apiKey) {
API_KEY = apiKey;
}
}

View File

@@ -0,0 +1,31 @@
package kr.kakao.map;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class KakaoMapMain {
public static void main(String[] args) {
final String apiKey = args[0];
KakaoApi.setApiKey(apiKey);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("주소를 입력하세요: ");
String address = reader.readLine();
double[] coordinate = KakaoApi.getAddressCoordinate(address);
if (coordinate != null) {
System.out.println("주소: " + address);
System.out.println("위도: " + coordinate[0]);
System.out.println("경도: " + coordinate[1]);
} else {
System.out.println("주소를 찾을 수 없습니다.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}