Skip to content

Instantly share code, notes, and snippets.

@dohoonk
Last active March 17, 2016 21:09
Show Gist options
  • Save dohoonk/85dae95fbb1bdf6ee10b to your computer and use it in GitHub Desktop.
Save dohoonk/85dae95fbb1bdf6ee10b to your computer and use it in GitHub Desktop.
Geocoder/

example of fundsy

gem "geocoder"

You have to turn the address into longetude and latitude

rails generate migration AddLatitudeAndLogitudeToModel(name) latitude:float longitude:float

In your campagin model Add this line of code

geocoded_by :full_street_address   # can also be an IP address
after_validation :geocode          # auto-fetch coordinates

In order to put a pin on the map you need another gem

gem 'gmaps4rails'

Displaying the pin on the map

<% if @campaign.longitude && @campaign.latitude %>
<div style='width: 800px;'>
  <div id="map" style='width: 800px; height: 400px;'></div>
</div>
<% end %>

Include the script in application.html.erb (create a seperate show page in real life)

<script src="//maps.google.com/maps/api/js?v=3.18&sensor=false&client=&key=&libraries=geometry&language=&hl=&region="></script> 
<script src="//google-maps-utility-library-v3.googlecode.com/svn/tags/markerclustererplus/2.0.14/src/markerclusterer_packed.js"></script>
<script src='//google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.9/src/infobox_packed.js' type='text/javascript'></script> <!-- only if you need custom infoboxes -->

In order for this code to work we need underscoresjs.org library download underscore and put it in javascript or Use a gem

gem 'underscore-rails' In your application js (The order is important)

//= require underscore
//= require gmaps/google

Add this to your show page

 <script>
  handler = Gmaps.build('Google');
  handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
    markers = handler.addMarkers([
       {
        "lat": <%= @campaign.latitude %>,
        "lng": <%= @campaign.longitude %>,
        "picture": {
          "url": "http://people.mozilla.com/~faaborg/files/shiretoko/firefoxIcon/firefox-32.png",
          "width":  32,
          "height": 32
        },
        "infowindow": "hello codecore!"
      }
    ]);
    handler.bounds.extendWith(markers);
    handler.fitMapToBounds();
  });

  </script>

Adding multiple location

Get the user's location (assuming that user is going to provide the address) bin/rails g migration add_geocoding_fields_to_user address latitude:float longitude:float

You have 3 options to get the address from the user IP Browser Gps

In your user model Add this line of code

geocoded_by :full_street_address   # can also be an IP address
after_validation :geocode          # auto-fetch coordinates

To mass assign address to users and campaigns

User.all.each {|u| u.update(address: "142 W Hastings, Vancouver, BC")}
Campaign.where(latitude: nill).limit(50).each {|c| c.update(address: address.sample)}

Geocoder nearby

Campaign.near([user.latitude, user.longitude], 50, units: :km)

This code will fetch the campaigns near the user

Create a seperate controller to show all the campaigns near the user

bin/rails g controller nearby_campaigns

In the controller

before_action :authenticate_user

def index
  user_cordinates = [current_user.latitude, current_user.longitude]
  @campagins = Campaign.near(user_coordinates, 50, units: :km)
end

Create the view page Create index.html.erb to display the campaigns

<h1>Nearby Campaigns</h1>

<div style='width: 800px;'>
  <div id="map" style='width: 800px; height: 400px;'></div>
</div>

<script>
handler = Gmaps.build('Google');
handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
  markers = handler.addMarkers(<%= raw markers(@campaigns).to_json %>);
  handler.bounds.extendWith(markers);
  handler.fitMapToBounds();
});
</script>

Generating JSON In your near_by caimpaign helper

module NearbyCampaignsHelper

  def markers(campaigns)
    Gmaps4rails.build_markers(campaigns) do |campaign, marker|
      marker.lat campaign.latitude
      marker.lng campaign.longitude
      campaign_link = link_to campaign.name, campaign_path(campaign)
      marker.infowindow campaign_link
    end
  end
end

Add routes

resources :near_by, only: [:index]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment