Skip to Content
Course content

66: Geospatial Visualization with leaflet

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I can't tell you how many times I've seen a developer stare at a blank grey screen or a map of the South Pacific when they were actually trying to map a neighborhood in London. It's a rite of passage with leaflet. Usually, it's not a bug in the package, but a fundamental misunderstanding of how geospatial coordinates are handled in the underlying JavaScript libraries.

The map is showing the middle of the ocean

library(leaflet)

# Let's say we have some coffee shop data for Seattle
shops <- data.frame(
  name = c("Cafe A", "Cafe B"),
  lat = c(47.6062, 47.6150),
  lon = c(-122.3321, -122.3410)
)

leaflet(shops) %>% 
  addTiles() %>% 
  addMarkers(lng = ~lat, lat = ~lon) # Wait, this looks right... right?

If you run the code above, you'll notice the markers aren't in Seattle. In fact, they're probably nowhere near Washington state. The code runs without an error message, which is the most frustrating part. You're just looking at the wrong part of the world.

Swap your X and Y

The fix is simple, but the reason is what matters: leaflet follows the GeoJSON standard, which treats coordinates as [longitude, latitude]. Think of it like a standard Cartesian plane: Longitude is your X-axis (east-west) and Latitude is your Y-axis (north-south). In the broken code above, I passed the latitude to the lng argument and the longitude to the lat argument.

leaflet(shops) %>% 
  addTiles() %>% 
  addMarkers(lng = ~lon, lat = ~lat) # Correct: Longitude first, then Latitude

Once you align these, your markers will snap back to where they belong. Always double-check your column mapping; it's the single most common mistake I see when people start with geospatial R.

Changing the map's aesthetic

By default, addTiles() pulls from OpenStreetMap. It's great for general use, but depending on what you're visualizing, it might be too cluttered. I often prefer the "CartoDB" tiles because they provide a cleaner, more muted background that makes your data points actually pop.

You can swap the default provider by passing a URL to addTiles() or using the providers argument if you have the leafletProviders package installed. For a quick, clean look without extra packages, try this:

leaflet(shops) %>% 
  addProviderTiles(providers = "CartoDB.Positron") %>% 
  addMarkers(lng = ~lon, lat = ~lat)

Managing marker clutter with clustering

If you're mapping five coffee shops, addMarkers() is fine. If you're mapping five thousand, your browser will likely hang, and your map will just be a solid blob of blue pins. This is where addMarkerCluster() becomes your best friend.

Instead of drawing every individual point, clustering groups nearby markers into a single circle with a number inside. As you zoom in, the clusters break apart into individual pins. It's much more performant and significantly more readable.

leaflet(shops) %>% 
  addProviderTiles(providers = "CartoDB.Positron") %>% 
  addMarkerCluster(lng = ~lon, lat = ~lat, popup = ~name)

I added the popup argument here too. In a real-world project, a pin without a label is useless. By passing a column from your data frame to popup, you give the user a way to actually identify what they're looking at.




📋 Practical Task

Visualizing NYC Bike Stations with Clustering

You have been handed a dataset of New York City Citi Bike stations. Your goal is to create an interactive map that doesn't overwhelm the user with thousands of overlapping pins.

Requirements:

  • Create a data frame called bike_stations with at least 5 sets of coordinates (Latitude and Longitude) located within NYC (approx. Lat: 40.7, Lon: -74.0).
  • Use the CartoDB.DarkMatter tile provider to give the map a "dark mode" aesthetic.
  • Implement addMarkerCluster instead of standard markers to handle the station density.
  • Ensure each marker has a popup that displays the station's name (you'll need to add a station_name column to your data frame).
  • Verify that your Longitude and Latitude are mapped to the correct leaflet arguments to avoid the "ocean bug".
Rating
0 0

There are no comments for now.

to be the first to leave a comment.