Explain Codes LogoExplain Codes Logo

Google Maps: How to create a custom InfoWindow?

javascript
prompt-engineering
best-practices
responsive-design
Nikita BarsukovbyNikita Barsukov·Oct 28, 2024
TLDR

For rapid Googlers, here's the blueprint to create a custom InfoWindow. You can extend the google.maps.OverlayView, construct your HTML content, put on some CSS styling, and then apply onAdd, draw, onRemove lifecycle methods to manage it on the map.

The illustration in code goes like this:

function CustomInfoWindow(content, position) { this.setPosition(position); // We are not lost, we know our position. google.maps.OverlayView.call(this); // Let's call mom, erm.. I mean OverlayView. this.content_ = content; // The VIP: Our HTML content. } CustomInfoWindow.prototype = Object.create(google.maps.OverlayView.prototype); // Prototype chain magic. CustomInfoWindow.prototype.onAdd = function() { var div = document.createElement('div'); // Bring life to a div! div.style.position = 'absolute'; // We don't go with the crowd. div.innerHTML = this.content_; // Dressing up our div with the VIP. this.div_ = div; this.getPanes().floatPane.appendChild(div); // Let's go to floatPane party! }; CustomInfoWindow.prototype.draw = function() { var projection = this.getProjection(); // "Draw me like one of your French divs!" var pixelPosition = projection.fromLatLngToDivPixel(this.getPosition()); // The never-confused pixelPosition. this.div_.style.left = `${pixelPosition.x}px`; // My X is now my strength. this.div_.style.top = `${pixelPosition.y}px`; // My Y the only limit! }; CustomInfoWindow.prototype.onRemove = function() { this.div_.parentNode.removeChild(this.div_); // This calls for a "Clean Break-Up". }; // Usage var myInfoWindow = new CustomInfoWindow('<p style="color:red;">My Custom Content</p>', myLatLng); myInfoWindow.setMap(map); // Bonding Time with our map, special!

Pro tip: Just like your favourite coffee, custom the setPosition() method to keep InfoWindow with a marker or a specific latitude/longitude.

Exploration of libraries

Extend the realms of custom InfoWindows by deploying third-party libraries like js-info-bubble or InfoBox. These champions will handle the heavy lifting for dynamic styling and refined look.

Diving deep into js-info-bubble

Behold, the js-info-bubble library. Blessed with styling riches, this can create magic beyond default Google Maps InfoWindow. Explore the js-info-bubble repository for your incantation guidebook: example.html.

Adventures with InfoBox

InfoBox expands the horizon of styling that Google Maps InfoWindow API provides. Access it via google-maps-utility-library-v3. To employ InfoBox:

var boxOptions = { content: '<div id="custom-content">My Content</div>', // Personal diary entry here. disableAutoPan: false, // Panning or no panning, mind the drifting content. maxWidth: 0, // Size matters, be careful with that! pixelOffset: new google.maps.Size(-140, 0), // Psssst! I am just offsetting myself. zIndex: null, // Who's the boss? Z-index, apparently. boxStyle: { background: "url('tipbox.gif') no-repeat", // Dress-code? Let's google that! opacity: 0.75, // We are just a little bit shy. width: "280px" // "280px" is the new black! }, closeBoxMargin: "10px 2px 2px 2px", // The lonely corner, but make it fancy. closeBoxURL: "closebutton.gif", // This is your close button, calling it out! infoBoxClearance: new google.maps.Size(1, 1), // The clearance sales are back! isHidden: false, // Hide and seek? Naah, we are more into "seek". pane: "floatPane", // Pane, meet float by the riverbank. enableEventPropagation: false // We don't like gossip, no propagation please. }; var ib = new InfoBox(boxOptions); ib.open(map, marker); // Map sees marker, InfoBox sees everything!

InfoBox can be easily upgraded with additional properties for a custom fit.

Precision with styling

For Google Map's amateur fashion designers, the CSS properties are the new sequins, feathers and tailoring instruments that can craft exquisite InfoWindow.

Creating sharp corners

Banish the rounded corners and welcome sleek and polished square corners InfoWindow. All by just applying CSS to your content div:

#custom-content { border-radius: 0; //Banished, no more rounds! border: 1px solid #ccc; //Just a little glam. /* Your kingdom of styling */ }

Tailoring close button

A smartly designed close button? Yes, please. This can be achieved by the wizardry of CSS:

.infoBoxClose { background: url('custom-close.png'); // Ssssh... Where is close button? width: 16px; // The "just-right" size. height: 16px; // We don't compromise on height. }

Making arrow visible

Out with the clutter and on with minimalist design! Remove the pointer arrow under the InfoWindow as follows:

infoWindowOptions.pixelOffset = new google.maps.Size(0, -25); // See the arrow? Now you don't.

Compatibility and interactive functions

Compatibility is not just for relationships, ensure your custom InfoWindows get along well with Internet Explorer.

For interactive fun, jQuery and vanilla JavaScript are your best friends to enhance domready event:

google.maps.event.addListener(infoWindow, 'domready', function() { // The party starts after InfoWindow gets ready! });

Time for handson

Dive into the world of samples! The Dive Seven allows you to discover great examples of customized InfoWindows using InfoBubble library. Don't forget the z-index and element hierarchy when dressing up your custom InfoWindows.

Flex your skills at a JS Fiddle playground to witness the birth of your InfoWindow transformations!

Nailing the best practices

While you journey through the customs of custom InfoWindows, be mindful of the clean code standards and anticipate challenges. The beter you prepare, the better the results.

Clean coding standards

Keep your JavaScript, CSS, and HTML distinct for easy maintainance and debugging.

Future proofing

When the future strikes with challenges like managing multiple InfoWindows, responsive design for mobile devices, and accessibility standards, be ready!