如何添加一个按钮到谷歌地图infowindow

时间:2014-01-29 16:37:37

标签: javascript google-maps

您好我有以下代码,每次我尝试添加一个按钮它都不起作用。这是我目前的代码。有人可以告诉我如何在点击时添加一个显示警告框的按钮。

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);
  });
});

1 个答案:

答案 0 :(得分:6)

你输了不匹配'

    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);
  });
});

代码段

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>