rebyn
rebyn

Reputation: 11

Passing Google Maps position data to Rails form?

When I drag the marker on my map to a new position, upon clicking the marker a infowindow will appear with a form of attributes :email, :latitude, :longitude inside. How to automatically set these attributes (latitude and longitude) with information of the new position, so that I just have to fill the :email and click Submit? This is my code (incomplete).

google.maps.event.addListener(testMarker, 'dragend', function(evt) {
        var testContent = '<%= form_for @newlazystreeter, :url => { :action => "create" }, :html => {:class => "nifty_form"} do |f| %>'+
            '<%= f.text_field :email %><br>'+
            '<%= f.text_field :latitude %><br>'+
            '<%= f.text_field :longitude %><br>'+
            '<%= f.submit "Submit!" %>'+
            '<% end %>';
        var infowindow = new google.maps.InfoWindow({
            content: testContent
        });
        infowindow.open(map,testMarker);
    });

Upvotes: 1

Views: 845

Answers (1)

formigarafa
formigarafa

Reputation: 376

I think, would be better you put form code apart because in some cases rails will generate multiples lines and that conversion from html to javascript will not work.

so, the first thing is add the form to the DOM and hide it within an invisible div: I also added some ids to make easier find these elements latter (form, latitude and longitude)

<div style="display:none">
  <%= form_for @newlazystreeter, :url => { :action => "create" }, :html => {:class => "nifty_form", :id => "info_window_form"} do |f| %>
    <%= f.text_field :email %><br>
    <%= f.text_field :latitude, :id => 'latitude_field' %><br>
    <%= f.text_field :longitude, :id => 'longitude_field' %><br>
    <%= f.submit "Submit!" %>
  <% end %>
 </div>

Than you create the info window using the form element as content option:

var infowindow = new google.maps.InfoWindow({
  content: document.getElementById('info_window_form'),
});

And here is where I really answer your question. Finally, you have to add the behavior you want to the marker. You open infowindow and update form values of latitude and longitude.

google.maps.event.addListener(testMarker, 'dragend', function(evt) {
  document.getElementById('latitude_field').value = testMarker.position.lat();
  document.getElementById('longitude_field').value = testMarker.position.lng();
  infowindow.open(map,testMarker);
});

I would suggest one more thing: hide this infowindow while you are dragging the marker.

google.maps.event.addListener(testMarker, 'dragstart', function(evt) {
  infowindow.close();
});

Remember of add this javascript code on a listener triggered by DOMContentLoaded to make sure that every html id will be found.

document.addEventListener('DOMContentLoaded', function () {
  // add here javascript code to load map and all this stuff above
}, false);

This should run well and fine.

Upvotes: 2

Related Questions