- Luke Johnson
- April 26, 2019
- Ask a question
- Email Luke
Google has made it fairly straightforward to create custom maps you can embed into a website. This is really useful if you want to show multiple locations for your store, all the churches in your diocese, your favourite coffee spots, or if you're looking for a really nerdy way to show every place you ever got a bee sting.
This guide isn’t fully comprehensive, since there are a lot of additional options you could invoke. But this is what you need to get a basic multi-point map running.
Get an API key.
With your key in hand, you’re ready to get coding.
1. A couple lines of HTML and JS.
That’s the basics.
2. Get your map data.
- coordinates (latitude and longitude)
- unique id
And a few more, which are used when we activate the marker’s pop-up info window.
- image (if you need one)
Retrieve your location data and store it in a
Note: You can create a custom HTML string for each marker, giving you total control over the info window that will display when you click on a marker.
3. Create a new script where the map will be built.
A few things happen in this new script, which are important to notice.
- A new instance of Google Maps is stored to
var mapinside the
initMap()is called by the first script we put in the page.)
map’s options, you can set the centering point of the map using latitude and longitude.
- We loop through the locations saved to
markersin order to add each marker to the map.
- An “info window” is created (the pop-up you see when you click on a marker).
bindInfoWindow()function binds the info window to its marker.
At this point, you will have a functioning map. However, it needs some enhancement. Left in this state, each info window will stay open even as you click new markers. Next we will add a function that will close previously opened info windows.
4. Close the unnecessary windows.
closeOtherWindows() makes it possible to close previously opened info windows so that the screen doesn’t fill up with them. The function checks to see if the
Windows array has at least 1 element in it. If it does, the
.close() method is called, which closes the open window (predictably), and resets the array count to 0.
closeOtherWindows(); is called within
infowindow.open() so that previously opened windows are closed before a new one is opened.
infowindow.open() runs, the window instance is added to
Windows array so that it can be closed next time an info window is requested.