谷歌地图,addlistener无法正常工作

问题描述 投票:1回答:1

我在一个项目中使用谷歌地图,我想在地图上显示一些可点击的标记,每个标记都显示一个具有不同数据的Div,所以我通过从数据库中获取数据并且运行良好来开始我的代码,然后我在地图上显示如下:

    showHazardsOnMap(result);

    function showHazardsOnMap(hazards) {
    var imgHzr = {
        url: "images/hazardPointer.png", // url
        scaledSize: new google.maps.Size(60, 60), // scaled size
        origin: new google.maps.Point(0, 0), // origin
        anchor: new google.maps.Point(0, 0)
    };

    setMapOnAll(null);
    for (var i = 0; i < hazards.length; i++) {
        markerHzr = new google.maps.Marker({
            position: { lat: hazards[i].Hazard_Lat, lng: hazards[i].Hazard_Long     },
            map: map,
            icon: imgHzr,
            animation: google.maps.Animation.DROP
        });
        showHazardDetails(marker, hazards[i]);
        }
        }
    }

    function showHazardDetails(mark, data) {
        google.maps.event.addListener(mark, 'click', function () {  
            alert("clicked!!!!!!!!!!!!!!!!");
            $("#hazardID").html(data.Hazard_ID);
            $("#hazardImgInfo").attr("src", data.Hazard_Image);
            $("#pDate").html(data.Hazard_DateTime);
            $("#pDes").html(data.Hazard_Description);
            $(".hazardInfo").fadeIn(1000);
        });
    }

好的,现在我可以看到地图上的标记,当我点击标记时,警报(“点击!!!”)工作,但它没有显示我想要看到的Div,有时它甚至没有显示我警报。

我会附上HTML的一部分,CSS可能会有所帮助

.hazardInfo {
width: 80%;
height: 80%;
background-color: #f5821f;
z-index: 2000;
position: fixed;
top: 10%;
right: 10%;
opacity:0.9;
text-align: center;
display: none;
border: none;
border-radius: 10px;    
}


<div class="hazardInfo">
    <p id="hazardID"></p>
    <img src="images/backbtn.png" class="backButton" /><br>
    <p id="pDate" style="font-size:18px; margin-top:11%;"></p><br>
    <img src="images/156.jpg" id="hazardImgInfo" style="height: 40%; width: 90%; border-radius:15px;"><br>
    <p id="pDes" style="font-size:17px; margin-top:4%; margin-right:4%; width:90%;"></p><br>
    <div id="thumbsUp">הוסף לרשימה</div>
</div>
javascript jquery google-maps google-maps-api-3
1个回答
1
投票

您的代码崩溃,因为当侦听器调用时,markinfowindow的值已经更改。你可以试试这样的东西(只需更改showHazardDetails函数):

function showHazardDetails(mark, data) {
    google.maps.event.addListener(mark, 'click', function () {  
        alert("clicked!!!!!!!!!!!!!!!!");
        console.log (mark);
        console.log (data);
    });
}

通常,markdata的输出总是相同的。

为了传递标记,contentString和infowindow的实际值,您必须创建一个IIFE。像这样,变量的值将被复制到函数内:

function showHazardDetails(mark, data) {
    (function (zmark, zdata) {
    google.maps.event.addListener(zmark, 'click', function () {  
        alert("clicked!!!!!!!!!!!!!!!!");
        $("#hazardID").html(zdata.Hazard_ID);
        $("#hazardImgInfo").attr("src", zdata.Hazard_Image);
        $("#pDate").html(zdata.Hazard_DateTime);
        $("#pDes").html(zdata.Hazard_Description);
        $(".hazardInfo").fadeIn(1000);
    });
    })(mark, data);
}

你可以看看how closures work

如果您有疑问,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.