Adding a Map feature to your React App

Cameron Bisca
3 min readMar 25, 2021

For this example I will be using Leaflet as my map API to display basketball courts throughout NYC. Luckily Leaflet’s homepage for React offers a very simple and easy guide to get you started.

Leaflet homepage: https://react-leaflet.js.org/

Before we get moving, make sure to follow the steps for installing the necessary packages and dependencies for this feature. Click on “Get Started” and navigate to installation on the left hand side of the page for these steps.

Before I begin implementing Leaflet’s map I start with adding two columns to my court model. One for latitude and the other for longitude, the datatype for both should be float. We’ll need this later for when we create markers for each court instance. After you migrate your tables make sure these attributes are included in the seeds file.

Following the Leaflet documentation, step one of preparing our page is adding the CSS file in the head section within index.html.

Steps two and three (including Leaflet JavaScript file and putting a div element with a certain id where you want your map to be) we don’t need to do thanks to React magic and installation. Ya love to see it!

Next we can implement the code provided by the docs to use as we see fit. In my example, I created a new file for my CourtMap component and pasted the code within the return for that component.

Sidebar: TileLayer is meant to give the folks who built this API the props they deserve. I don’t believe it’s contributing to any of the mechanics under the hood.

A couple of attributes worth noting here on MapContainer:

Center refers to the starting point of your map. So if you are focus on NYC like I am it’s probably best to not start in London. To change the coordinates for a center value of your choice, right click on your desired location in google maps and the latitude longitude coordinates should be the first option. Past those here.

scrollWheelZoom refers to the ability to zoom in and out with the scroll wheel on your mouse. Change the value to true if you prefer this functionality.

It’s important to know that the MapContainer needs a size included in the CSS styling to function. This container comes with default CSS classes that you can find with your developer tools in the browser.

Back to rendering markers on the map for each court instance..

The courts variable are my array of courts in state that was passed down from the parent component. Map over this array and for each court create a marker that dynamically assigns the latitude and longitude for each court to the position attribute. Within the marker, include a Popup for when a user clicks on the marker. In this example I am displaying the courts name. If you would like to add a click event, check out the rest of the documentation for how to click and redirect to a show page.

That’s it y’all! Have fun.

--

--