codingman codingman - 2 months ago 41
Javascript Question

How to add a button to google maps infowindow

Hi I have the following code and everytime I try to add a button it doesn't work. This is the code I have at the moment. Could someone please show me how to add a button that shows an alert box when clicked.

var infowindow = new google.maps.InfoWindow({
content: " "
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<p>Event Name: '+this.title+'</p>' +
'<p>Event Type: '+this.etype+'</p>' +
'<p>Cause: '+this.cause+'</p>' +
'<p>Date: '+this.date+'</p>' +
'<p>Time: '+this.time+'</p>' +
'<button onclick="myFunction()"> 'Click me'</button>');


infowindow.open(map, this);
});
});

Answer

You have mismatched '

    var infowindow = new google.maps.InfoWindow({
    content: " "
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent('<p>Event Name: '+this.title+'</p>' +
            '<p>Event Type: '+this.etype+'</p>' +
            '<p>Cause: '+this.cause+'</p>' +
            '<p>Date: '+this.date+'</p>' +
                '<p>Time: '+this.time+'</p>' +
                '<button onclick="myFunction()">Click me</button>');


    infowindow.open(map, this);
  });
});

code snippet:

var infowindow;

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var marker = new google.maps.Marker({
    position: map.getCenter(),
    map: map
  });

  infowindow = new google.maps.InfoWindow({
    content: " "
  });

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent('<p>Event Name: ' + this.title + '</p>' +
      '<p>Event Type: ' + this.etype + '</p>' +
      '<p>Cause: ' + this.cause + '</p>' +
      '<p>Date: ' + this.date + '</p>' +
      '<p>Time: ' + this.time + '</p>' +
      '<button onclick="myFunction()">Click me</button>');
    infowindow.open(map, this);
  });
  google.maps.event.trigger(marker, 'click');
}
google.maps.event.addDomListener(window, "load", initialize);

function myFunction() {
  infowindow.setContent('<div style="background-color: green">' + infowindow.getContent() + "</div>");
}
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>