【问题标题】:using values of a javascript array outside of a function在函数外使用 javascript 数组的值
【发布时间】:2011-05-03 22:10:09
【问题描述】:

我有一个 forloop,其中调用了一个函数。在该函数中,我将值推送到称为标记的数组。

有没有办法在 forloop 之外访问标记数组的值?

代码如下:

<script type="text/javascript"> 
    // arrays to hold copies of the markers and html used by the side_bar 
    // because the function closure trick doesnt work there 
    var map = null;
    geocoder = new google.maps.Geocoder();
    var side_bar_html = ""; 
    var icon = '';
    var markers = [];

    function codeAddress(this_address,index,callback) {
        geocoder.geocode( { 'address': this_address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                callback.call(window,index,results[0].geometry.location)
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });
    }


    function initialize() {
        // create the map
        var myOptions = {
            zoom: 3,
            center: new google.maps.LatLng(46.90, -121.00),
            mapTypeControl: true,
            mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
            navigationControl: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }

        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        google.maps.event.addListener(map, 'click', function() {
            infowindow.close();
        });


        for (var i = 0; i < businesses.length; i++) {
            codeAddress(businesses[i].address,i,function(i,point){
                var description = businesses[i].description;

                if(businesses[i].business_type == "Wine"){
                    //http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=A|00CC99|000000
                    icon = 'http://google-maps-icons.googlecode.com/files/wineyard.png';
                }else if(businesses[i].business_type == "Golf"){
                    icon = 'http://google-maps-icons.googlecode.com/files/golf.png';
                }else{
                    icon = 'http://google-maps-icons.googlecode.com/files/festival.png';
                }

                var marker = createMarker(point,businesses[i].name,description,icon);

                // put the assembled side_bar_html contents into the side_bar div
                document.getElementById("side_bar").innerHTML = side_bar_html;
            });//End codeAddress-function
        }//End for-loop

        console.log(markers);
        var markerCluster = new MarkerClusterer(map, markers);               

    }

    // A function to create the marker and set up the event window function 
    function createMarker(latlng, name, html,icon) {
        var contentString = html;
        var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            icon: icon,
            zIndex: Math.round(latlng.lat()*-100000)<<5
            });

        google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent(contentString); 
            infowindow.open(map,marker);
        });

        // save the info we need to use later for the side_bar
        markers.push(marker);

        // add a line to the side_bar html
        side_bar_html += '<a href="javascript:myclick(' + (markers.length-1) + ')">' + name + '<\/a><br />'+html+'<br />';

    }

    var infowindow = new google.maps.InfoWindow({ 
        size: new google.maps.Size(150,50)
    });

    // This function picks up the click and opens the corresponding info window
    function myclick(i) {
        google.maps.event.trigger(markers[i], "click");
    }

</script>

如您所见,最后一行显示“var markerCluster = new MarkerCluster(map, markers);”这是我希望能够从中访问信息的地方。

谢谢!

【问题讨论】:

  • 看起来您缺少几行代码来显示函数以及数组的声明方式。
  • 我更新了代码以显示更多内容。

标签: javascript google-maps maps google-api


【解决方案1】:

问题是您没有考虑到对codeAddress 的调用的异步性质。您在循环中调用该函数,这会触发对 Google Maps API 的一系列调用。

你正在运行这一行:

var markerCluster = new MarkerClusterer(map, markers);

...甚至在回调被触发之前。

要修复,请维护一个计数器。每次触发回调时,该计数器都会增加 1。一旦它等于businesses.length,您就知道所有地址都已进行地理编码,并且所有标记都已添加到数组中。现在您可以创建MarkerCluster

【讨论】:

  • 到目前为止,您的回答似乎是最有意义的,但是我将把计数器放在哪里以及在哪里创建 MarkerCluster?
【解决方案2】:

是的,在 for 循环之前声明它。

var markers
for(....

【讨论】:

  • 我试过这个,但好像forloop中的函数正在清除标记数组或其他东西。
【解决方案3】:

将标记的定义带到 for 循环之外 ...

var markers = new Array ();
for (var i = 0; i < businesses.length; i++) {
    markers[i] = ...

【讨论】:

  • 我试试这个,但它就像函数之后清除数组一样
  • 标记的值被分配给标记数组。
  • 您不会返回由 createMarker 函数创建的标记。另外,不是 var marker = createMarker ( ... ),而是 --> marker [ i ] = createMarker ( ... )
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多