Search code examples
ruby-on-railsrubyruby-on-rails-3google-mapsgmaps4rails

How can I let the user choose a destination using Gmaps4Rails?


I have this model:

class Location < ActiveRecord::Base
  acts_as_gmappable
  def gmaps4rails_address
    "#{self.city}, #{self.country}"
  end
end

having this schema:

t.float    "latitude"
t.float    "longitude"
t.boolean  "gmaps"
t.datetime "created_at"
t.datetime "updated_at"
t.string   "country"
t.string   "city"
t.string   "street"

I would like to allow the user to specify a starting point and an ending one, and give him the distance between them. I would like to have him select them on the map. Could you please guide me in accomplishing this?


Solution

  • There is no straight way to achieve what you want with gmaps4rails, at least not both parts of it:

    • clicking on the map and creating markers belongs to you

    • displaying the destination can be handled by the gem once you've retrieved the two places.

    In your view, you should add the following ruby code (take the following options as mere example, the only purpose of the helper here is to create the map):

    <%= gmaps( "map_options" => { "center_on_user" => true, "zoom" => 5 }) %>
    

    Then you could include javascript:

    //starting point
    Gmaps4Rails.direction_conf.origin = from_var_string;
    //where to go
    Gmaps4Rails.direction_conf.destination = to_var_string;
    //if you want to display a panel with the instructions
    Gmaps4Rails.direction_conf.display_panel = true;
    //pass here the id of the panel
    Gmaps4Rails.direction_conf.panel_id = 'instructions';
    //set the travel mode
    Gmaps4Rails.direction_conf.travelMode = 'DRIVING';
    //add one or more waypoints
    Gmaps4Rails.direction_conf.waypoints = [{"stopover":true,"location": waypoint1_string},{"stopover":true,"location": waypoint2_string}];
    //trigger the creation
    Gmaps4Rails.create_direction();