Skip to content

Instantly share code, notes, and snippets.

@stefanoverna
Created April 9, 2014 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanoverna/10252309 to your computer and use it in GitHub Desktop.
Save stefanoverna/10252309 to your computer and use it in GitHub Desktop.
#= require ./behaviour
class @GeocodedField extends Behaviour
init: ->
@$latField = @domData('lat-dom')
@$lngField = @domData('lng-dom')
startingValue = @$dom.val()
if startingValue.length > 0
startingOptions = [
{
address: startingValue,
lat: @$latField.val(),
lng: @$lngField.val()
}
]
@$dom.selectize
valueField: "address"
labelField: "address"
searchField: "address"
delimiter: '|||'
options: startingOptions
maxItems: 1
create: false
load: (query, cb) =>
return cb() unless query.length
@getCoords query, (err, results) ->
if err
cb()
else
cb(results)
onChange: =>
if @selectize.getValue().length > 0
result = @selectize.options[@selectize.getValue()]
@$latField.val(result.lat)
@$lngField.val(result.lng)
@selectize = @$dom.get(0).selectize
getCoords: (address, cb) ->
geocoder = new google.maps.Geocoder()
geocoder.geocode address: address, region: 'it', (data, status) ->
if status is google.maps.GeocoderStatus.OK
results = for result in data
{
address: result.formatted_address
lat: result.geometry.location.lat()
lng: result.geometry.location.lng()
}
cb(null, results)
else
cb("Cannot find #{@location}!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment