为什么谷歌地图getPlace()总是返回未定义的对象?

时间:2016-12-28 09:47:31

标签: google-maps google-maps-api-3 google-places-api

这是我用于getPlace()的函数,它始终返回undefined个对象:

var element = document.getElementById('hdnOldAddress');
var AutoCompleteAddress2;
element.value = 'Marketfair Mall 1916 Skibo Road  Fayetteville  NC 28314';

autocomplete2 = new google.maps.places.Autocomplete(element);


autocomplete2.addListener('place_changed', function () {
    var place2 = autocomplete2.getPlace();
    if (place2.address_components) {
        AutoCompleteAddress2 = [
            (place2.address_components[0] && place2.address_components[0].short_name || ''),
            (place2.address_components[1] && place2.address_components[1].short_name || ''),
            (place2.address_components[2] && place2.address_components[2].short_name || ''),
            (place2.address_components[3] && place2.address_components[3].short_name || ''),
            (place2.address_components[4] && place2.address_components[4].short_name || ''),
            (place2.address_components[5] && place2.address_components[5].short_name || ''),
            (place2.address_components[6] && place2.address_components[6].short_name || ''),
            (place2.address_components[7] && place2.address_components[7].short_name || ''),
            (place2.address_components[8] && place2.address_components[8].short_name || ''),
            (place2.address_components[9] && place2.address_components[9].short_name || ''),
            (place2.address_components[10] && place2.address_components[10].short_name || ''),
            (place2.address_components[11] && place2.address_components[11].short_name || ''),
            (place2.address_components[12] && place2.address_components[12].short_name || ''),
            (place2.address_components[13] && place2.address_components[13].short_name || ''),
            (place2.address_components[14] && place2.address_components[14].short_name || ''),
        ].join(' ');
    }
});
google.maps.event.trigger(autocomplete2, 'place_changed');

修改

this.getPlace()

替换autocomplete2.getPlace()

2 个答案:

答案 0 :(得分:1)

这是我在上面使用的替代品。我没有使用Autocomplete()我使用AutocompleteService()返回predicted个地点并使用该地址我将其传递给geocodingmap显示位置如预期的那样。

var service = new google.maps.places.AutocompleteService();
service.getPlacePredictions({ input: 'Marketfair Mall 1916 Skibo Road  Fayetteville  NC 28314' }, function (predictions, status) {                    
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        matchAddress = predictions[0].structured_formatting.secondary_text; 
        //Add further processing for geocoding for found address.
    }
});

答案 1 :(得分:0)

编辑:没关系,我错了。在此代码中,this = autocomplete2。

问题是没有触发place_changed ......

你遇到的一个问题是"这个"不是你想要的。你不能使用"这个" (意思是自动完成的实例)在处理事件的函数中(在place_changed上)。在这些事件函数中,此变量表示受影响的元素(单击,悬停,...)

试试这个:

替换var place2 = this.getPlace(); by var place2 = autocomplete2.getPlace();

让我知道是否修复了它(否则我们需要进一步研究)