<p>A number of map services are offered through The National Map (<a href="https://nationalmap.gov/">TNM</a>).
There are no use restrictions on these <a href="https://viewer.nationalmap.gov/services/">services</a>.
However, map content is limited to the United States and Territories.
This post explains how to integrate TNM services within your own interactive web map using
<a href="https://rstudio.github.io/leaflet/">Leaflet for R</a>.</p>
<p>R packages required for this tutorial include
<a href="https://cran.r-project.org/package=leaflet">leaflet</a>,
<a href="https://cran.r-project.org/package=rgdal">rgdal</a>, and
<a href="https://cran.r-project.org/package=dataRetrieval">dataRetrieval</a>.
Install the required packages from the Comprehensive R Archive Network (<a href="https://cran.r-project.org/">CRAN</a>)
using the following commands:</p>
<pre><code>for (pkg in c(&quot;leaflet&quot;, &quot;rgdal&quot;, &quot;dataRetrieval&quot;)) {
  if (!pkg %in% rownames(utils::installed.packages()))
    utils:install.packages(pkg, repos = &quot;https://cloud.r-project.org/&quot;)
}
</code></pre>
<p>The first step is to create a Leaflet map widget:</p>
<pre><code>map &lt;- leaflet::leaflet()
</code></pre>
<p>In Leaflet, a map layer is used to display a specific dataset.
Map layers are organized by group.
Many layers can belong to the same group, but each layer can only belong to zero or one groups.
For this example, each map layer belongs to a discrete group.
Create a vector of unique group names identifying the five layers to be added to the map widget:</p>
<pre><code>grp &lt;- c(&quot;USGS Topo&quot;, &quot;USGS Imagery Only&quot;, &quot;USGS Imagery Topo&quot;,
         &quot;USGS Shaded Relief&quot;, &quot;Hydrography&quot;)
</code></pre>
<p>Specify the line of attribution text to display in the map using the Hypertext Markup Language (HTML) syntax:</p>
<pre><code>att &lt;- paste0(&quot;&lt;a href='https://www.usgs.gov/'>&quot;,
              &quot;U.S. Geological Survey&lt;/a> | &quot;,
              &quot;&lt;a href='https://www.usgs.gov/laws/policies_notices.html'>&quot;,
              &quot;Policies&lt;/a>&quot;)
</code></pre>
<p>Leaflet supports base maps using <a href="https://www.mapbox.com/help/how-web-maps-work/">map tiles</a>.
TNM base maps are available as Web Map Service (<a href="https://en.wikipedia.org/wiki/Web_Map_Service">WMS</a>) tiles.
Add tiled layers (base maps) that describe topographic information in TNM to the map widget:</p>
<pre><code>GetURL &lt;- function(service, host = &quot;basemap.nationalmap.gov&quot;) {
  sprintf(&quot;https://%s/arcgis/services/%s/MapServer/WmsServer&quot;, host, service)
}
map &lt;- leaflet::addWMSTiles(map, GetURL(&quot;USGSTopo&quot;),
                            group = grp[1], attribution = att, layers = &quot;0&quot;)
map &lt;- leaflet::addWMSTiles(map, GetURL(&quot;USGSImageryOnly&quot;),
                            group = grp[2], attribution = att, layers = &quot;0&quot;)
map &lt;- leaflet::addWMSTiles(map, GetURL(&quot;USGSImageryTopo&quot;),
                            group = grp[3], attribution = att, layers = &quot;0&quot;)
map &lt;- leaflet::addWMSTiles(map, GetURL(&quot;USGSShadedReliefOnly&quot;),
                            group = grp[4], attribution = att, layers = &quot;0&quot;)
</code></pre>
<p>The content of these layers is described in the
<a href="https://viewer.nationalmap.gov/help/3.0%20TNM%20Base%20Maps.htm">TNM Base Maps</a> document.</p>
<p>An overlay map layer adds information, such as river and lake features, to a base map.
Add the tiled overlay for the <a href="https://nhd.usgs.gov/">National Hydrography Dataset</a> to the map widget:</p>
<pre><code>opt &lt;- leaflet::WMSTileOptions(format = &quot;image/png&quot;, transparent = TRUE)
map &lt;- leaflet::addWMSTiles(map, GetURL(&quot;USGSHydroCached&quot;),
                            group = grp[5], options = opt, layers = &quot;0&quot;)
map &lt;- leaflet::hideGroup(map, grp[5])
</code></pre>
<p>Point locations, that appear on the map as icons, may be added to a base map using a marker overlay.
In this example, site locations are included for selected wells in the
<a href="https://id.water.usgs.gov/INL/">USGS Idaho National Laboratory</a>
water-quality observation network.
Create the marker-overlay dataset using the following commands (requires web access):</p>
<pre><code>site_no &lt;- c(&quot;USGS 1&quot;    = &quot;432700112470801&quot;,
             &quot;USGS 14&quot;   = &quot;432019112563201&quot;,
             &quot;USGS 8&quot;    = &quot;433121113115801&quot;,
             &quot;USGS 126A&quot; = &quot;435529112471301&quot;,
             &quot;USGS 29&quot;   = &quot;434407112285101&quot;,
             &quot;USGS 52&quot;   = &quot;433414112554201&quot;,
             &quot;USGS 84&quot;   = &quot;433356112574201&quot;,
             &quot;TRA 4&quot;     = &quot;433521112574201&quot;)
dat &lt;- dataRetrieval::readNWISsite(site_no)
sp::coordinates(dat) &lt;- c(&quot;dec_long_va&quot;, &quot;dec_lat_va&quot;)
sp::proj4string(dat) &lt;- sp::CRS(&quot;+proj=longlat +datum=NAD83&quot;)
dat &lt;- sp::spTransform(dat, sp::CRS(&quot;+init=epsg:4326&quot;))
</code></pre>
<p>Popups are small boxes containing text that appear when marker icons are clicked.
Specify the text to display in the popups using the HTML syntax:</p>
<pre><code>num &lt;- dat$site_no  # site number
nam &lt;- names(site_no)[match(num, site_no)]  # local site name
url &lt;- sprintf(&quot;https://waterdata.usgs.gov/nwis/inventory/?site_no=%s&quot;, num)
pop &lt;- sprintf(&quot;&lt;b>Name:&lt;/b> %s&lt;br/>&lt;b>Site No:&lt;/b> &lt;a href='%s'>%s&lt;/a>&quot;,
               nam, url, num)
</code></pre>
<p>Add the marker overlay to the map widget:</p>
<pre><code>opt &lt;- leaflet::markerClusterOptions(showCoverageOnHover = FALSE)
map &lt;- leaflet::addCircleMarkers(map, radius = 10, weight = 3, popup = pop,
                                 clusterOptions = opt, data = dat)
</code></pre>
<p>Add a Leaflet control feature that allows users to interactively show and hide base maps:</p>
<pre><code>opt &lt;- leaflet::layersControlOptions(collapsed = FALSE)
map &lt;- leaflet::addLayersControl(map, baseGroups = grp[1:4],
                                 overlayGroups = grp[5], options = opt)
</code></pre>
<p>Print the map widget to display it in your web browser:</p>
<pre><code>print(map)
</code></pre>
<p>Some users have reported that base maps do not render correctly in the
<a href="https://www.rstudio.com/">RStudio</a> viewer.
Until RStudio can address this issue, the following workaround is provided:</p>
<pre><code>options(viewer = NULL)
print(map)
</code></pre>
<p>And let’s not forget the R session information.</p>
<pre><code>print(utils::sessionInfo())
</code></pre>
<pre><code>## R version 3.3.3 (2017-03-06)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 14393)
## 
## locale:
## [1] LC_COLLATE=English_United States.1252 
## [2] LC_CTYPE=English_United States.1252   
## [3] LC_MONETARY=English_United States.1252
## [4] LC_NUMERIC=C                          
## [5] LC_TIME=English_United States.1252    
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_0.12.10        xml2_1.1.1          knitr_1.15.1       
##  [4] magrittr_1.5        hms_0.3             lattice_0.20-35    
##  [7] xtable_1.8-2        R6_2.2.0            plyr_1.8.4         
## [10] stringr_1.2.0       httr_1.2.1          dplyr_0.5.0        
## [13] tools_3.3.3         rgdal_1.2-6         grid_3.3.3         
## [16] DBI_0.6-1           htmltools_0.3.5     crosstalk_1.0.0    
## [19] yaml_2.1.14         dataRetrieval_2.6.7 leaflet_1.1.0      
## [22] digest_0.6.12       assertthat_0.1      tibble_1.3.0       
## [25] shiny_1.0.1         reshape2_1.4.2      readr_1.1.0        
## [28] htmlwidgets_0.8     curl_2.4            evaluate_0.10      
## [31] mime_0.5            sp_1.2-4            stringi_1.1.5      
## [34] jsonlite_1.4        lubridate_1.6.0     httpuv_1.3.3
</code></pre>