Search code examples
google-mapsgoogle-maps-api-3

How can you customize the contents of popups when you click on built-in locations (not markers) in a map from the Google Maps API?


I'm talking about this sort of pop-up, which appears when you click on a store (etc.) in Google Maps:

Google Maps popup

In my case (a covid-related volunteer project) we want replace the View on Google Maps CTA with a link to a page in our web app, with the store information pre-filled. That may be impossible (pointers welcome if not), but knowing how/whether you can customize the popup at all is the first thing.


Solution

  • As I understand, your intention is replace standard Google Maps info window for POIs with your custom info window information. There is no way to modify predefined info windows of POIs via Google Maps JavaScript API. However, you can prevent the predefined info window of POI and show your own info window instead. For this purpose you should add a click event listener on your map. Each time you click on the POI, the map will trigger an event of type google.maps.IconMouseEvent:

    https://developers.google.com/maps/documentation/javascript/reference/map#IconMouseEvent

    So, if event has placeId information, that means you clicked POI, in this case you can stop propagation of the event to prevent standard info window and create your own info window.

    Have a look at following code snippet

    var map;
    function initMap() {
      map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 17.414571, lng: 78.480922},
        zoom: 19
      });
      var infowindow = new google.maps.InfoWindow();
      map.addListener('click', function(event){
        if (event.placeId) {
          event.stop();
          infowindow.close();
          infowindow.setPosition(event.latLng);
          infowindow.setContent(
            '<div>'
            + '<strong>You clicked place</strong><br>' 
            + 'Place ID: ' + event.placeId + '<br>' 
            + 'Position: ' + event.latLng.lat() + ',' + event.latLng.lng() + '<br>' 
            + 'Some additional content can go here' 
            + '</div>');
          infowindow.open(map);
        }
      });
    }
    #map {
      height: 100%;
    }
    html, body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <div id="map"></div>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap"
        async defer></script>