Reverse geocoding with a deferred object in a coffeescript class

177 views Asked by At

I am writing a coffeescript class which will act as a wrapper object for a Google Maps Marker. One of the key pieces of functionality for this object is the ability to fetch the Markers address via the Google Maps reverse geocoding service. In order to minimize service calls, I would like to store the geocoding result in an @address variable that is only set when an address function is called (ex: city(),state(),country()). I have attempted to use jQuery's Deferred objects to accomplish this goal, but I'm not quite sure how to ensure that the @address variable is set before I proceed further in the code. Here is the class so far:

class @GMarker
  constructor: (args) ->
    @title    = args.title
    @map      = args.map
    @position = args.position
    @marker   = new google.maps.Marker(position: @position, map: @map, title: @title)
    @address  = null

  city: () =>
    @setAddress()
    @address.address_components # this is executing before @setAddress has finished running

  reverseGeocode: () ->
    geocoder = new google.maps.Geocoder()
    defer = jQuery.Deferred()
    geocoder.geocode {'latLng': @position}, (results, status) ->
      if status == google.maps.GeocoderStatus.OK
        defer.resolve(results[0])
    defer.promise()

  setAddress: () =>
    unless @address?
      $.when(@reverseGeocode()).then (result) =>
        @address = result

I have created a JSFiddle which explicitly demonstrates the problem that I am having: https://jsfiddle.net/3ryztfjm/3/

0

There are 0 answers