Coder Social home page Coder Social logo

jt-rails-address's Introduction

JTRailsAddress

Gem Version

JTRailsAddress simplify postal addresses management and geocoding with Google Maps API in Ruby On Rails and Javascript.

Installation

JTRailsAddress is distributed as a gem, which is how it should be used in your app.

Include the gem in your Gemfile:

gem 'jt-rails-address', '~> 1.0'

Usage

Basic usage

In your migration file:

class CreateUsers < ActiveRecord::Migration
	def change
		create_table :users do |t|

			t.string :username, null: false
			t.string :email, null: false
			t.string :password_digest

			# Each field will be prefixed by 'address_'
			t.address :address

			t.timestamps null: false
		end
	end
end

It will create all the fields you need for address management:

  • formatted_address, "Empire State Building, 350 5th Ave, New York, NY 10118"
  • street_number, "350"
  • street_name, "5th Ave"
  • street, "350 5th Ave", it's the concatenation of street_number and street_name
  • city
  • zip_code
  • department
  • department_code
  • state
  • state_code
  • country
  • country_code
  • lat, GPS latitude
  • lng, GPS longitude

There are also add_address and remove_address methods for migrations.

In your model:

class User < ActiveRecord::Base

    # Add a virtual field named `address` and a class method `address_fields` returning `JT::Rails::Address.fields` prefixed by `address_` in this case
    has_address :address

end

Javascript usage with Google Maps API

You probably want to use an autocompletion service like Google Maps API.

In your HTML:

<!-- Basic form, address is just a virtual field used for searching the address on Google Maps API -->
<%= form_for @user do |f| %>

	<div class="jt-address-autocomplete">
		<!-- This field is used to search the address on Google Maps -->
		<%= f.text_field :address, class: 'jt-address-search' %>

		<!-- All fields are hidden because the javascript will set their value automatically -->
		<% for attr in JT::Rails::Address.fields %>
			<%= f.hidden_field "address_#{attr}", class: "jt-address-field-#{attr}" %>
		<% end %>
	</div>

	<!-- Optional, if this field is true, the address will be remove -->
	<%= f.check_box :address_destroy %>

	<%= f.submit %>

<% end %>

<!-- Load Google Maps and call googleMapInitialize when it's done -->
<script async type="text/javascript" src="//maps.googleapis.com/maps/api/js?libraries=places&callback=googleMapInitialize&key=YOUR_GOOGLE_API_KEY"></script>

In your applicaton.js you have to add:

//= require jt_address

// This function is call when Google Maps is loaded
window.googleMapInitialize = function(){

    // Simple usage
    $('.jt-address-autocomplete').jt_address();
    
    // Advanced usage with google options
    $('.jt-address-autocomplete').jt_address({
        type: ['restaurant'],
        componentRestrictions: { country: 'fr' }
    });

};

Each time the data for the address change, an event jt:address:data_changed is triggered. You can catch it with:

$('.jt-address-autocomplete').on('jt:address:data_changed', function(event, data){
	console.log(data);
});

Google Maps API in Ruby

Thanks to graticule, there is a simple way to use autocomplete in Ruby.

# Simple usage
data = JT::Rails::Address.search("Eiffel Tower", "YOUR GOOGLE API KEY")

# Advanced usage
data = JT::Rails::Address.search("Eiffel Tower", "YOUR GOOGLE API KEY", {components: 'country:fr'})

# Use the data retrieve from Google Maps API
my_instance.load_address(:address, data)

# Use the set a nil all address fields
my_instance.reset_address(:address)

# Use the set a nil all address fields with HTML forms
my_instance.update({address_destroy: true})

Author

License

JTRailsAddress is released under the MIT license. See the LICENSE file for more info.

jt-rails-address's People

Contributors

johnvuko avatar

Stargazers

Jelani Woods avatar Serhii Ponomarov avatar Donncha O'Toole avatar Arif Ikhsanudin avatar stayce avatar Haris Pobric avatar Harry Keefe avatar Gary Lai avatar  avatar Jonathan Crawford avatar william avatar Matt Didcoe avatar Washington Botelho avatar Olivier avatar Jason Buck avatar  avatar nizar avatar Igor Zubkov avatar Logan Leger avatar ma11o avatar Andrew Kane avatar Bijan Rahnema avatar Spenser X avatar Christopher Jaeger avatar Khalil Gharbaoui avatar Peter Højlund Palluth avatar Druid avatar Eduardo de Santana Medeiros avatar Tomas Jukin avatar Alejandro Perezpayá avatar E.T.Cook avatar Cherie Sew avatar Vivek Kumar Singh avatar Joseph Page avatar Michael avatar Trong Tran avatar Colin Kearns avatar  avatar Menghong Li avatar Guillaume Occuly avatar Alexander ADAM avatar

Watchers

 avatar  avatar James Cloos avatar Jake Smith avatar  avatar

jt-rails-address's Issues

How to migrate address?

Hello
Migration:

class AddAddressToMembers < ActiveRecord::Migration[5.1]
  def change
    add_column :members, :address, :address
  end
end

Error:

Caused by:
PG::UndefinedObject: ERROR:  type "address" does not exist
LINE 1: ALTER TABLE "members" ADD "address" address

and
undefined method has_address' for #Class:0x007f500d44aca0`

Submitting form with Enter key before search field loses focus does not successfully update the address

This is a weird one. I've debugged this from every which way and the update claims to be successful, but as soon as I go back to the edit page, the address is back to what it used to be.

Here is my controller's update method:

  def update
    respond_to do |format|
      if @person.update(person_params)
        format.html { redirect_to @person, notice: 'Person was successfully updated.' }
        format.json { render :show, status: :ok, location: @person }
      else
        format.html { render :edit }
        format.json { render json: @person.errors, status: :unprocessable_entity }
      end
    end
  end

  private

  ...

    # Never trust parameters from the scary internet, only allow the white list through.
    def person_params
      params.require(:person).permit(:name,
                                     :address,
                                     :address_formatted_address,
                                     :address_street_number,
                                     :address_street_name,
                                     :address_street,
                                     :address_city,
                                     :address_zip_code,
                                     :address_department,
                                     :address_department_code,
                                     :address_state,
                                     :address_state_code,
                                     :address_country,
                                     :address_country_code,
                                     :address_lat,
                                     :address_lng)
    end

Stepping over the .update call claims to be successful and in the debugger I threw in another .save call just to see if I could get it to persist.

I can't seem to narrow down this behavior very well, but this is my best attempt at an explanation: If using the search field, and the mouse is used to select from the dropdown, then submitting the form works whether the button or enter key is used. But if you select an address using the search field with using the mouse, the submission does not persist. And as mentioned above, rails seems to think it is updating in the controller.

Since this seems so weird, I recorded the steps...

https://giphy.com/gifs/l0MYsXEfeMNQMPfri

removing address

How would one go about removing an address from an ActiveRecord object in the update action of that controller?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.