使用Javascript v3 API向Google Map添加多个点

时间:2011-07-08 21:51:38

标签: javascript google-maps-api-3

我已经被困在这几天了。我在使用Javascript API的v3向地图添加多个点时遇到问题。

我在SO上阅读了this threadthis thread以及this thread,我发现了一些错误并做了一些修改,但我仍然无法展示任何内容对于map_canvas中的HTML文本。

非常感谢任何帮助。感谢。

代码的当前迭代:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script> 
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script> 
<script type="text/javascript"> 
    $(document).ready(function() { initialize(); });

    function initialize() {
        var map_options = {
            center: new google.maps.LatLng(33.84659,-84.35686),
            zoom: 14,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        var google_map = new google.maps.Map(document.getElementById("map_canvas"), map_options);

        var info_window = new google.maps.InfoWindow({
            content: 'loading'
        });

        var t = [];
        var x = [];
        var y = [];
        var h = [];

        t.push('Location Name 1');
        x.push(33.84659);
        y.push(-84.35686);
        h.push('<p><strong>Location Name 1</strong><br/>Address 1</p>');

        t.push('Location Name 2');
        x.push(33.846253);
        y.push(-84.362125);
        h.push('<p><strong>Location Name 2</strong><br/>Address 2</p>');

        var i = 0;
        for ( item in t ) {
            var m = new google.maps.Marker({
                map:       google_map,
                animation: google.maps.Animation.DROP,
                title:     t[i],
                position:  new google.maps.LatLng(x[i],y[i]),
                html:      h[i]
            });

            google.maps.event.addListener(m, 'click', function() {
                info_window.setContent(this.html);
                info_window.open(map, this);
            });
            i++;
        }
    }
</script> 
<div id="map_canvas" style="width:400px;height:400px;">Google Map</div> 

1 个答案:

答案 0 :(得分:16)

问题在于:

info_window.open(map, this);

应该是:

info_window.open(google_map, this);

因为此处没有名为map的变量。这里的工作版本:http://jsfiddle.net/nrabinowitz/2DBXY/

如果你还没有这样做,请尝试使用像Firebug或Chrome控制台这样的工具 - 调试Javascript几乎不可能没有。