我正在尝试实现这个,来自 gem wiki https://github.com/apneadiving/Google-Maps-for-Rails/wiki/Javascript-goodies
<% content_for :scripts do %>
<script type="text/javascript" charset="utf-8">
var markersArray = [];
// On click, clear markers, place a new one, update coordinates in the form
Gmaps.map.callback = function() {
google.maps.event.addListener(Gmaps.map.map, 'click', function(event) {
clearOverlays();
placeMarker(event.latLng);
updateFormLocation(event.latLng);
});
};
// Update form attributes with given coordinates
function updateFormLocation(latLng) {
$('location_attributes_latitude').value = latLng.lat();
$('location_attributes_longitude').value = latLng.lng();
$('location_attributes_gmaps_zoom').value = Gmaps.map.map.getZoom();
}
// Add a marker with an open infowindow
function placeMarker(latLng) {
var marker = new google.maps.Marker({
position: latLng,
map: Gmaps.map.map,
draggable: true
});
markersArray.push(marker);
// Set and open infowindow
var infowindow = new google.maps.InfoWindow({
content: '<div class="popup"><h2>Awesome!</h2><p>Drag me and adjust the zoom level.</p>'
});
infowindow.open(Gmaps.map.map,marker);
// Listen to drag & drop
google.maps.event.addListener(marker, 'dragend', function() {
updateFormLocation(this.getPosition());
});
}
// Removes the overlays from the map
function clearOverlays() {
if (markersArray) {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
}
markersArray.length = 0;
}
</script>
<% end %>
但运气不好...我猜这更多是我的字段的名称/ID 的问题,请原谅我的 JavaScript 知识。
我已更改字段以使用坐标进行更新:
function updateFormLocation(latLng) {
$('location[lat]').value = latLng.lat();
...
}
但是该字段没有更新:
= simple_form_for :location do |l|
= l.input :lat
...
我错过了什么吗?谢谢!
最佳答案
从表面上看,该语法是为原型(prototype)编写的。如果您将 Rails 3.1 与 jQuery 结合使用,则需要更新该语法才能查找 DOM 节点。
即如果您正在查找 id 为 "location_attributes_latitude"
的元素,则需要使用:
$('#location_attributes_latitude')
为了设置值:
$('#location_attributes_latitude').val(latLng.lat());
关于ruby-on-rails-3 - gmaps4rails - 删除标记并更新表单中的字段属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9425816/