Skip to content

Instantly share code, notes, and snippets.

@mgirouard
Last active December 17, 2015 17:09
Show Gist options
  • Save mgirouard/5644395 to your computer and use it in GitHub Desktop.
Save mgirouard/5644395 to your computer and use it in GitHub Desktop.
A simple zip code locater component
// http://jsfiddle.net/6R5Ea/3/
// App Namespace
(function ($j, $u, $b) {
var App = window.app = {};
})(window.jQuery, window._, window.Backbone);
// Zip Locater Application
// =======================
(function ($j, $u, $b) {
var App = window.app,
ZipLocater = App.ZipLocater = {};
// The Zip Locater Core Model
// --------------------------
ZipLocater.Model = $b.Model.extend({
defaults: { street: null, city: null, state: null, zip: null },
// Defines the url to load the geocoded data from
// This assumes a valid model
url: function () {
var base = 'https://maps.googleapis.com/maps/api/geocode/json?sensor=false',
url = [this.get('street'), this.get('city'), this.get('state')].join(', ');
return base + '&address=' + encodeURIComponent(url);;
},
// Parses the reverse geocoded data from Google
parse: function (response) {
if (!response.results[0] || !response.results.length) return null;
var parts = response.results[0].address_components;
return {
street: parts[0].long_name + ' ' + parts[1].long_name,
city: parts[3].long_name,
state: parts[5].short_name,
zip: parts[7].long_name
}
}
});
// Zip Code Locater Core View
// --------------------------
ZipLocater.View = $b.View.extend({
el: '.zip-locater',
events: { 'submit': 'reverseGeocode' },
initialize: function () {
this.model.on('sync', function () {
var zip = this.model.get('zip');
if (zip) this.$('.zip').text(zip);
}, this);
},
reverseGeocode: function (event) {
event.preventDefault();
var data = {};
_.each(this.$el.serializeArray(), function (field) {
data[ field.name ] = field.value;
});
this.model.set(data);
this.model.fetch();
}
});
})(window.jQuery, window._, window.Backbone);
// Initialization routine
// ======================
jQuery(function ($) {
var App = window.app;
App.zipLocater = new App.ZipLocater.View({
model: new App.ZipLocater.Model
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment