From 10b3de6068da1650401b6afbf02d106d558da66f Mon Sep 17 00:00:00 2001 From: Lucas Date: Mon, 15 Apr 2024 14:15:58 +0200 Subject: [PATCH] Implement OpenStreetMap API call to retrieve the GPS location of any adress --- .../u_paris/gla/project/utils/ApiUtils.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/main/java/fr/u_paris/gla/project/utils/ApiUtils.java diff --git a/src/main/java/fr/u_paris/gla/project/utils/ApiUtils.java b/src/main/java/fr/u_paris/gla/project/utils/ApiUtils.java new file mode 100644 index 0000000..3a40845 --- /dev/null +++ b/src/main/java/fr/u_paris/gla/project/utils/ApiUtils.java @@ -0,0 +1,54 @@ +package fr.u_paris.gla.project.utils; + +import fr.u_paris.gla.project.idfm.IDFMNetworkExtractor; +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class ApiUtils { + /** The logger for information on the process */ + private static final Logger LOGGER = Logger + .getLogger(IDFMNetworkExtractor.class.getName()); + + // OpenStreetMap API URL + private static final String OSM_URL = "https://nominatim.openstreetmap.org/search"; + + public static double[] getGPSLocation(String term) { + try { + String urlString = String.format("%s?q=%s&format=json", OSM_URL, URLEncoder.encode(term, StandardCharsets.UTF_8)); + HttpURLConnection connection = (HttpURLConnection) new URL(urlString).openConnection(); + + connection.setRequestMethod("GET"); + + BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String inputLine; + StringBuilder response = new StringBuilder(); + + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + + JSONArray jsonArray = new JSONArray(response.toString()); + + if (!jsonArray.isEmpty()) { + JSONObject firstResult = jsonArray.getJSONObject(0); + + double lat = firstResult.getDouble("lat"); + double lon = firstResult.getDouble("lon"); + return new double[]{lat, lon}; + } + } + catch (IOException e) { + LOGGER.log(Level.SEVERE, e, + () -> "Error accessing the API"); + } + return new double[]{0, 0}; + } +}