This year marks the 100th anniversary of the National Park Service, an organization established by Congress for “preserving the ecological and historical integrity of the places entrusted to its management while also making them available and accessible for public use and enjoyment”. Among the centennial festivities is a call to get out to experience the National Parks and “Find Your Park.”

We thought it might be fun to help you plan a National Park visit with this React app that provides current forecast information for the National Parks.

See the Pen National Park Weather with React by Sev (@sevleonard) on CodePen.

In this post we will use the Google Maps API, the DarkSky API for weather forecasting, and the Recreation Information Database (RIDB) for National Parks info. We’ll wrap all this up in a React app to help you plan a National Parks trip. For more info on getting started with RIDB and Google Maps check out Interactive Mapping with Python, GeoJSON, and JavaScript and Advanced Google Maps with JavaScript. If you are coming to React from a background in jQuery this primer is a great way to get started.

In this post you will learn:

Some quick Python data wrangling to acquire, clean, and organize data from an API

How to create a Google Maps object in React, import markers from JSON, and update info windows

Using state properties to optimize forecast retrieval

Using axiom to load external data in React

Using Promises to encapsulate calls to the DarkSky API

Dealing with CORS issues in codepen

We’re covering a lot of ground in this post, so if you’re here for something specifc you might want to skip to that area:

Using Python to get National Park Data

Setting up Google Maps in React

Integrating the DarkSky API

Async Marker Retrieval

Forecast Promises

Getting the forecast: state or API?

Getting Information on National Parks



Using the RIDB organizations endpoint we can get a list of all properties managed by the National Park Service. We’ll use a bit of Python to get this info from the API and store it into a flat file for use by our React app later on. You will need to get a RIDB API key to execute this code.

endpoint = 'https://ridb.recreation.gov/api/v1/organizations/{orgID}/recareas' # NPS is org_id 128 org_id = 128 offset=0 params = dict(apiKey= config.RIDB_API_KEY, offset=offset) nps_url = endpoint.replace('{orgID}', str(org_id)) resp = requests.get(url=nps_url, params=params) data = json.loads(resp.text) df = json_normalize(data['RECDATA'])

The RIDB endpoint will return 50 records at a time. To see how many records there are for the NPS org, we can look at the TOTAL_RECORDS field in the response data:

max_records = data['METADATA']['RESULTS']['TOTAL_COUNT']

Max records is 590. There are 58 National Parks, so clearly we are getting a lot more information than we need. We’ll extract the National Parks after we download the entire list.

We’ll continue calling the API until we’ve reached max_records, adding the response data to a data frame to accumulate all the organizations. We will use the offset value to keep track of where we are in the list and update the API query to provide the next 50 records

#save the first 50 records before we iterate df_nps = df while offset < max_records: offset = offset + len(df) print("offset: " + str(offset)) df = pd.DataFrame() params = dict(apiKey = config.RIDB_API_KEY, offset = offset) try: resp = requests.get(url = nps_url, params = params) except Exception as ex: print(ex) break if resp.status_code == 200: data = json.loads(resp.text) if data['METADATA']['RESULTS']['CURRENT_COUNT'] > 0: df = json_normalize(data['RECDATA']) df_nps = df_nps.append(df) else : print("Response: " + str(resp.status_code))

Now lets look for the National Parks among this list. Lets start out by just checking the name for “National Park”

df_np = df_nps[df_nps['RecAreaName'].apply(lambda x: x.find('National Park') > 0)] df_np.shape (61,18)

That certainly helped! Looks like we have a few extras above the 58 National Parks we have to weed out. Another thing to check for is latitude and longitude values, since we want to plot this data on a map. Lets see how many of these 61 areas are missing location info:

df_np[df_np['RecAreaLongitude'] == ""].RecAreaName 21 Arches National Park 38 Black Canyon Of The Gunnison National Park 18 Carlsbad Caverns National Park 47 Denali National Park & Preserve 43 Gates Of The Arctic National Park & Preserve 49 Glacier National Park 16 Guadalupe Mountains National Park 21 Haleakalā National Park 43 Katmai National Park & Preserve 9 Lassen Volcanic National Park 21 Western Arctic National Parklands 9 Congaree National Park Wilderness 48 Rocky Mountain National Park Wilderness

13 of the National Park areas are missing location info. Looking at the last three in the list, Western Arctic National Parklands, Congaree National Park Wilderness, and Rocky Mountain National Park Wilderness are not part of the 58 National Parks, so we will drop them from the list. For the other 10 we can look up the latitude/longitude and update the data frame with those missing values using pandas update:

# file we stored the missing lat/long values in after looking them up missing_latlongs = pd.read_csv('missing_lat_longs.csv') missing_latlongs.head() RecAreaName RecAreaLatitude RecAreaLongitude 0 Arches National Park 38.7331 -109.5925 1 Black Canyon Of The Gunnison National Park 38.5754 -107.7416 2 Carlsbad Caverns National Park 32.1479 -104.5567 3 Denali National Park & Preserve 63.1148 -151.1926 4 Gates Of The Arctic National Park & Preserve 67.9204 -153.2753 #set the indexes for missing_latlongs and df_np to the RecAreaName. The update function uses the index to merge the data missing_latlongs = missing_latlongs.set_index('RecAreaName') df_np = df_np.set_index('RecAreaName') df_np.update(missing_latlongs) # RecAreaName has been converted to an index, recreate this field and reset the index df_np['RecAreaName'] = df_np.index df_np['newIndex'] = range(0,58) df_np.set_index(df_np['newIndex']) df_np = df_np.drop('newIndex', axis=1) # check that we captured all 58 National Parks df_np.shape (58, 18) #save to csv for later use df_np.to_csv('np_info.csv')

Great! We now have all 58 National Parks and their lat/long data for the map. Next lets switch over to React to create the Google Maps object for displaying these parks.

Creating the Google Maps object



While we are able to use the Google Maps API with React, it doesn’t exactly let us do so in a way that is truly React-ish, you can read more about that issue here. That caveat aside, lets dive into creating a map in React.

We’ll start by creating a React Component object to encapsulate the methods, states, and properties for the map

class NpsForecastMap extends React.Component

The Component class includes a number of lifecycle methods to handle creation, initialization, interaction, and disposal. Lets get started by defining some properties

state = { forecast:{} }; propTypes = { np_url: React.PropTypes.string, init_lat: React.PropTypes.number, init_lng: React.PropTypes.number };

Our app is going to generate the current forecast for each National Park when a user clicks on the marker. Since the DarkSky API isn’t free, we can keep track of if the forecast has been fetched already to avoid the overhead, both financially and in waiting on the API response, by maintaining a dictionary of forecast state. We’ll see later how this will be used to cache the current forecast.

The propTypes objects enables us to validate the inputs to our component. By parameterizing the input geojson file and the initial map center we can reuse this component with other datasets, for example, local state parks or a set of points you plan to visit on a road trip. The React.PropTypes validators enable us to confirm that the inputs received are of the expected type, though note that these validators will not screen for a valid geojson file or valid latitude and longitude, they simply check the type of the object passed.

Now that we have setup the component properties, lets take a look at some of the methods for our NpsForecastMap component.

The render() method is required, and will read the state and props properties of the component. This method will also contain the HTML representation of our component to be added to the DOM at the time of rendering. For the NpsForecastMap component will simply add a div for React to reference when building the map, as we will see later:

render() { return

}

Remember from previous articles that we need to give the map divs a defined size:

.NpsForecastMap { height: 100%; position: absolute; width: 100%; }

In the HTML we have a div available for React to render the component in:

<div id="container"></div>

At the end of our React App file, we will attach the Map component to the div “container”.

ReactDOM.render(, document.getElementById('container'));

After the NpsForecastMap component has been rendered we can initialize the Google Maps object in the ComponentDidMount method, which runs after the initial rendering has occurred:

componentDidMount() { this.map = this.createMap() ... } createMap() { let mapOptions = { zoom: 3, center: this.mapCenter() } return new google.maps.Map(this.refs.mapdiv, mapOptions) } mapCenter() { return new google.maps.LatLng( this.props.init_lat, this.props.init_lng ) }

Notice that we are creating the map by referencing the mapdiv ref we created in the render() method. By providing references to entities with in the NpsForecastMap component we can avoid having to directly reference the DOM.

Async Marker Retrieval



In React apps, we want to leave the DOM rendering to React as much as possible, meaning JQuery’s methods of direct DOM manipulation don’t play nice with the React paradigm. For async calls to APIs, we can use the axios promise-based HTTP client in place of AJAX. Lets take a look at how to do that for loading the National Park geojson file.

After creating the map in the componentDidMount method, we will call a method to load the geojson and create the makers for the map.

componentDidMount() { this.map = this.createMap() this.loadFeatures()

Taking a look at the first part of the loadFeatures function, we can see how similar the axios API is to JQuery for getting data:

loadFeatures() { ... var self = this axios.get(th.props.nps_source) .then(function(result) { ...

Notice that we are saving the context ‘this’ off to a local variable ‘self’. When working with async calls its important to remember that we will be operating in a different scope when the callback occurs, so ‘this’ will pertain to that local scope, not the scope in which we called loadFeatures. Creating a variable to encapsulate the initial scope will enable us to refer to methods and properties of the class when handling the result from the async call.

When we get the result from the axios get call, we’ll iterate through each feature in the collection and create the markers:

axios.get(th.props.nps_source) .then(function(result) { for (let val of result.data.features) { let marker = self.createMarker(val, self.map)

Notice that we are using the ‘self’ variable to access the createMarker method of the NpsForecastMap component and to pass the map object to createMarker.

createMarker(val, map) { let pointval = new google.maps.LatLng( parseFloat(val['geometry']['coordinates'][1]), parseFloat(val['geometry']['coordinates'][0])); let titleText = val['properties']['title'] let marker = new google.maps.Marker({ position: pointval, map: map, title: titleText }); return marker }

Once we parse the geojson we can create a new Marker object with the features, using the ‘map’ parameter to link the marker to the NpsForecastMap property. Now the marker will display on the map. We’ll come back to the markers to add an InfoWindow with the park name and current weather, for now lets take a look at how to get our forecast from DarkSky

See the Pen National Park Weather with React by Sev (@sevleonard) on CodePen.

Integrating the DarkSky API

Ideally, we would separate out the call to the forecast into a separate react component, ForecastAction.js for example. This would enable us to be flexible with our forecast provider, and provide a more appropriate separation of view and control in our app. We’ve started that work by creating a function with a fairly universal interface, taking only latitude and longitude as parameters and returning the current weather:

getForecast(lat, lng) { ... let request_url="https://crossorigin.me/https://api.darksky.net/forecast/8266ff95ef9bbfccf0ea24c325818f31/" request_url = request_url + lat + "," + lng axios.get(request_url) .then(function(result) { let content = result.data.daily.summary

To access the DarkSky API from codepen, we need to use crossorigin.me to avoid CORS issues when querying the forecast. To do this we prepend crossorigin.me to the DarkSky API URL. Using the axios library again we query the API for our location and extract the daily summary, which will look something like:

“Mixed precipitation throughout the week, with temperatures peaking at 55°F on Saturday.”

So we have our forecast, but we have an async call within getForecast. We want to add the daily summary text to our marker info window, which needs to happen after we have retrieved the forecast. One option would be to pass the marker info window into the getForecast function, so we could directly update the info window when we get the forecast. But then we are mixing view elements with control elements, and making the call to getForecast less generic to enable swapping in a different forecast provider. Instead, we can wrap getForecast in a Promise, preserving the separation of control from view and maintaining the generic interface of the function.

Forecast Promises



Appropriate, since a forecast is kind of like a promise about the weather, your mileage may vary as to how well weather promises are kept, however.

If you are new to Promises here is an overview of the Promise object and how it works. At a high level, we will be creating a structure within the getForecast function that will enable us to call it like the axios get function, i.e.

getForecast(lat,lng) .then(function(result) { // add forecast to info window })

First, we need to create a promise object, forecast_p. The forecast object needs to implement a resolve directive, for providing direction on when the async method has completed successfully, and a reject method for when things don’t turn out as we expect. In this promise, we only have a resolve directive for brevity.

getForecast(lat, lng) { let forecast_p = new Promise( function(resolve,reject) { ... axios.get(request_url) .then(function(result) { let content = result.data.daily.summary resolve(content) }); });

After we get the forecast from DarkSky we resolve with the daily summary.

With the Promise created, we can now determine what to do after the forecast has been fetched:

forecast_p.then( function(result) { return result } ) return forecast_p

The result will be the daily forecast we passed to resolve() when creating the Promise. At this point, we return the Promise so the caller can determine when to initiate the DarkSky request.

Getting the forecast: state or API?



Now that we have a mechanism for getting the forecast, we can proceed with adding a click handler to the marker. In addition to getting the current forecast (or not, depending on the state) we will pop up an InfoWindow to display the park name and forecast summary. On click, we will close the current InfoWindow, this will avoid multiple InfoWindows being created and requiring the user to manually close them. We are also creating a local variable getWeather which will be used to determine if we can read from our forecast state property or if we need to query DarkSky.

let marker = th.createMarker(val, th.map) marker.addListener('click', function() { infoWindow.close() let title = this.title let infoContent = "" let getWeather = false-

Now, lets check our forecast state to see if we already have the weather for this marker:

// check to see if we already have the forecast for this marker if (title in th.state.forecast) { infoContent = title + " " + th.state.forecast[title] } else { infoContent = title + " Loading Current Weather..." getWeather = true }

Our forecast state property is indexed by park name, which is the marker title. If we can find the park in the forecast state property we can read the forecast directly from there without having the query the API. We can create the info window content directly from here.

Otherwise, we will provide a message ‘Loading current weather’ and set our getWeather variable. Based on this, we can call into our getForecast Promise, updating the info window with the result:

if (getWeather) { th.getForecast(marker.position.lat(),marker.position.lng()) .then(function(result) { infoWindow.setContent(title + " " + result) th.state.forecast[title] = result }) }

Check it out for yourself! There are some debug messages you can check out in the console to verify if the weather is being read from state

See the Pen National Park Weather with React by Sev (@sevleonard) on CodePen.

Summary

Wow, we’ve covered a lot here. Pat yourself on the back and check out this React google maps module if you’d like to take a shortcut. Tom does a great job of React-ifying the Google Maps API in this npm module.

When you’re ready for more, consider these potential next steps