【发布时间】: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