我正在尝试优化我的地理编码脚本而不是它实际上有效,我想知道当用户从下拉列表中选择自动建议时是否可以实际启动地理编码。
这样,当用户单击搜索按钮时,地理编码将完成,他们不必等待。当用户单击自动建议的位置时,是否可以使用某种事件来触发地理编码?
这是代码
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>