Using Custom Markers For google-map-react
In my previous post, I talked about how when you first start using API keys (or anytime afterwards), you should always abstract them away in an external .env file. Afterwards, it should be -gitignored to manually ignore pushing that particular file to your repository, allowing the safe and personal use of one’s own API keys!
This next step is also quite an important one when you’re working with google-map-react.
This particularly library doesn’t come with any out-the-box map markers or pins. Instead, one can display markers as React components like a <div>
. These markers are then styled with CSS, and react just like normal web page elements would be expected to.
The first step is to start with a basic React component:
export default MyMarker = () => (
<div className='myMarker'></div>
)
Then, we move on to styling.
The library for google-map-react doesn’t exactly have the best documentation, but luckily, we can take their first example to learn just how to place a marker:
.myMarker {
position: absolute,
width: 40,
height: 40,
left: -20,
top: -20,
border: 5px solid #f44336,
border-radius: 40,
background-color: white,
text-align: center,
color: #3f51b5,
font-size: 16,
font-weight: bold,
padding: 4
}
Now we’ve got a lovely marker! It’s a little basic looking, however… Let’s try something a bit more traditional:
.myMarker{
position: absolute;
top: 40%;
left: 50%;
margin-left: -115px;
border-radius: 50% 50% 50% 0;
border: 4px solid #fff;
width: 20px;
height: 20px;
transform: rotate(-45deg);
background-color: white;
border-color: #1264DE;`;
}
What’s important to see here is that border-radius
is the main style rule that smooths out our box-y div
, and that transform: rotate()
will rotate where our corners will be. These 2 rules effectively combine to create a traditional map marker from scratch.
As stated before, the documentation for google-map-react… can leave much to be desired. However, it thankfully allows us to take full control of most every detail to our map markers.