Google Maps with Meteor not working

此生再无相见时 提交于 2019-12-24 05:58:15

问题


For my project i need google maps api. I just can serve the api via script tag, so i tried something like that.

my 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>

my 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
  });
}

On execution the error is: Uncaught ReferenceError: google is not defined

How can i get this working?


回答1:


The meteor script is typically run before the google maps API is loaded so its best to put your code in a Template.rendered : see Template.rendered at the meteor docs

e.g If you have a template

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

Your js would be:

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);   
}

It really depends more on what your template looks like. The rendered callback will re run everytime the template changes reactively too. So if you find it re-renders you might have to use a Session hash to check it only sets the maps center/settings only once.

Another option would be to put your map centering code in Meteor.startup(function() { ... });, but again this depends on your template structure as the map needs to be visible on the first template and not one another page (as the div element wont be on the screen)



来源:https://stackoverflow.com/questions/16383866/google-maps-with-meteor-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!