Retrieve a string from database, put it into another function


#1

I want to be able to set the center of a Google Map based on coordinates stored in a Mongo collection.

Inside my Template.Home.helpers, I have the following function to get the coordinates:

mapCenter: function () {
  return (this.map); //returns -37.8136, 144.9631
}

How can I pass this value into this mapOptions function, also inside the same template helper:

mapOptions: function() {
    // Make sure the maps API has loaded
    if (GoogleMaps.loaded()) {
      // Map initialization options
      return {
        center: new google.maps.LatLng(XX.XXXX,XX.XXXX),
        zoom: 8
      };
    }
  }

Can I store mapCenter as a variable and call it from this?


#2

I’m fairly new to meteor, so please take this with a grain of salt. :smile:

Can’t you just use a session to do this?
Like this:

   mapCenter: function () {
    	var myVariable = this.map;
    
    	return (myVariable);
    	Session.set('mySession', myVariable);
    }
    
    mapOptions: function() {
    	var mySession = Session.get('mySession');
    
    	// Make sure the maps API has loaded
    	if (GoogleMaps.loaded()) {
    	  // Map initialization options
    	  return {
    		center: new google.maps.LatLng(mySession),
    		zoom: 8
    	  };
    	}
    }

I haven’t tested this and since Sessions are global, this might not be an ideal solution.
I’d also be interested on how this is done best.


#3

Hi Nils, thanks for replying.

The Session.set is unreachable after return, so says my JS linter. I did not explain the whole scenario in my first post, but I have a list with many items. Every item have a map, so the center position need to update when you go from item #1 to item #2.

Session.set and Session.get would maybe not support this?


#4

helpers are run when template is being rendered, so this is not best place to set reactive variable.

But yes, in event handler, or in template onRendered function, you can easily set Session variable like Session.set("myCenter", {lat: latitude, lon: longitude});

And in that mapOptions function just use

center: new google.maps.LatLng(Session.get("myCenter"));

I would personally do it with reactive var to not polute global namespace, but that would be too long discussion :smiley:


#5

If mapCenter and mapOptions are both helpers in the same template, and mapCenter is referring to this.map, why can’t mapOptions also refer to this.map?

Template.Home.helpers({
  mapCenter: function () {
    return this.map;
  },

  mapOptions: function () {
    // Make sure the maps API has loaded
    if (GoogleMaps.loaded()) {
      // Map initialization options
      return {
        center: new google.maps.LatLng(this.map.lat, this.map.lng),
        zoom: 8
      };
    }
  }
});