Search code examples
ruby-on-railsgmaps4railssearch-box

How to make searchbox for gmaps4rails


I am new at coding. I am working with the gmaps4rails api. I am trying to make a location search box for gmaps4rails and I cant find any way how. I have created a basic map. I also created a form for @place , for the user to enter a location, but when i press submit, nothing happens. I know there are more things to do, but I'm honestly at a loss at to what that is. I don't have any errors according to my console log. I would like to make it so that when a user presses submit, the map would zoom to that location/area on the map. I honestly have no clue what to do next. I would appreciate if someone can provide me with an example of what I need to do. Thank you in advance.

Please see below for my form that I do have.

<!-- START OF SEARCH FORM -->
  <%= form_for @place do |f| %>
   <% if @place.errors.any? %>
    <% @place.errors.full_messages.each do | msg | %>
     <p><%= msg %></p>
   <% end %>
 <% end %>

  <%= f.text_field :address, placeholder: "Where Are You?" %>
<br>

 <%= f.submit %>
<% end %>

  <!-- END OF SEARCH FORM -->

Solution

  • You will need to use jquery if you want it so that you don't have to refresh the page every time a user types in an address, which is currently what your code requires.

    The first order of business is to create a searchbox, you can do this with rails helpers like you've done or with simple html.

    Then you need to bind the searchbox either by its class or id inside a jquery function, and handle the cases when a user types in a location/presses enter.

    I highly advise you take a look at the geocoder gem, which extracts a latitude and longitude from any address the user types into a searchbox. The docs are here: https://github.com/alexreisner/geocoder. There are also quite a bit of examples on google, check them out to help you get started.

    You'll be making use of the .getMap().setZoom(...) and .map.centerOn(markers[...]) gmaps4rails methods. Look at the docs for examples on zooming in on markers: https://github.com/apneadiving/Google-Maps-for-Rails

    The solution for this is unfortunately quite long and arduous, but with a bit of effort you should be able to do it!