2014-02-18 70 views
0

我正在使用Google Maps Api(包括自动完成功能)让用户将地址写入表单字段,然后查找输入地址的纬度和经度值。在提交之前将Lat Lng值设置为隐藏字段

现在,我想将这些值发回到表单(隐藏字段)以提交给数据库。 后台全部建立,我只是不知道如何在客户端上完成。我很感谢任何帮助!

我的代码 红宝石:

<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)); 
    }); 
    } 
} 
+0

有什么不对的代码?你需要以正确的方式设置隐藏字段,并且在提交表单时,可以按照需要将这些值保存在数据库中。你错过了什么? – sissy

+0

感谢您查看代码。我没有得到经纬度/ lng值来保存... – robinyapockets

回答

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(); 
} 
+0

谢谢!我认为这是到达那里。但是,在我的控制台中,这些值不会被插入到数据库中。位置名称是,但不是lat和lng值... – robinyapockets

1

您的问题是形式:你应该把经纬度和长期隐藏字段与表单生成器是这样的:

<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> 
相关问题