How to add a full screen button to MapKit JS
This week, I've been working on a new multimedia mode for the blog that I call
Spots, which are essentially map pins of places I visit.
Rather than merely list all of my Spot posts one-at-a-time as
reverse-chronological posts, I also wanted to make a single interactive map that
aggregated all my annotations in one place so that readers could explore them
spatially. Because I'm a tool for all things Apple, I decided to use the MapKit
JS framework they
introduced in 2018 for the job.
All told, it was actually pretty easy to get up-and-running and the documentation
(while sparse) told me what I needed to do to get a map rendered, centered, and
loaded with annotations.
One thing the docs didn't tell me however, was how to let users make a map
full screen, and the reason the docs don't mention it is because framework
doesn't support it. And that's quite a bummer when your layout's maximum width
is as narrow as it is on this humble blog.
So this morning, I figured out a way to hack together a full-screen button that
aped the Maps UI's look-and-feel for MapKit JS. Since it's an odd omission, I
figured it might be useful to somebody out there if I did a quick show-and-tell
on how I did it.
Here's what the button does, before and after clicking it:
Interested? Well, here's what the recipe calls for:
- An absolute-positioned div inside the parent element of the map, styled to
look like a button and with a couple full-screen zoom icons from Tailwind's
excellent Heroicons project
- A click handler that that toggles a bunch of
Tailwind classes to switch the map's parent div
between its regular and fixed full-screen display (also swapping the button icon)
- A keyup handler that listens for escape key and—if any maps are
full-screened—will exit full screen. This felt necessary while I was testing,
because the shrink button can be an awful far distance for one's mouse to travel
Let's dive in and find out…