不确定为什么在Google地图的监听器事件中值未定义

时间:2015-11-18 16:29:01

标签: javascript arrays google-maps undefined infowindow

我试图从数组数组中获取一个字符串。我想将第一个属性[0]放入信息窗口。我可以使用第二个和第三个值来设置标记的位置,我也可以在console.log中获得第一个值。

特定的JavaScript代码在这里:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
   <tr>
     <td>
	   <input  class="quantity_input" />
	 </td>
	 <td>
	   <input  class="price_input" />
	 </td>
	 <td>
	   <input  class="totl_input" />
	 </td>
   </tr>
   <tr>
     <td>
	   <input  class="quantity_input" />
	 </td>
	 <td>
	   <input  class="price_input" />
	 </td>
	 <td>
	   <input  class="totl_input" />
	 </td>
   </tr>
   <tr>
     <td>
	   <input  class="quantity_input" />
	 </td>
	 <td>
	   <input  class="price_input" />
	 </td>
	 <td>
	   <input  class="totl_input" />
	 </td>
   </tr>
   </table>

当我markers = [ ["4841 Bethesda Avenue (Elm Street)", 38.980724, -77.0964], ["7171 Woodmont Avenue", 38.980097, -77.093662], ["921 Wayne Avenue", 38.995740, -77.025652], ["801 Ellsworth Drive",38.997778, -77.025071] ]; infoWindow = new google.maps.InfoWindow() for (var i = 0; i < markers.length; i++) { console.log("markers: " + markers[i][0]); position = new google.maps.LatLng(markers[i][1], markers[i][2]); marker = new google.maps.Marker({ position: position, map: map, title: markers[i][0] }); console.log("markers 2: " + markers[i][0]); google.maps.event.addListener(marker, 'click', function () { infoWindow.setContent("<div>Hello, World" + markers[i][0] + "</div>"); infoWindow.open(map, this); }); }; 它产生我想要的东西时。但是,一旦它进入console.log(markers[i][0])事件,就会失去它,我不确定原因。

为什么它变得不确定?

Fiddle here.

HTML:

addListener

CSS:

<h1 style="text-align: center;">Parking Garage Availability</h1>

<div id="map"></div>

<ul id="list"></ul>
<p id="GAR57"></p>
<p id="GAR31"></p>
<p id="GAR60"></p>
<p id="GAR61"></p>

JavaScript的:

#map {
    height: 300px;
    width: 500px;
    margin: 0 auto;
    border: 1px solid black;
}

1 个答案:

答案 0 :(得分:0)

Markers [i] [0]变得未定义,因为它在addListener中的函数范围内不存在,即您没有将标记传递给函数。

相反,您传递标记

 for (var i = 0; i < markers.length; i++) {
    console.log("markers: " + markers[i][0]);
    position = new google.maps.LatLng(markers[i][1], markers[i][2]);
    marker = new google.maps.Marker({
        position: position, 
        map: map,
        title: markers[i][0]
    });
    console.log("markers 2: " + marker.title);
    google.maps.event.addListener(marker, 'click', function () {
        infoWindow.setContent("<div>Hello, World " + marker.title + "</div>");
        infoWindow.open(map, this);
    });
};

This显示了单击标记时显示标题的示例。我假设的是你想要实现的目标。