我試圖優化我的地理編碼腳本並不在於它的實際工作,我想知道,如果當用戶選擇從下拉的自我暗示有可能實際啓動地理編碼。谷歌地圖地理編碼 - 在自動提示地理編碼點擊
這樣的地理編碼將是用戶點擊搜索按鈕的時間完成,並且他們不會等待。當用戶點擊自動創建的位置時,是否可以使用某種事件觸發地理編碼?
這是代碼
http://jsfiddle.net/sR4GR/22/
原始的Javascript
<script type="text/javascript" src="//maps.google.com/maps/api/js?sensor=true&libraries=places"></script>
<script type="text/javascript">
// SET COOKIE FOR TESTING
$.cookie("country", "UK");
// GEOCODE RESULT
function geocode() {
var GeoCoded = {
done: false
};
var input = document.getElementById('loc');
var options = {
types: ['geocode']
};
var country_code = $.cookie('country');
if (country_code) {
options.componentRestrictions = {
'country': country_code
};
}
var autocomplete = new google.maps.places.Autocomplete(input, options);
$('#searchform').on('submit', function(e) {
if (GeoCoded.done) return true;
e.preventDefault();
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('loc').value;
$('#searchform input[type="submit"]').attr('disabled', true);
geocoder.geocode({
'address': address
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
GeoCoded.done = true;
$.cookie("location_input", $("#loc").val());
$.cookie("lng", $("#lng").val());
$.cookie("lat", $("#lat").val());
$('#searchform').submit();
} else {
$('#searchform input[type="submit"]').attr('disabled', false);
alert("We couldn't find this location")
}
});
});
};
</script>
<body onload="geocode()">
<form id="searchform">
<input class="kw" id="keyword" placeholder="Keyword"></input>
<input id="loc" placeholder="Location" type="text"></input>
<input type="submit" value="Search" id="search">
<input class="hidden" id="lat" disabled="true" placeholder="lat"></input>
<input class="hidden" id="lng" disabled="true" placeholder="lng"></input>
</form>
那看起來就是我所追求的,除非我無法實現它。對於我的例子,它不應該像這樣簡單嗎? google.maps.event.addListener(autocomplete,'place_changed',function(){ geocode() }); – Jimmy 2013-05-13 12:02:54
沒有,要定義地理編碼函數內部自動完成,你不能事件處理程序的定義之前綁定到它,我想你應該把這個事件處理程序自動完成創建後馬上使用您在申請提交searchform – paulitto 2013-05-13 12:09:19
相同的功能,我認爲你的說明是正確的,但我不能得到它的工作,我是新來的JavaScript,似乎這東西是有點高於我。這是我試過的:http://jsfiddle.net/sR4GR/23/ – Jimmy 2013-05-13 12:15:41