Merge branch 'openstreetmap-gps' into 'idf-mobilite-net'

[feat] Implement OpenStreetMap API calls

See merge request gla-groupe-3/projet!9
This commit is contained in:
RODRIGUEZ lucas 2024-04-15 14:28:42 +02:00
commit 5d2214ac23

View file

@ -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};
}
}