---
title: "Load and plot data from Nevada Geodetic Laboratory"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Load and plot data from Nevada Geodetic Laboratory}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  fig.width = 10, # Set default plot width (adjust as needed)
  fig.height = 8, # Set default plot height (adjust as needed)
  fig.align = "center" # Center align all plots
)
```



First, load the `gmwmx2` package.
```{r}
library(gmwmx2)
```

# Download all available stations from NGL

```{r}
all_stations <- download_all_stations_ngl()
head(all_stations)
```

# Download one station
```{r}
data_CERN <- download_station_ngl("CERN")
```
# Extract GNSS position time series for the station
```{r}
attributes(data_CERN)
head(data_CERN$df_position)
```

# Locate the station on a map

The interactive map uses the nominal station coordinates returned by
`download_station_ngl()` and OpenStreetMap tiles via the optional `leaflet`
package. No account or API key is needed. The map background requires an
internet connection when viewing the vignette; attribution is shown on the map.

```{r station-map}
if (!is.data.frame(data_CERN$df_position) || nrow(data_CERN$df_position) == 0L) {
  message("Skipping map: no position data were downloaded for CERN.")
} else if (!requireNamespace("leaflet", quietly = TRUE)) {
  message("Install the optional 'leaflet' package to display the station map.")
} else {
  latitude <- data_CERN$df_position$nominal_station_latitude
  longitude <- data_CERN$df_position$nominal_station_longitude
  valid <- which(is.finite(latitude) & abs(latitude) <= 90 &
                   is.finite(longitude))

  if (length(valid) == 0L) {
    message("Skipping map: no valid station coordinates are available for CERN.")
  } else {
    latitude <- latitude[valid[1L]]
    longitude <- ((longitude[valid[1L]] + 180) %% 360) - 180

    station_map <- leaflet::leaflet()
    station_map <- leaflet::addTiles(station_map)
    station_map <- leaflet::setView(station_map, lng = longitude,
                                    lat = latitude, zoom = 12)
    leaflet::addMarkers(station_map, lng = longitude, lat = latitude,
                        popup = "CERN GNSS station", label = "CERN")
  }
}
```

# Extract equipment or software change steps
```{r}
head(data_CERN$df_equipment_software_changes)
```

# Extract earthquake steps
```{r}
head(data_CERN$df_earthquakes)
```



# Plot GNSS position time series 
```{r}
if (is.data.frame(data_CERN$df_position) && nrow(data_CERN$df_position) > 0L) {
  plot(data_CERN)
  plot(data_CERN, component = "N")
  plot(data_CERN, component = "E")
  plot(data_CERN, component = "V")
} else {
  message("Skipping plots: no position data were downloaded for CERN. Check the download warnings and try again later.")
}
```
