0

In my visits collection I have a geocodeVisit function which uses the Google geocoding service to gecode an address. The problem is that the meteor script is typically run before the google maps API is loaded, resulting in an Exception while invoking method 'visitInsert' ReferenceError: google is not defined error. So I need to wait with the inser till the geocoding has finished. How can I do this? This is the visits collection:

Meteor.methods({
  visitInsert: function(visitAttributes) {
    check(Meteor.userId(), String);
    check(visitAttributes, {
      nr: String,
      visit_date: String
    });

    var properties = {
      userId: Meteor.userId(),
      position: geocodeVisit(visitAttributes.address)
    };

    var visit = _.extend(visitAttributes, properties);
    var visitId = Visits.insert(visit);
    return {
      _id: visitId
    };
  }
});

geocodeVisit = function (address) {
  this.unblock;
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      return results[0].geometry.location;
    }
  });
}
John
  • 6,404
  • 14
  • 54
  • 106
  • You should load the google script ( – Emmanuel Delay Dec 01 '14 at 15:12
  • That is already done and loaded initially upon first visit of the site. Adding a visit happens after the initial load, so that Google script is loaded – John Dec 01 '14 at 15:20

1 Answers1

0

Instead of including the maps api using a script tag in the HTML code, you should download the file to your "/lib" directory. Everything in that directory is loaded before any Meteor code is run.


Also, you are going to run into an async problem with you code. You are trying to return the value from the success callback in the geocodeVisit function. The two approaches that I can see working are:

  1. Figure out how to make synchronous requests using the maps api. Maybe this: Synchronous request in Node.js
  2. Go ahead and insert the visit without the location info. Then make the geocode request to the maps api and update the entry once the response comes back. Personally, this is the approach I would take.
Community
  • 1
  • 1
desposi1
  • 36
  • 4
  • I like your second approach very much. When I download the maps api and add it to the ``/lib`` folder, it returns an error ``window is not defined`` on this line ``window.google = window.google || {};``? – John Dec 01 '14 at 18:31
  • Doh! Ok, two things to try are (1) Edit the file to wrap all of the code in a if(Meteor.isClient){...} block (I am not sure this works...) or (2) Place it in the client directory instead. Note that scripts are loaded in alphabetical order so you can name it 00_google.maps.min.js so that it is loaded first. Compliments of https://github.com/rdio/jquery.rdio.js/issues/6 – desposi1 Dec 01 '14 at 21:04