简体   繁体   中英

Value from return, into a Google maps function

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

I use Meteor as framework. 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 put it into the center in the mapOptions function?

Four basic options:

  1. Save the coordinates into a Session variable then pick them up later
  2. Save the coordinates into a closure
  3. Save the coordinates into a reactive variable
  4. Save the coordinates in a document in a collection

Session variable example:

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

mapOptions: function() {
    // Make sure the maps API has loaded
    if (GoogleMaps.loaded()) {
      // Map initialization options
      return {
        var coord = Session.get('coordinates');
        center: new google.maps.LatLng(coord.latitude,coord.longitude),
        zoom: 8
      };
    }
  } 

This approach has some limitations however since your Session variable is global in scope. If the user has multiple tabs open with multiple maps then you might end up with all the maps being the same. Then a closure might be better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM