Search code examples
javascriptruby-on-railsrubygoogle-mapsgmaps4rails

use geocode autocomplete in a form so users don't need to type in where they are


Users will have a simple form where they can enter 3 address. the first address is most likely going to be where they currently are. so i would like to have a button right next to it that says "my current location" that will automatically fill in that input with their current location but im not entirely sure how to go about doing this. here is the code for my form:

      <div class="main-container z-depth-5">
       <h3 class="txt-primary">Equidestined</h3>
         <p class="home-instructions">Enter two or three addresses to find the optimal meeting spot!</p>
            <%= form_for @search do |search_form| %>
            <% @search.locations.each do |location| %>
              <div class="input-field col s12">
              <%= search_form.fields_for location, index: location.id do |location_form|%>
              <%= location_form.text_field :address %>
               <%= location_form.label :address%>
                <% end %>
              </div>
             <% end %>
            <br><%= submit_tag('Get Midpoint!', :class=>"waves-effect waves-light btn") %>
         <% end %>
         </div>

can anyone point me in the right direction? thanks


Solution

  • What you are looking for is HTML 5's geolocation feature.

    https://www.w3schools.com/html/html5_geolocation.asp

    Do note that the user can decline this option or the browser may not support it which will make your button nonfunctional. It is best to only show the option (button in your case) if geolocation is available.

    EDIT

    Using HTML Geolocation The getCurrentPosition() method is used to return the user's position.

    The example below returns the latitude and longitude of the user's position:

    Example

    var x = document.getElementById("demo");
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else {
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }
    function showPosition(position) {
        x.innerHTML = "Latitude: " + position.coords.latitude + 
        "<br>Longitude: " + position.coords.longitude; 
    }