A guide to using Mapbox and Unsplash to build a map of photos.

Plotting photos on a map with the Unsplash API and Mapbox

I moved to New York City in October of 2020. After the vicious first wave of the pandemic, articles flew across the internet declaring that New York was dead. Photography was re-emerging as one of my hobbies during quarantine, so I thought I might take my camera and venture across town to see if I might still be able to find life in this little city.

I set the ambitious, perhaps impossible, goal of photographing every block in NYC to show the life that still exists here. Setting aside the challenge of photographing all 120,000 blocks across the five boroughs (although less than 3,000 in Manhattan), the first thing I needed to do was build a tool to help me display my photos on a map.

What are we building?

I planned to take thousands of photos for this project. Each photo would need to be uploaded and tagged with a location. The website is intended to serve as a geospatial photo gallery. So, visitors to the site should be able to view a map to see where all of the photos were taken, and also click a location to see the photo at that location.

Follow along as I attempt to photograph all of NYC at Is New York Dead?

There were several pieces of this that I didn’t want to build myself:

  • Uploading a photo
  • Image transformation and compression
  • Tagging a photo with an address
  • Converting a photo’s address to set of latitude and longitude coordinates

To avoid building all of this myself, I looked for creative shortcuts. I came across Unsplash’s API. Unsplash is a website that allows photographers to make their work available for free use. Unsplash checks all of the boxes above: I can upload my photos (and in bulk groups, up to 10 at a time) and type in an address. Unsplash then makes that address’s coordinates available via API, as well as all of the photo’s metadata. Having that extra metadata will come in handy as my project grows and likely takes a new shape.

The Toolkit


Development Environment

I’m partial to Ruby on Rails, hosted on Heroku. It’s quick to start and there’s plenty of documentation available. To start, I followed Heroku’s tutorial to creating a new Rails 6 project in Heroku. This tutorial gets you to a point where you’ll have a website live on the internet that says “Hello World!”


To display a map from Mapbox on your website, you’ll first need three things:

  1. A Mapbox account: create one here.
  2. An Access token: once you’re logged into Mapbox, visit /access-tokens/ and create a token there. Mapbox also offers the option to restrict your token to only work on certain URLs. As a security measure to prevent someone else from using your token, add your website’s url to this list.
  3. A Style URL: Mapbox allows you to create your own map styles. Visit studio.mapbox.com to create a new style. After creating your style, you should see an option to share the style URL. The style URL should take the following structure: mapbox://styles/username/style-id


To begin working with the Unsplash API, you’ll first need two things:

  1. An Unsplash account: create one here.
  2. An API access key and secret key: Once you’re logged in, visit the Unsplash developers page and then visit ‘Your apps’. Create a new application and complete the basic information that Unsplash requires to work with their API. Once your app is created, you should see a page that includes an Access Key and Secret Key. Keep these secure and hold on to these for later use.

Adding a Mapbox map to the website

We’ll use Mapbox GL JS to display the map on the website.

  1. Add the following within the <head></head> tag in application.html.erb:
<script src='https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.css' rel='stylesheet' />

2. Next, we’ll add the snippet to our view to control how the map is displayed. If you followed Heroku’s Rails 6 setup tutorial, the file you’re looking for is index.html.erb

<div id='map' style='width: 400px; height: 300px;'></div>
mapboxgl.accessToken = "YOUR ACCESS TOKEN HERE";
var map = new mapboxgl.Map({
container: 'map',
center: [-73.975854, 40.728525],
zoom: 12.5,

Make sure to plug in the access token and style url that you created earlier. Then, boot up your server with rails s in Terminal and visit http://localhost:3000. At this point, you should see a map!

Adjust the center or zoom values in the script above and refresh the page to see how these settings affect the map’s default display.

Fetching photos from Unsplash

Installing the Unsplash Gem

Now, let’s try to grab photos from Unsplash. I started by following the instructions on the unplash_rb repo. Basically, you need to do three things:

  1. Install the Unsplash gem. In terminal, enter $ gem install unsplash
  2. Next you’ll need to configure the gem with your credentials. Create a new file in /config/initializers/ called unsplash.rb and populate it with the following:
Unsplash.configure do |config|
config.application_access_key = ENV['UNSPLASH_KEY']
config.application_secret = ENV['UNSPLASH_SECRET']
config.application_redirect_uri = "https://your-application.com/oauth/callback"
config.utm_source = "alices_terrific_client_app"

To securely provide the Unsplash Access Key and Secret that you previously acquired, you’ll need to store them as environment variables. In terminal, enter:


If you happen to close your terminal and come back to the project later, you may need to redo this step. Also to make sure this works on your production Heroku app, provide these values as Config Vars on the Settings tab in Heroku.

Testing the API connection

To make sure this works, let’s grab a random dog photo from Unsplash. In the index method of your controller, add the following API call:

@photo = Unsplash::Photo.search("dogs")[0][:urls][:regular]

Let’s break this call down to understand what’s happening:

  • @photo = : we’re defining a variable that will store the photo’s url and make it accessible in the view.
  • Unsplash::Photo.search("dogs"): This is the API call, using the search method and passing along that we’d like to search for dogs. This returns a big chunk of JSON that we then need to parse to get the url of a dog photo. To understand this, view the expected JSON output of the Unsplash API search here.
  • [0][:urls][:regular]: This bit is combing through the JSON. It selects the first photo in the results array, finds the list of that photo’s URLs, and then selects the URL for the regular sized photo.

Next, let’s render that photo in the view. Currently, @photo stores the URL of a random dog photo (could we ask for a better surprise?). To view the photo, head back to index.html.erb and plug that URL into an HTML image tag:

<img src="<%= @photo %>" alt="">

Boot up your server with rails s and refresh localhost. If you see a dog photo, your API connection is working!

Fetching photos from a collection

The project goal is to grab a collection of photos and display them all on a map. To do this, I uploaded several photos to Unsplash and then added them to a new collection on my profile. This allows me to keep this project separated from other photography projects I might pursue in the future.

To fetch all of the photos and their locations from this collection, we’ll need to make a few API calls:

  1. Get the IDs of all photos in a collection
  2. Looping through those IDs, get and store their information in an array.

Replace the current API call in your controller index method with this:

@photos = []
Unsplash::Collection.find('32804345').photos(page=1, per_page=20).each do |p|
@photos << Unsplash::Photo.find(p[:id])

This creates an empty array called @photos , fetches the first 20 photos from collection ID 32804345 (the ID of the collection I just created), and loops through those photos and calls the API again to add their information to the array.

Jumping back to index.html.erb, we can test that this worked by looping through the @photos array and loading the photo into the view.

<% @photos.each do |p| %>
<img src="<%= p[:urls][:regular] %>" alt="">
<% end %>

There’s a few problems with this, however:

  1. We’re making 21 API calls every time the page is loaded. This will quickly deplete the 50 calls/hr allowed in Unsplash’s demo level. This also certainly hurts page performance.
  2. We’re also doing a lot of wrangling of JSON in the view to get the information we want.

To address these issues, I decided to build a simple database that stores just the photo’s URL, description, and coordinates from Unsplash.

Storing photo links in a simple database

Building the database

I’m going to build a database with four attributes that are all strings: description, image_url, latitude, and longitude. Because I’m displaying each of these on a block in New York City, I’ll call the table Blocks. Rails makes this a breeze, just enter this into Terminal:

$ rails generate model Block description:string image_url:string latitude:string, longitude:string

You’ll then need to create and migrate your database by running $ rake db:create db:migrate in Terminal. After pushing your changes to Heroku, you’ll have to do the same in Heroku: $ heroku run rake db:create db:migrate.

Fetching and saving photos on command, instead of on page load

The database can store the photo URLs and provide them on page load, making it possible to call the Unsplash API only when there are new photos in the collection that need to be added to the database. To do this, we’ll first move the API logic to a rake task. A rake task requires a namespace and a method name. In this case, I’ll call them blocks and fetch_all, respectively.

Create a new file in /lib/tasks called blocks.rake. In this file, we’ll do several things:

  1. Loop through the collection and add all photos to an array. To add all, we use the collections [:total_photos] count to create a for loop.
  2. For each photo in the collection, call the API to fetch its details and then use its latitude and longitude to first see if that block already exists in our database. Using find_or_create means we’ll update the block of it exists and create it if it doesn’t.
  3. We’ll then parse the photo’s JSON to find and save the attributes we want to include in our database.
namespace :blocks do
task fetch_all: :environment do
@photos = []
count = Unsplash::Collection.find('32804345')[:total_photos]
pages = count/20.ceil() + 1
for n in 1..pages
Unsplash::Collection.find('32804345').photos(page=n, per_page=20).each do |p|
@photos << Unsplash::Photo.find(p[:id])
@photos.each do |photo|
block = Block.find_or_create_by(latitude: photo[:location][:position][:latitude], longitude: photo[:location][:position][:longitude])
block.description = photo[:description]
block.latitude = photo[:location][:position][:latitude]
block.longitude = photo[:location][:position][:longitude]
block.image_url = photo[:urls][:regular]

There’s a few redundancies in this bit of code that could be cleaned up, but it works.

When you add photos to your Unsplash collection, all you’ll need to do is run the following Terminal command to update your database: rake blocks:fetch_all or, in Heroku, heroku run rake blocks:fetch_all. Super slick.

Displaying photos on the map

So, we have a map and we have a database filled with blocks that each have an image_url and latitude/longitude coordinates. All that’s left is to display those photos on the map.

The rake task created the blocks in the database, so now our controller only needs to get those blocks from the database and provide their information to the view on page load. Returning to our controller, let’s update the index method to replace all of those API calls with a database call:

class WelcomeController < ApplicationController
def index
@blocks = Block.all

Creating and displaying a Mapbox feature set on the map

Now, in the view, we’ll need to work with Mapbox again to display a set of markers (see Mapbox documentation). To display the photos on the map, we need to do two things:

  1. Use the collection of blocks from our database to create a set of features
  2. Display each of those features on the map

Working again in index.html.erb, we’ll first create the feature set by pasting the following snippet within your Mapbox <script> and just below the block where you defined var map = ….

var geojson = {
type: 'FeatureCollection',
features: [
<% @blocks.each do |b| %>
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [<%= b.longitude %>, <%= b.latitude %>]
properties: {
image_url: "<%= b.image_url %>",
<% end %>

This takes the @blocks array that was provided by the controller and provides the photo’s longitude, latitude, and image_url to Mapbox.

Next, we’ll use that feature set to create markers on the map. Add the following just below the snippet we just added:

geojson.features.forEach(function(marker) {
var el = document.createElement('div');
el.className = 'marker';
new mapboxgl.Marker(el)
.setPopup(new mapboxgl.Popup({ offset: 10 })
.setHTML("</p><img src='" + marker.properties.image_url + "'>"))

This creates an element with the marker class for each photo in the database. To make those elements visible on the map, we need to add some styling in application.scss:

.marker {
background-color: pink;
border-radius: 50%;
cursor: pointer;
height: 14px;
width: 14px;

That’s it! Start your server and you should now see a dot on the map for each photo in your database. Clicking the marker on the map will then display the photo using the URL of the image hosted on Unsplash.


I have learned so much from tutorials like these, but often find that the documentation is not entirely clear or perfectly applicable to what I’m trying to do in my own project. I hope you find this tutorial helpful but if there is anything that isn’t clear or if I have missed any detail, please don’t hesitate to contact me on Twitter (@robinsongreig). I will do my best to help you!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store