Google Map API - foreach 循环中的信息窗口

Google Map API - infowindow in foreach loop

本文关键字:信息 信息窗 窗口 循环 Map API foreach Google      更新时间:2023-09-26

您好,我正在从 SqlServerCe 检索数据,所以我创建了 foreach 循环来创建标记 - 它可以创建多个标记,但现在我想在每个标记中添加一个信息窗口。但是现在每当我单击标记时,信息窗口都会在最后创建的标记上弹出。

<script>
function initialize() {
    var mapProp = {
        center:new google.maps.LatLng(51.508742,-0.120850),
        zoom:5,
        mapTypeId:google.maps.MapTypeId.ROADMAP
    };
    var map=new google.maps.Map(document.getElementById("googleMap")
      , mapProp);
    $(function () {
 @foreach (var row in data)
 {
   <text>
        var marker = new google.maps.Marker({ position: new google.maps.LatLng(@row.GeoLat,  @row.GeoLong),
            map: map });
        marker.info = new google.maps.InfoWindow({
            content: "test"
        });
        google.maps.event.addListener(marker, 'click', function() {
            marker.info.open(map, marker);
        });
        </text>

 }
    });
}

google.maps.event.addDomListener(window, 'load', initialize);

有人可以帮助我为每个创建的标记添加信息窗口吗?

感谢您的回复和时间。

这就是我从 SqlServerCe 加载的方式

var db = Database.Open("StarterSite");
var data = db.Query("SELECT DescriptionService,GeoLong,GeoLat FROM services");
var array = new []{data} ;

您可以使用以下内容,用javascript编写

var infoWindowContent = [];
for(var index=0; index< places.length; index++){
        infoWindowContent[index] = getInfoWindowDetails(places[index]);
        var location = new google.maps.LatLng(places[index].latitude,places[index].longitude);
        bounds.extend(location);
        marker = new google.maps.Marker({
            position    : location,
            map         : map,
            title       : places[index].title
        });
        google.maps.event.addListener(marker, 'click', (function(marker,index){
            return function(){
                infoWindow.setContent(infoWindowContent[index]);
                infoWindow.open(map, marker);
                map.setCenter(marker.getPosition());
                map.setZoom(15);
            }
        })(marker,index));
    }   

    function getInfoWindowDetails(location){
        var contentString = '<div id="content" style="width:270px;height:100px">' +
                            '<h3 id="firstHeading" class="firstHeading">' + location.title + '</h3>'+
                            '<div id="bodyContent">'+
                                '<div style="float:left;width:100%">'+ location.address + '</div>'+
                            '</div>'+
                        '</div>';
        return contentString;
    }

我添加了一个数组infoWindowContent然后将信息添加到数组中。您可以使用相同的逻辑