Custom Google Maps Info Windows
Part 19 of 48 in API Driven Development With Laravel and VueJSBuilding off of our last tutorial where we added custom markers to the map: https://serversideup.net/custom-markers-google-map/, the next step is to add an info window to these markers when clicked. This should be a pretty quick tutorial since we will just be binding an info window to a marker on click.
Step 1: Open CafeMap.vue
The /resources/assets/js/components/cafes/CafeMap.vue
is where all of our map logic will be located. In the buildMarkers()
method, we create all of the markers. Well we need to bind the info windows to the marker, so this is where our coding will take place.
First, we will need to add an infoWindows
array to the data for the CafeMap.vue
component. We will store all of our info windows in that array so we can call methods on those when needed. Our data should now look like:
data(){
return {
markers: [],
infoWindows: []
}
},
Next, navigate to the buildMarkers()
method in the for
loop. In there, find the marker declaration. Below that, we will add the following code:
/*
Create the info window and add it to the local
array.
*/
let infoWindow = new google.maps.InfoWindow({
content: this.cafes[i].name
});
this.infoWindows.push( infoWindow );
What this does is declare an info window object that declares the name of the cafe. If you look at the Google Docs: Info Windows | Google Maps JavaScript API | Google Developers for info windows, you can add HTML mark up and really customize the look and feel of the info window. We will be doing this in a style update update, but for now, we are just getting an info window to display.
Now, we just need to bind a click to the marker to open the info window. To do that, right below the last code added add:
/*
Add the event listener to open the info window for the marker.
*/
marker.addListener('click', function() {
infoWindow.open(this.map, this);
});
What this does is when the user clicks on the marker, it opens the info window on the map, above this
which is referencing the marker.
When you click on one of the markers on the map, you should see an info window with the name of the cafe it represents like below:
Conclusion
To add an info window is pretty simple, making them look good isn’t hard either since we will be using HTML. The next part of the tutorial, we will be doing a design overhaul and any tweaks I’ll document in that tutorial. For now, enjoy the Google Maps Info Windows on your map and make sure to check out the code here: GitHub – serversideup/roastandbrew