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

问题描述:

我想在地图上有一个默认标记来表示地址,而用户可以将用户标记拖动到他们认为正确的地方。 (在某些地图整改情况适用...)如何在Google Map infowindow中触发事件?

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

}

的问题是,我不能让那些按钮,在信息窗口的工作。如果我的onclick添加到一个按钮,就像上面的代码,在这种情况下,它说:“clsMark没有定义”

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

我得到的功能没有定义的错误:我不能click事件绑定到使用按钮。

所以我完全不知道如何让按钮在infowindow中工作。请帮我...

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

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

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