【问题标题】:Setting Lat Lng Values into Hidden Field Before Submit提交前将 Lat Lng 值设置为隐藏字段
【发布时间】:2014-02-18 08:51:57
【问题描述】:

我正在使用 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));
    });
  }
}

【问题讨论】:

  • 这段代码有什么问题?您正在以正确的方式设置隐藏字段,并且在提交表单时,您可以按照您需要的方式将这些值保存在您的数据库中。你错过了什么?
  • 感谢您查看代码。我没有得到要保存的 lat/lng 值...

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


【解决方案1】:

如果这是您尝试使用$("#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();
}

【讨论】:

  • 谢谢!我认为这是到了那里。但是在我的控制台中,这些值并没有被插入到数据库中。位置名称是,但不是 lat 和 lng 值...
【解决方案2】:

您的问题出在表单中:您应该像这样在表单构建器中放置 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>

【讨论】:

    猜你喜欢
    • 2015-10-11
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多