未捕获的参考错误:未定义无

时间:2013-05-06 17:48:44

标签: javascript google-maps jinja2

javascript新手。尝试添加标记列表(从python)到谷歌地图。

我的原始Jinja2模板:

<head>
<title>Google Map Test</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
    #map-canvas { height: 700px; width: 400px; }
</style>

<script type="text/javascript"
  src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&sensor=false">
</script>

<script type="text/javascript">
  var locations = {{ locations|safe }};

  /* 
  locations|safe results in the following line in my rendered template:
  var locations = [['A.W. Hastings / Windows & Doors by Brownell', '44.4456', '-73.1276'], ['AARP', '44.4757', '-73.2113'], ['Adirondack Audiology', '44.4792', '-73.22'], ['Alchemy Jewelry Arts #1A', '44.4672', '-73.2147'], ['All Smiles Dental', '44.2334', '-72.5539']];
  */

  function initialize() {
    var mapOptions = {
      center: new google.maps.LatLng(43.953, -72.593),
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map-canvas"),
        mapOptions);
  }

  var infowindow = new google.maps.InfoWindow();

  var marker, i;

for (var i = 0; i < locations.length; i++) {
    marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
    });

    google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
            infowindow.setContent(locations[i][0]);
            infowindow.open(map, marker);
        }
    })(marker, i));
}
</script>

我从我的视图中发送列表“位置”,因为列表会定期更改。

我收到了我定义locations变量的行的Uncaught Reference Error。完整输出是:

未捕获的ReferenceError:无定义127.0.0.1:14 (匿名函数)

2 个答案:

答案 0 :(得分:1)

在函数内移动函数initialize()后面的代码,否则变量map在您访问它的时间和位置不可用。

答案 1 :(得分:0)

我的“位置”模板标记有超过300个项目。为简单起见,我截断了列表。这删除了作为问题根源的违规“无”。

我做了Molle博士推荐的更改并返回并删除了任何带有“无”作为属性的列表项,一切都运行良好。