谷歌地图和标记在地图上

时间:2014-01-22 17:27:50

标签: javascript google-maps google-maps-api-3

我需要在地图上显示标记,并为每个标记显示带有一些信息的弹出窗口。 这是我的代码:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
    var createMap = function() {
        var address = document.getElementById("address").value;
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode( {'address': address}, function(results,status){
            if (status == google.maps.GeocoderStatus.OK) {
                var options = {
                    zoom: 12,
                    center: results[0].geometry.location,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                var map = new google.maps.Map(document.getElementById('map'), options);
                setMarkers(map, sites);
            } 
            else {
                alert("Problema nella ricerca dell'indirizzo: " + status);
            }
        });
    }

    //Aggiungo i marker alla mappa
    function setMarkers(map, markers) {
        for (var i = 0; i < markers.length; i++) {
            var sites = markers[i];
            var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
            var marker = new google.maps.Marker({
                position: siteLatLng,
                map: map,
                title: sites[0],
                zIndex: sites[3],
                html: "<b>"+sites[0]+"</b><br>"+sites[4]
            });

            google.maps.event.addListener(marker, "click", function () {               
                infowindow.setContent(this.html);
                infowindow.open(map, this);
            });
        }
    }

    //Elenco dei marcatori da aggiungere
    var sites = [[ 'Veterinari Associati', 45.448405,9.19823 , 1 , 'Via Palladio 4 - 20100 Milano (MI)'],];


    window.onload = createMap;
</script>
<input id="address" type="hidden" value="Milan">
<div id="map" style="width:345px; height:306px;"></div>

一切都按预期工作,标记被放置但是当我点击市场时弹出窗口就会显示出来。 我无法理解问题出在哪里......

2 个答案:

答案 0 :(得分:2)

你没有初始化infowindow,试试这个

google.maps.event.addListener(marker, "click", function () {  
  var infowindow = new google.maps.InfoWindow();
  infowindow.setContent(this.html);
  infowindow.open(map, this);
});

答案 1 :(得分:1)

这是因为您在设置HTML并打开它之前没有设置信息窗口。插入此内容:

var infowindow = new google.maps.InfoWindow();