Get startedGet started for free

Labels and Pop-ups

1. Labels and Pop-ups

Now that we're working with hundreds of markers, it is impossible to remember what each one represents. To help remind us, we can add either pop-ups or labels. Let's take a look at how we can add these features efficiently.

2. Piping and the ~ Operator

There are several ways to write the code for your leaflet maps. The approach on the left pipes our data into the leaflet() function. I find this approach more readable and like that it prevents us from repeatedly specifying the data frame name, like the alternative on the right. When piping data in leaflet() you will often see the tilde operator. The tilde allows us to quickly refer to variables from our piped data. There is one more difference in the code, can you spot it?

3. All the Colors

That's not a new cool hashtag we haven't heard of, it's a hex code. Hex, or hexadecimal, uses base 16 rather than base 10. This allows two digits to represent a number that in the more common decimal system ranges from 0 to 255. This is handy because that's the range that colors take in the full RGB spectrum. For example, FF 00 00 has the value of 255 for red, 0 for green, and 0 for blue. So, how do we get from FF to 255? The letter F is the sixth letter in the alphabet and represents the number 15. A represents 10, B 11, and so. The location of the number or letter is also important. The character furthest to the right is in the zero position and the next character is in the first position. To convert to the decimal system, we take 16 to first power times the number in the first position and then add 16 to zero power times the number in the 0 position. If you ever need help finding the right hex code for a color, Google it and you will be shown the color along with a slider to adjust it.

4. Building a Better Pop-up

Enough math for now; back to making maps! We've been adding pop-ups with a single piece of information. We can provide our users with two or three data elements using the paste0() function. paste0() converts its arguments to characters and joins them together into a single string that we can present in a pop-up. Taking our design one step further, we can use a few html tags to customize the appearance of our pop-ups.

5. Labels

Pop-ups are great, but they require a little extra work and sometimes we don't want to click the mouse again. As you see in the map, when we use labels, we get the same information with a simple hover. You'll also notice a trick to quickly zoom the map is to hold shift to draw a rectangle.

6. Let's practice!

Now it's your turn, give it a try on one of your maps.