在提交之前将Lat Lng值设置为隐藏字段

时间:2014-02-18 08:51:57

标签: javascript jquery forms google-maps-api-3 ruby-on-rails-4

我正在使用Google Maps Api(包括自动填充功能)让用户将地址写入表单字段,然后查找输入的地址的纬度和经度值。

现在,我想将这些值发送回表单(隐藏字段)以提交给数据库。 后端全部设置完毕,我只是不确定如何在客户端上执行此操作。我很感谢你的帮助!

我的代码 红宝石:

<div id="form>
  <%= f.text_field :location, onFocus: "geolocate", id: "autocomplete" %>
  <%= hidden_field_tag :latitude, id: "lat" %>
  <%= hidden_field_tag :longitude, id: "lng" %>
  <%= f.button :submit, class: "btn" %>
</div>

使用Javascript:

function codeAddress() {
    var address = document.getElementById("autocomplete").value;
    // next line creates asynchronous request
    geocoder.geocode( { 'autocomplete': address}, function(results, status) {
      // and this is function which processes response
      if (status == google.maps.GeocoderStatus.OK) {
        $("#lat").val(results[0].geometry.location.lat());
        $("#lng").val(results[1].geometry.location.lng());
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

  var placeSearch, autocomplete;

  function initialize() {
    autocomplete = new google.maps.places.Autocomplete(
        (document.getElementById('autocomplete')),
        { types: ['geocode'] });
  }

  function fillInAddress() {
    var place = autocomplete.getPlace();

    for (var component in componentForm) {
      document.getElementById(component).value = '';
      document.getElementById(component).disabled = false;
    }
  }

function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = new google.maps.LatLng(
          position.coords.latitude, position.coords.longitude);
      autocomplete.setBounds(new google.maps.LatLngBounds(geolocation,
          geolocation));
    });
  }
}

2 个答案:

答案 0 :(得分:2)

如果您使用$("#form").submit(); docs尝试执行此操作,则可以在成功的地理位置上提交回复以提交表单。

if (status == google.maps.GeocoderStatus.OK) {
    $("#lat").val(results[0].geometry.location.lat());
    $("#lng").val(results[1].geometry.location.lng());
    $("#form").submit();
}

答案 1 :(得分:1)

你的问题在于:你应该将lat和long隐藏字段放在表单生成器中,如下所示:

<div id="form>
  <%= f.text_field :location, onFocus: "geolocate", id: "autocomplete" %>
  <%= f.hidden_field :latitude, id: "lat" %>
  <%= f.hidden_field :longitude, id: "lng" %>
  <%= f.button :submit, class: "btn" %>
</div>