1

我正在做我的第一个谷歌地图项目。我有多个标记出现,并且还使用了自定义标记。但是,单击标记时我无法使信息窗口工作!任何人都可以帮忙吗?

单击标记时,什么也没有发生 - 它甚至没有进入函数(我设置了控制台日志)。

<script type="text/javascript">

var map,
    geocoder,
    bounds,
    address,
    marker = [],
    myLatlng = new google.maps.LatLng(40, -74);

function initialize() {

    var mapOptions = {
        center: myLatlng,
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: false,
        scrollwheel: false,
        navigationControl: true,
        mapTypeControl: false,
        scaleControl: true,
        draggable: true
    };


    //styles
    var styles = [{
    "elementType": "geometry.fill",
    "stylers": [
        { "visibility": "on" },
        { "hue": "#FF0000" },
        { "weight": 2 },
        { "gamma": 1 },
        { "lightness": 20 },
        { "saturation": 50 }
        ]
    }];


    map = new google.maps.Map(document.getElementById('map'), mapOptions);

    geocoder = new google.maps.Geocoder();

    map.setOptions({styles: styles});


    var buildings = [
            '76 Ninth Ave, New York, NY ‎',
            '825 8th Ave, New York, NY ',
            '127 E 23rd St, New York, NY ‎'
];



    var contentString = '<div id="content">test</div>';

    var infowindow = new google.maps.InfoWindow({
            content: contentString      
        });

    var marker = {url:'<?php echo site_url(); ?>/wp-content/themes/theme/img/pointer2.png', scaledSize:new google.maps.Size(45, 72)};


    for (var i = 0; i < buildings.length; ++i) {
        (function(address) {
            geocoder.geocode({ 'address': address }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                     marker += new google.maps.Marker ({
                            map: map,
                            position: results[0].geometry.location,
                            icon: marker

                    });
                };
            });
        })(buildings[i]);
    };

    google.maps.event.trigger(map, 'resize');

    google.maps.event.addListener(marker, 'click', function() {
        console.log("test3");
        infowindow.open(map,marker);

        map.setZoom(8);
        map.setCenter(marker.getPosition());
    });

};


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

4

1 回答 1

2

我认为首先你必须在循环内移动 click eventListener 。您在顶部有一个标记数组,但您正在用 覆盖它var marker = {url:'<?php echo site_url(); ?>...,所以我们暂时将其称为“yourIcon”。此外,在循环中,您将所有标记添加到一个字符串中,就我而言,这没有任何意义;)

在循环中,您必须将 eventListener 附加到每个标记。

for (var i=0; i < buildings.length; i++) {
    // Create a new lexical scope by "copying the buildings"
    (function(address) {
        geocoder.geocode({ 'address': address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                // Create the marker
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });

                // Create the info window
                var infowindow = new google.maps.InfoWindow({
                    content: address
                });

                // Add the eventListener
                google.maps.event.addListener(marker, 'click', function() {
                    infowindow.open(map, this);
                    map.setZoom(12);
                    map.panTo(this.getPosition());
                });                   
            };
        });
    })(buildings[i]);
}


你可以在这里看到工作小提琴

PS
你已经在你的问题中避免了闭包问题,我只是厌倦了看到它;)
这是一种解释闭包的方法:JavaScript闭包如何工作?


编辑 1:Wordpress
为了在 wordpress 中进行这项工作,您不必做太多事情。我建议在您的建筑物数组中使用对象,这样您就可以轻松访问更多数据。

这就是您的建筑物阵列的样子:

var buildings = [
    { address: '76 Ninth Ave, New York, NY‎', title: "Test 1" },
    { address: '825 8th Ave, New York, NY‎', title: "Test 2" },
    { address: '127 E 23rd St, New York, NY‎', title: "Test 3" }
];

循环:

<?php if ( have_posts() ) : ?>
    <?php $postCount = 0; ?>
    var buildings = [
    <?php while ( have_posts() ) : the_post(); ?>
        <?php $postcount++; ?>
        { address: '<?php customMetaAddressHere; ?>', title: '<?php the_title(); ?>', link: '<?php the_permalink(); ?>', }
        <?php if($postCount < sizeof($posts)) { ?>
        ,
        <?php } ?>
    <?php endwhile; ?>
    ];
<?php else : ?>
    var buildings = [];
<?php endif; ?>

将您的 Google 标记循环更改为:

(function(building) {
    geocoder.geocode({ 'address': building.address }, function(results, status) {
        // You have access to buildings.title as well
        ...
    });
})(buildings[i]);

这是未经测试的,但你可以在这里看到我的意思。


编辑 2:只有一个活动的信息窗口
如果您希望一次只打开一个信息窗口,最好在循环之外创建它,并且只在标记单击时更改它的内容和位置:

// Create the info window
var infowindow = new google.maps.InfoWindow();

for (var i=0; i < buildings.length; i++) {
    // Create a new lexical scope by "copying the buildings"
    (function(building) {
        geocoder.geocode({ 'address': building.address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                // Create the marker
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });

                // Add the eventListener
                google.maps.event.addListener(marker, 'click', function() {
                    infowindow.setContent("<b>" + building.title + "</b><br> " + building.address);
                    infowindow.setPosition(this.getPosition());
                    infowindow.open(map, this);
                    map.setZoom(12);
                    map.panTo(this.getPosition());
                });               
            };
        });
    })(buildings[i]);
}

你可以在这里找到一个工作小提琴。

于 2013-09-27T22:31:30.030 回答