chaosbohne
chaosbohne

Reputation: 2484

Google Maps with Meteor not working

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?

Upvotes: 2

Views: 2740

Answers (1)

Tarang
Tarang

Reputation: 75955

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)

Upvotes: 6

Related Questions