使用 Google 地图建议和 focusout 地理编码生成动态输入数组

Generating array of dynamics input with Google maps suggestion and focusout geocode

我正在开发一个脚本,您可以添加多个目的地,输入是使用 jquery 动态生成的,并向每个输入添加 google 地点建议。 因此,当用户写入一个城市并且 Focus Out 事件自动发生时,尝试对该城市进行地理编码。这部分一切正常,问题是当用户只写城市名称部分并用鼠标按下建议时,在城市名称完全写入之前生成焦点事件。

示例:我正在搜索 "Porto, Portugal",我只需要为 google 写 "Po" - 建议建议我 "Porto, Portugal" 但问题是按鼠标移开他只是将 "Po" 发送到 google-geocode 检索不同的结果 "Pau, France"。

刚刚捕获的结果"Po"

这是我正在使用的代码:

<!DOCTYPE html>
<html>
<head>
<title>Add or Remove text boxes with jQuery</title>
<script type="text/javascript" src="//code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3&libraries=places&language=en"></script>
<script type="text/javascript">
window.onload = function () {
    var input = /** @type {HTMLInputElement} */(document.getElementById('box1'));
    var autocomplete = new google.maps.places.Autocomplete(input,{types: ['geocode']});
}

$(window).load(function() {
    //check if the user FocusOut if yes start looking for geocoding
    $(document).on('focusout','.autocomplete',function() {
        LocationValidator(this.value);
    });
});
</script>


<style type="text/css">
<!--
#main {
    max-width: 800px;
    margin: 0 auto;
}
.autocomplete{
    width:280px;    
}
-->
</style>
</head>
<body>

<div id="main">
    <h1>Add or Remove text boxes with jQuery</h1>
    <div class="my-form">
        <form role="form" method="post" id="sendDestiny" action="mapAddSave.php">
            <p class="text-box">
                <label for="box1">Destiny <span class="box-number">1</span></label>
                <input class="autocomplete" type="text" name="boxes[]" value="" id="box1" onkeydown="if (event.keyCode == 13) return false;" />
                <a class="add-box" href="#">Add More</a>
            </p>
            <p><input type="submit" value="Submit" /></p>
        </form>
    </div>
</div>


<script type="text/javascript">
jQuery(document).ready(function($){
    //Add extra box
    $('.my-form .add-box').click(function(){
        var n = $('.text-box').length + 1;
        if( 5 < n ) {
            alert('You have reached the maximum!');
            return false;
        }
        var box_html = $('<p class="text-box"><label for="box' + n + '">Destiny <span class="box-number">' + n + '</span></label> <input class="autocomplete" type="text" name="boxes[]" value="" id="box' + n + '" onkeydown="if (event.keyCode == 13) return false;" /> <a href="#" class="remove-box">Remove</a></p>');
        box_html.hide();
        $('.my-form p.text-box:last').after(box_html);
        box_html.fadeIn('slow');


        var acInputs = document.getElementsByClassName("autocomplete");
        for (var i = 0; i < acInputs.length; i++) {
            var autocomplete = new google.maps.places.Autocomplete(acInputs[i],{types: ['geocode']});
        }
        return false;
    });
    //Remove one existing box
    $('.my-form').on('click', '.remove-box', function(){
        $(this).parent().css( 'background-color', '#FF6C6C' );
        $(this).parent().fadeOut("slow", function() {
            $(this).remove();
            $('.box-number').each(function(index){
                $(this).text( index + 1 );
            });
        });
        return false;
    });
});



function LocationValidator(value) {
    var address = "";
    var geocoder = new google.maps.Geocoder();

    geocoder.geocode({ 'address': value }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var latitude = results[0].geometry.location.lat();
            var longitude = results[0].geometry.location.lng();
            address = results[0].formatted_address;

            // iterate through address_component array and Get City and Country
            var arrAddress = results[0].address_components; itemLocality=""; itemCountry="";
            $.each(arrAddress, function (i, address_component) {
                if (address_component.types[0] == "locality"){
                    itemLocality = address_component.long_name;
                }
                if (address_component.types[0] == "country"){ 
                    itemCountry = address_component.long_name;
                }
            });
            NextFunction(latitude,longitude,itemLocality,itemCountry);
        } else {
            //call function telling that happen erro
        }
    });
}

function NextFunction(latitude,longitude,itemLocality,itemCountry)
{
  //do your next thing here....
  alert("nextFunction: "+latitude+" "+longitude+" city:"+itemLocality+" Country:"+itemCountry);
}
</script>
</body>
</html>

jsfiddle working exemple

有人对如何解决这个问题有什么建议吗? 已经尝试使用事件 focusout 和 blur

提前致谢!!!

根据 MrUpsidown 和 ztan 的评论使用 place_changed 我制作了下一个代码:

google.maps.event.addListener(autocomplete, 'place_changed', function(){
    var place = autocomplete.getPlace();
    LocationValidator(place.formatted_address);
});

我使用 formatted_address 获得了更好的结果,因为 place.name 产生了不明确的结果。

Documentation about details of results