谷歌地图自动完成Wordpress

时间:2016-09-08 19:37:25

标签: jquery wordpress google-maps

我有一个页面,在邻居字段中启用了谷歌地图自动完成功能,用于过滤搜索结果。我想在City字段上自动完成。拼命地尝试和失败 The url of the page.

C / o请点击右上角过滤结果切换到右上角以查看字段。

if($('#search_city').length > 0) {
    var city= document.getElementById('search_city');
    var cityAuto= new google.maps.places.Autocomplete(city);
    google.maps.event.addListener(cityAuto, 'place_changed', function() {
        var place = cityAuto.getPlace();
        $('#search_city').blur();
        setTimeout(function() { $('#search_city').val(place.address_components[0].short_name); }, 1);

        return false;
    });

}

1 个答案:

答案 0 :(得分:0)

这里只是一些一般性建议,如果您的对象未定义,它可能对您有所帮助。

将代码更改为true jQuery,并将对象缓存在变量中。此外,最好使用$为所有jQuery包装对象做好准备。

//if your code isn't already in a document ready function, keep this.  if not, delete the following line and the last line, `});`
$(document).ready(function(){

    var $searchCity = $("#search_city"); //cache object to prevent querying for it again

    if($searchCity.length > 0) {
        //$searchCity already set, don't set it again

        var cityAuto = new google.maps.places.Autocomplete($searchCity);
        //var cityAuto = new google.maps.places.Autocomplete($searchCity[0]); //if Google wants a raw DOM object, use this line, delete the above line - the [0] gives you the DOM object from a jQuery object

        google.maps.event.addListener(cityAuto, 'place_changed', function() {
            var place = cityAuto.getPlace();
            $searchCity.blur();

            setTimeout(function() {
                $searchCity.val(place.address_components[0].short_name); 
            }, 1);

            return false;
        });
    }
});

如果有效,请告诉我。