在javascript中可以有多个具有相同名称的对象吗?

时间:2016-06-23 06:28:55

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

我一直在阅读谷歌地图api中的功能关闭。他们使用以下示例:



function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 4,
          center: {lat: -25.363882, lng: 131.044922 }
        });

        var bounds = {
          north: -25.363882,
          south: -31.203405,
          east: 131.044922,
          west: 125.244141
        };

        // Display the area between the location southWest and northEast.
        map.fitBounds(bounds);

        // Add 5 markers to map at random locations.
        // For each of these markers, give them a title with their index, and when
        // they are clicked they should open an infowindow with text from a secret
        // message.
        var secretMessages = ['This', 'is', 'the', 'secret', 'message'];
        var lngSpan = bounds.east - bounds.west;
        var latSpan = bounds.north - bounds.south;
        for (var i = 0; i < secretMessages.length; ++i) {
          var marker = new google.maps.Marker({
            position: {
              lat: bounds.south + latSpan * Math.random(),
              lng: bounds.west + lngSpan * Math.random()
            },
            map: map
          });
          attachSecretMessage(marker, secretMessages[i]);
        }
      }

      // Attaches an info window to a marker with the provided message. When the
      // marker is clicked, the info window will open with the secret message.
      function attachSecretMessage(marker, secretMessage) {
        var infowindow = new google.maps.InfoWindow({
          content: secretMessage
        });

        marker.addListener('click', function() {
          infowindow.open(marker.get('map'), marker);
        });
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
&#13;
html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
&#13;
 <div id="map"></div>
&#13;
&#13;
&#13;

他们在每次循环迭代中定义marker变量。

  

问题:为什么在前一个声明中声明的marker被下一个循环迭代中声明的marker覆盖?为什么地图上会显示多个标记?由于只有一个marker变量,因此地图上只能显示一个`标记。

3 个答案:

答案 0 :(得分:1)

marker是一个变量,每次循环迭代时,都会创建一个新对象 使用新的运算符

现在,每次标记变量更新时,它都会引用不同的对象,只是变量赋值更改,对象仍在内存中

考虑一个例子

var student = {
marks: 100
}

var student1 = student;
student = {
marks: 200
}

console.log(student1.marks); //100
console.log(student.marks); //200

看到obects仍在内存中,只有我的学生变量引用更改

答案 1 :(得分:1)

Marker仍被覆盖,但在这种情况下,它并不重要,因为他们并未再次引用这些对象。我可以在一个循环中声明一个变量,然后立即执行一个动作,但只要我不需要在循环之外引用每个单独的对象,它们仍然应该服务于它们的目的,在这种情况下是显示标记并显示秘密消息。例如,在下面的代码中,我使用相同的变量来制作5个按钮,一旦我将它们悬停在每个按钮上,每个按钮都会提醒我我已经徘徊。

var buttons = ['button1', 'button2', 'button3', 'button4', 'button5'];

    for(var i = 0; i < buttons.length; ++i)
    {
        var btn = document.createElement("BUTTON");
        var t = document.createTextNode(buttons[i]);
        btn.appendChild(t);           
        document.body.appendChild(btn); 
        hover(btn, buttons[i]);
    } 

    function hover(thing,text)
    {
        thing.addEventListener('mouseover',function(){alert("hovered over "+ text);});
    }

答案 2 :(得分:0)

你好我之前想过这个问题。有时我必须从标记传递特定参数,所以我将标记放入数组并通过索引控制标记。这是我的代码剪辑。

  var markersArray = []; //goolge map array
        function GmapCreateMaker(index, x, y, content, iconurl) { //creat Goole map icon
            var myLatlng = new google.maps.LatLng(y, x);
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map
            });
            markersArray.push(marker);
            if (index == alldataarr.length - 1) {//Check All GMAP ICON ARE PUT INTO ARRAY
                showOverlays();
            }
        }
        function showOverlays() {  //put gmap icon on map
            for (i in markersArray) {
                markersArray[i].setMap(map);
            }
        }