Skip to content

Instantly share code, notes, and snippets.

@jennli
Last active March 20, 2016 05:49
Show Gist options
  • Save jennli/4e0271b23905eebb6ad1 to your computer and use it in GitHub Desktop.
Save jennli/4e0271b23905eebb6ad1 to your computer and use it in GitHub Desktop.

Geocoding

gem 'geocoder'
gem 'gmaps4rails'
gem 'underscore-rails'
  • application.js
//= require underscore
//= require gmaps/google
  • add the following fields
rails g migration add_geocoding_fields_to_user address longitude:float latitude:float
  • generate address for users
User.all.each {|u| u.update(address: "142 W Hasting Street")}
  • put the following to layout application
<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 -->

show

<% if @campaign.longitude && @campaign.latitude %>
  <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([
      {
        "lat": <%= @campaign.latitude %>,
        "lng": <%= @campaign.longitude %>,
        "infowindow": "hello CodeCore!"
      }
    ]);
    handler.bounds.extendWith(markers);
    handler.fitMapToBounds();
  });

  </script>
<% end %>
  • look for campaigns within 50 km radius
Campaign.near([user.latitude, user.longitude], 50, units: :km)

near by campaigns controller

rails g controller nearby_campaigns
  • index
def index
    user_coordinates = [current_user.latitude, current_user.longitude]
    @campaigns = Campaign.near(user_coordinates, 50, units: :km)
end
  • in nearby campaign helper
module NearbyCampaignsHelper
  def markers(campaigns)
    Gmaps4rails.build_markers(@users) do |campaign, marker|
      marker.lat campaign.latitude
      marker.lng campaign.longitude
      marker.infowindow campaign.title
    end
  end
end
  • in index.html.erb of nearby 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>
  • routes:
resources :nearby_campaigns, only: [:index]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment