如何在Google Map infowindow中触发事件?

时间:2012-06-25 07:54:15

标签: google-maps google-maps-api-3

我想在地图上有一个默认标记来指示地址,而用户可以将用户标记拖到他们认为正确的位置。 (适用于某些地图修正情况......)

<script type="text/javascript"><!--
var geocoder;
var map;
var point;
function mapLoad() {
geocoder = new google.maps.Geocoder();
var myOptions = {
  zoom: 16,
  mapTypeControl: false, 
  mapTypeId: google.maps.MapTypeId.ROADMAP
}

map = new google.maps.Map(document.getElementById("map"), myOptions);
var address = "LS2 2RD"; //default postcode
geocoder.geocode( { 'address':address,region:"UK",language:"en"}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    point=results[0].geometry.location;
    map.setCenter(point);
    var defaultMarker = new google.maps.Marker({map: map, position: point}); //default marker
    var marker = new google.maps.Marker({
        map: map, 
        position: point,
  draggable: true
    }); //The marker for users to drag

    var DefaultContent ='<h4>Default Location</h4><h6>You can drag it to anywhere you think it is right or confirm here is the right place</h6><div class="confirm"><input type="button" value="This location is correct"></div>'
    var DefaultInfo = new google.maps.InfoWindow({content: DefaultContent,maxWidth:200});
    DefaultInfo.open(map,marker); //default infowindow

      var TargetContent='<h4>New Location</h4><h6>Are you sure here is the right place?</h6><div class="confirm"><input type="button" value="Yes, I confirm" />'+
      '<input type="button" value="Cancel" onclick="clsMark()" /></div>'; //here cancel button is not working
      var infobox = new google.maps.InfoWindow({content: TargetContent}); //after drag ended, the new infowindow

google.maps.event.addListener(marker, 'drag', function(){
        DefaultInfo.close();
        });
google.maps.event.addListener(marker, 'dragend', function() {
      infobox.open(map, marker);
    });

function clsMark(){if (infobox != null) {infobox.close();}//if user cancel, clear the infowindow, and put the marker back to default position
        marker.setPosition(point);}

  } else {
    alert("Geocode was not successful for the following reason: " + status);
  }
});

}

问题是我无法在infowindow中使用这些按钮。我无法使用以下命令将click事件绑定到按钮:

google.maps.event.addListener(buttonID, 'click', function(){...}

如果我在按钮上添加onclick,我会得到函数未定义的错误,就像上面的代码一样,在这种情况下它表示“clsMark未定义”。

所以我完全不知道如何在infowindow中使用按钮。请帮帮我...

1 个答案:

答案 0 :(得分:1)

你声明clsMark()函数里面传递给geocoder.geocode()的匿名函数,这就是为什么它在全局范围内不可用(onclick处理程序正在寻找它)。

尝试在 geocoder.geocode调用之前移动函数clsMark(),使其对onclick处理程序可见。

至于你尝试使用'addListener(buttonID,..',请注意addListener不能使用ID,你必须提供'object'作为第一个参数,所以这只能使用谷歌地图对象。