{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "(wheterAPI)=\n", "# Geoposición y Clima\n", "\n", "En este ejemplo se utilizan dos APIs: \n", "- [Geocoding API](https://openweathermap.org/api/geocoding-api): Dado el nombre de una ciudad retorna la latitud y longitud.\n", "- [Free Weather API](https://open-meteo.com/): Dada una latitud y longitud retorna el estado del clima (hora loca, temperatura actual, descripción del clima, etc).\n", "\n", "Código fuente Weather.java.\n", "\n", "## Dependencias de Maven" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "%%loadFromPOM\n", "\n", "\n", " org.json\n", " json\n", " 20240303\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Código de Java" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// Tomado y adaptado de: https://www.youtube.com/watch?v=WS_H44tvZMI\n", "import org.json.JSONArray;\n", "import org.json.JSONObject;\n", "import org.json.JSONTokener;\n", "\n", "import java.io.IOException;\n", "import java.math.BigDecimal;\n", "import java.net.HttpURLConnection;\n", "import java.net.URI;\n", "import java.net.URL;\n", "import java.util.Scanner;\n", "\n", "public class WeatherAPIData {\n", " public static void main(String[] args) {\n", " try{\n", " for(String city: args){\n", " System.out.print(\"City Entered: %s\\n\".formatted(city));\n", "\n", " BigDecimal[] coordenadas = getLocationData(city);\n", " displayWeatherData(coordenadas);\n", " //System.out.println(\"\");\n", " } \n", "\n", " }catch(Exception e){\n", " e.printStackTrace();\n", " }\n", " }\n", "\n", " private static BigDecimal[] getLocationData(String city){\n", " city = city.replaceAll(\" \", \"+\");\n", " String urlString = \"https://geocoding-api.open-meteo.com/v1/search?name=\" +\n", " city + \"&count=1&language=en&format=json\";\n", " \n", " try{\n", " // 1. Fetch the API response based on API Link\n", " HttpURLConnection apiConnection = fetchApiResponse(urlString);\n", "\n", " // check for response status\n", " // 200 - means that the connection was a success\n", " if(apiConnection.getResponseCode() != 200){\n", " System.out.println(\"Error: Could not connect to API\");\n", " return null;\n", " }\n", "\n", " // 2. Read the response and convert store String type\n", " URI uri = new URI(urlString);\n", " JSONTokener jsonResponse = new JSONTokener(uri.toURL().openStream());\n", "\n", " // 3. Parse the string into a JSON Object\n", " JSONObject resultsJsonObj = new JSONObject(jsonResponse);\n", "\n", " // 4. Retrieve Location Data\n", " JSONArray locationData = (JSONArray) resultsJsonObj.get(\"results\");\n", "\n", " // Get location data\n", " JSONObject cityLocationData = (JSONObject) locationData.get(0);\n", " BigDecimal latitude = (BigDecimal) cityLocationData.get(\"latitude\");\n", " BigDecimal longitude = (BigDecimal) cityLocationData.get(\"longitude\");\n", " \n", " System.out.print(\"\"\"\n", " - URL Geoposition: %s\n", " Longitude: %.2f\n", " Latitude: %.2f\n", " \"\"\".formatted(urlString, longitude.doubleValue(), latitude.doubleValue()));\n", "\n", " BigDecimal[] coordenadas = {latitude, longitude};\n", " return coordenadas;\n", "\n", " }catch(Exception e){\n", " e.printStackTrace();\n", " }\n", " return null;\n", " }\n", "\n", " private static void displayWeatherData(BigDecimal[] coordenadas ){\n", " try{\n", " BigDecimal latitude = coordenadas[0], longitude = coordenadas[1];\n", " // 1. Fetch the API response based on API Link\n", " String url = \"https://api.open-meteo.com/v1/forecast?latitude=\"+latitude+\"&longitude=\"+longitude+\"¤t=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m&format=json\";\n", " //System.out.println(\" - URL Weather: \"+url);\n", "\n", " HttpURLConnection apiConnection = fetchApiResponse(url);\n", "\n", " // check for response status\n", " // 200 - means that the connection was a success\n", " if(apiConnection.getResponseCode() != 200){\n", " System.out.println(\"Error: Could not connect to API\");\n", " return;\n", " }\n", "\n", " // 2. Read the response and convert store String type\n", " URI uri = new URI(url);\n", " JSONTokener jsonResponse = new JSONTokener(uri.toURL().openStream());\n", " \n", " // 3. Parse the string into a JSON Object\n", " JSONObject jsonObject = new JSONObject(jsonResponse);\n", " JSONObject currentWeatherJson = (JSONObject) jsonObject.get(\"current\");\n", "\n", " // 4. Store the data into their corresponding data type\n", " String time = (String) currentWeatherJson.get(\"time\");\n", " //System.out.println(\" Current Time: \" + time);\n", "\n", " BigDecimal temperature = (BigDecimal) currentWeatherJson.get(\"temperature_2m\");\n", " // System.out.println(\" Current Temperature (C): \" + temperature.doubleValue());\n", "\n", " // long relativeHumidity = (long) currentWeatherJson.get(\"relative_humidity_2m\");\n", " // System.out.println(\"Relative Humidity: \" + relativeHumidity);\n", "\n", " BigDecimal windSpeed = (BigDecimal) currentWeatherJson.get(\"wind_speed_10m\");\n", " // System.out.println(\" Weather Description: \" + windSpeed.doubleValue()+\"\\n\");\n", "\n", " System.out.print(\"\"\"\n", " - URL Weather: %s\n", " Current Time: %s\n", " Current Temperature (C): %.2f\n", " Weather Description: %.2f\n", " \"\"\".formatted(url, time, temperature.doubleValue(), windSpeed.doubleValue()));\n", " }catch(Exception e){\n", " e.printStackTrace();\n", " }\n", " }\n", "\n", " private static HttpURLConnection fetchApiResponse(String urlString){\n", " try{\n", " // attempt to create connection\n", " URL url = new URL(urlString);\n", " HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n", "\n", " // set request method to get\n", " conn.setRequestMethod(\"GET\");\n", "\n", " return conn;\n", " }catch(IOException e){\n", " e.printStackTrace();\n", " }\n", "\n", " // could not make connection\n", " return null;\n", " }\n", "}" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "City Entered: Bogota\n", "- URL Geoposition: https://geocoding-api.open-meteo.com/v1/search?name=Bogota&count=1&language=en&format=json\n", " Longitude: -74,08\n", " Latitude: 4,61\n", "- URL Weather: https://api.open-meteo.com/v1/forecast?latitude=4.60971&longitude=-74.08175¤t=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m&format=json\n", " Current Time: 2024-11-20T05:45\n", " Current Temperature (C): 12,700000\n", " Weather Description: 4,500000\n", "\n", "City Entered: New York\n", "- URL Geoposition: https://geocoding-api.open-meteo.com/v1/search?name=New+York&count=1&language=en&format=json\n", " Longitude: -74,01\n", " Latitude: 40,71\n", "- URL Weather: https://api.open-meteo.com/v1/forecast?latitude=40.71427&longitude=-74.00597¤t=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m&format=json\n", " Current Time: 2024-11-20T05:45\n", " Current Temperature (C): 9,900000\n", " Weather Description: 2,900000\n", "\n", "City Entered: Cali\n", "- URL Geoposition: https://geocoding-api.open-meteo.com/v1/search?name=Cali&count=1&language=en&format=json\n", " Longitude: -76,52\n", " Latitude: 3,44\n", "- URL Weather: https://api.open-meteo.com/v1/forecast?latitude=3.43722&longitude=-76.5225¤t=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m&format=json\n", " Current Time: 2024-11-20T05:45\n", " Current Temperature (C): 19,500000\n", " Weather Description: 1,800000\n", "\n" ] } ], "source": [ "// Probado la clase WeatherAPIData\n", "String [] ciudades = {\"Bogota\", \"New York\", \"Cali\"};\n", "new WeatherAPIData().main(ciudades);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Descripción del Código\n", "\n", "\n", "\n", "## Recursos Adicionales\n", "\n", "- [How to perform API calls in Java - Weather Forecast API Example](https://www.youtube.com/watch?v=WS_H44tvZMI)\n", "- [Java-Tutorials/WeatherAPIData.java - GitHub](https://github.com/curadProgrammer/Java-Tutorials/blob/main/WeatherAPIData.java)" ] } ], "metadata": { "kernelspec": { "display_name": "Java", "language": "java", "name": "java" }, "language_info": { "codemirror_mode": "java", "file_extension": ".jshell", "mimetype": "text/x-java-source", "name": "java", "pygments_lexer": "java", "version": "21.0.5+11-Ubuntu-1ubuntu124.04" } }, "nbformat": 4, "nbformat_minor": 2 }