谷歌地图与流星不工作

时间:2013-05-05 11:07:39

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

对于我的项目,我需要google maps api。 我只是可以通过脚本标签来提供api,所以我尝试了类似的东西。

我的HTML:

<head>
  <title>app</title>
  <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">    </script>
</head>

<body>
  {{> hello}}
</body>

<template name="hello">
  <div id="map-canvas"/>
</template>

我的js:

if (Meteor.isClient) {

  var mapOptions = {
      center: new google.maps.LatLng(-34.397, 150.644),
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

  var map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);    
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}

执行时错误是: 未捕获的ReferenceError:谷歌未定义

我怎样才能使这个工作?

1 个答案:

答案 0 :(得分:6)

流星脚本通常在加载Google地图API之前运行,因此最好将您的代码放入Template.rendered:请参阅流星文档中的Template.rendered

例如,如果您有模板

<template name="maps">
    <div id="map-canvas"></div>
</template>

你的js会是:

Template.maps.rendered = function() {
    var mapOptions = {
        center: new google.maps.LatLng(-34.397, 150.644),
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map-canvas"),
        mapOptions);   
}

这实际上更多地取决于模板的外观。每当模板发生反应性更改时,渲染的回调将重新运行。因此,如果您发现它重新渲染,您可能必须使用Session哈希来检查它,它只设置一次地图中心/设置。

另一种选择是将地图居中代码放在Meteor.startup(function() { ... });中,但这又取决于您的模板结构,因为地图需要在第一个模板上可见而不是另一个页面(因为div元素不会在屏幕上)