如何获取infoWindow单击标记

时间:2013-05-28 12:40:46

标签: javascript google-maps events infowindow

我想知道当我点击标记时如何打开信息窗口,我认为这是正确的,但不起作用。 这是脚本

var map;
function initialize() {
    navigator.geolocation.getCurrentPosition(function(position){
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
        var coords = new google.maps.LatLng(latitude, longitude);
        var mapOptions = {
            disableDefaultUI: true,
            center: coords,
            mapTypeId: google.maps.MapTypeId.ROADMAP
            };
        map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
        placeMarker();
        var infowindow = new google.maps.InfoWindow();
        google.maps.event.addListener(marker, 'click', function() {
            getComment(marker, infowindow);
      });
});
}
function getComment(marker, infowindow){
    var message = "Hello";
    infowindow.setContent(message);
    infowindow.open(map, marker);
}
function placeMarker() {
    //place some marker
}
google.maps.event.addDomListener(window, 'load', initialize);

感谢您的任何建议!

1 个答案:

答案 0 :(得分:0)

没有在jsfiddle中运行它,但下面的代码应该可以工作。

您必须在函数var marker之外定义placeMarker(),就像使用infoWindow一样。{/ p>

var map;
function initialize() {
    navigator.geolocation.getCurrentPosition(function(position){
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
        var coords = new google.maps.LatLng(latitude, longitude);
        var mapOptions = {
            disableDefaultUI: true,
            center: coords,
            mapTypeId: google.maps.MapTypeId.ROADMAP
            };
        map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

        //position of marker = coords in this example
        var marker = new google.maps.Marker({
            position: coords,
            map: map,
            title: "randomTitle",
            zIndex: Math.round(latlng.lat()*-100000)<<5
        });
        var infowindow = new google.maps.InfoWindow();
        google.maps.event.addListener(marker, 'click', function() {
            getComment(marker, infowindow);
      });
});
}
function getComment(marker, infowindow){
    var message = "Hello";
    infowindow.setContent(message);
    infowindow.open(map, marker);
}
google.maps.event.addDomListener(window, 'load', initialize);