user1010101
user1010101

Reputation: 1658

Using geocode autocomplete in a form

bI have a small form as shown below where user can enter some start and end location address in text format. I want to add the autocomplete feature that is in google maps because most people are lazy to type the entire address.

<%= form_tag("/welcome/index", method: "post") do %>
  <h5>Current Location</h5>
  <%= label_tag :address %><br> 
  <%= text_field_tag :address %>

  <h5>Destination Location</h5>
  <%= label_tag :address %><br> 
  <%= text_field_tag :destaddress %>


  <p>
    <%= submit_tag("Submit") %>
  </p>

Upon doing research i found that it is possible to do with rails using GeoComplete.

Ass suggested by tutorial I tried the following:

I included the required google api scripts in my code and added this

$("address").geocomplete();

It is not working. can someone tell me what I did wrong?

Upvotes: 0

Views: 3076

Answers (2)

Rob Mulholand
Rob Mulholand

Reputation: 899

Haven't worked with GeoComplete, but a quick and dirty way to get autocomplete working is this:

# application.html.erb
<head>
...
  <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
...
</head>

# Your Form
<script type="text/javascript">
  function initialize() {

  var input = document.getElementById('address');
  var autocomplete = new google.maps.places.Autocomplete(input);
  }

  google.maps.event.addDomListener(window, 'load', initialize);
</script>

<script type="text/javascript">
  function initialize() {

  var input2 = document.getElementById('destaddress');
  var autocomplete2 = new google.maps.places.Autocomplete(input2);
  }

  google.maps.event.addDomListener(window, 'load', initialize);
</script>

<%= form_tag("/welcome/index", method: "post") do %>
  <h5>Current Location</h5>
  <%= label_tag :address %><br> 
  <%= text_field_tag "address" %>

  <h5>Destination Location</h5>
  <%= label_tag :address %><br> 
  <%= text_field_tag "destaddress" %>

<p>
  <%= submit_tag("Submit") %>
</p>

Later, you can move the javascript out to a separate file and include it with erb to clean up the view.

You may have to turn off turbolinks in links to the form ("data-no-turbolink" => true) to be sure the JS will load.

Upvotes: 3

rb512
rb512

Reputation: 6948

You might wanna check out gmaps-autocomplete or gmaps-autocomplete-rails. Both gems have good examples to get you started and do just what you're looking for.

Upvotes: 2

Related Questions