#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

const char* openElevationAPI = "https://api.open-elevation.com/api/v1/lookup";
const float latitude = 37.7749;  // Replace with your latitude
const float longitude = -122.4194;  // Replace with your longitude

void setup() {
  Serial.begin(115200);

  // Connect to Wi-Fi
  WiFi.begin("Wokwi-GUEST");

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting...");
  }

  Serial.println("Connected");
}

void loop() {
  // Make the API request
  sendElevationRequest(latitude, longitude);

  // Wait for some time before making the next request
  delay(500);
}

void sendElevationRequest(float lat, float lon) {
  HTTPClient http;

  // Build the API URL
String url = String(openElevationAPI) + "?locations=" + String(lat, 6) + "," + String(lon, 6);

  // Serial.println("Sending request to: " + url);

  // Start the HTTP request
  http.begin(url);

  // Send the request and get the response
  int httpCode = http.GET();
  if (httpCode > 0) {
    if (httpCode == HTTP_CODE_OK) {
      String payload = http.getString();
      // Serial.println("Response: " + payload);

      // Parse JSON response
      DynamicJsonDocument doc(1024);
      DeserializationError error = deserializeJson(doc, payload);
      
      if (error) {
        Serial.println("Failed to parse JSON");
        return;
      }

      // Extract elevation value
      float elevation = doc["results"][0]["elevation"];
      Serial.print("Elevation: ");
      Serial.println(elevation);
    } else {
      Serial.println("HTTP request failed with error code: " + String(httpCode));
    }
  } else {
    Serial.println("HTTP request failed");
  }

  // End the request
  http.end();
}