我正在使用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));
});
}
}
有什么不对的代码?你需要以正确的方式设置隐藏字段,并且在提交表单时,可以按照需要将这些值保存在数据库中。你错过了什么? – sissy
感谢您查看代码。我没有得到经纬度/ lng值来保存... – robinyapockets