Last Updated: February 25, 2016
·
3.542K
· royletron

Want to use GoogleMaps and Meteor?

Picture
I have literally been around the houses trying to get Google Maps to work nicely with Meteor. Everything was going swimmingly until I wanted to use a Handlebars template to show info about a selected marker on the map. Every time the Session data was updated, because a marker had been clicked, the sub-template for the marker info would refresh and kick the main template (containing the Google Map) into refresh loosing any kind of nice transition (when you click the marker the viewport pans to center on it). Anyway, after a lot of faffing, including trying to render the sub-template using jQuery (heavens forbid), I found two really useful things I hadn't previously come across.

Constant

{{#constant}}
    <div class="row" style="height:300px" id="map-canvas-sm"></div>
{{/constant}}

This voodoo Handlebar helper ensures that the defined section doesn't get refreshed, even if it is part of a template that does get refreshed... voodoo!

Template.foo.rendered

Template.map.rendered = function() {
    if(!this.rendered){
        //Stuff here is run on first render only.
        var map = getMap("map-canvas-sm", false);
        setTypeAhead("place-search", map);
        this.rendered = true;
    }
}

Next, you need to ensure that the JS that sets up the Google Map doesn't get run multiple times. I tend to stick these kinds of things in the Template.foo.rendered function, but obviously this gets triggered every time the template refreshes. I had read about Template.foo.created but this is problematic as the template has yet to be drawn so you can't do anything DOM related. To use the rendered function, but only once, you simple stick a variable into the Template once you know it has been rendered for the first time. I used 'rendered' but really it could be anything.

Chances are that everyone knew about these, but I didn't, so equally there is a chance that someone will find this useful!