2

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

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

感谢您的任何建议!

4

1 回答 1

0

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

你必须var marker在你的函数之外定义placeMarker(),就像你用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);

        //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);
于 2013-05-28T13:16:20.643 回答