我有一個谷歌地圖和他們的自動完成文本框之一,用戶開始輸入,地址顯示在下拉列表中,然後地圖放大到最終選定的地圖。到目前爲止,我對我的所作所爲非常滿意。問題在於,用戶必須點擊列表中的地址才能使其工作。谷歌地圖自動完成地址點擊
我想要的也是這個選項:當用戶在鍵盤上點擊'ENTER'時,即使他們沒有完全填充auto_complete框,列表中的第一個地址也會自動選中,地圖放大對此。
我玩弄
$(autocomplete).trigger("click");
,但我無法修復它。所以,如果你能給我一隻手,我會很感激......我的代碼是:
<script type="text/javascript">
function initialize_google_maps() {
var midOfIreland = new google.maps.LatLng(53.252069, -7.860718);
var myOptions = {
zoom: 7,
center: midOfIreland,
mapTypeId: google.maps.MapTypeId.ROADMAP, // ROADMAP, SATELLITE, HYBRID
streetViewControl: false
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var input = document.getElementById('address_autocomplete');
var options = {
types: ['geocode']
};
autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.bindTo('bounds', map);
// $(autocomplete).trigger("click");
var contentstring = $('#info_window').html();
var infowindow = new google.maps.InfoWindow({content: contentstring, width:1, height:1});
// for the 'x', to close the infoWindow, we give it the same behaviour as the 'No' link, in the infoWindow
google.maps.event.addListener(infowindow, 'closeclick', function() {
$(".map-no-link").trigger("click");
});
var marker = new google.maps.Marker({
map: map
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(11);
}
marker.setPosition(place.geometry.location);
$('#user_lat').val(place.geometry.location.lat());
$('#user_lng').val(place.geometry.location.lng());
$('#changed').val('1');
// infowindow.setContent(place.name);
infowindow.open(map, marker);
});
<% if current_user.address and current_user.lat %>
var currentlatlng = new google.maps.LatLng(<%= current_user.lat %>, <%= current_user.lng %>);
var marker = new google.maps.Marker({map: map, position: currentlatlng});
map.setCenter(currentlatlng);
map.setZoom(11);
<% end %>
}
$(function() {
initialize_google_maps();
});
</script>
嗨Mr.Pohoda,爲感謝,但不能得到它的工作。我將你的代碼添加到腳本的底部。在控制檯(Chrome)中出現錯誤:Uncaught TypeError:無法讀取未定義的屬性「視口」。任何其他想法?它就像你提供的代碼中的錯誤,但是當我把它拿出來時,我已經存在的代碼中沒有錯誤。 – CHarris
如果它在上面的例子中適用於您,那麼您的代碼必須存在問題。你有沒有包含Places庫?將您的代碼發佈到jsFiddle,以便我們可以看一看。 –
嗨,感謝您的幫助,但是我的html和javascript全部都與Ruby on Rails的東西聯繫在一起。不知道如何將它們分開......無論如何,我粘貼了我認爲是jsfiddle上的相關代碼......感謝任何幫助:http://jsfiddle.net/Christophe1/GpkYY/ – CHarris