duanmuyao0463 2014-02-08 10:42
浏览 39
已采纳

Google Maps Javascript API v3函数getPlace()返回undefined

I am using the Google Place service to obtain the place details for a result coming out from an auto complete. The problem is that executing getPlace() request on my autocomplete object returns undefined for the variable (var place). Have been around this issue for days now, can't get on it.

My page is : here, and the example I am following is here.

error:

TypeError: place is undefined [testdebug.php:232]

main pieces of code:

window['auto_'+inputFieldID+'_autocomplete'] = new google.maps.places.Autocomplete(document.getElementById(inputFieldID));
window['auto_'+inputFieldID+'_autocomplete'].bindTo('bounds', map);

var place = window['auto_'+GoogleMapItems[LoopIndex]+'_autocomplete'].getPlace();

if (!place.geometry) 
{
console.log('cannot resolve rendering.');
}

Thanks for your help.

  • 写回答

1条回答 默认 最新

  • douan6931 2014-02-08 12:38
    关注

    Closure issue: loop index is used as 1 (value when loop finishes) instead of 0.

    You can fix it using closure for loop index around event listener:

    (function(LoopIndex) {
        google.maps.event.addListener(window['auto_'+GoogleMapItems[LoopIndex]+'_autocomplete'], 'place_changed', function() 
        ...         {
        });
    
    })(LoopIndex);
    

    This is one fix. Now another issue occurs: points is not defined

    You are using variable points which seems has to contain information about markers. It is not defined in your code.

    Update: Code as it is written now sets event listener to departure autocomplete only. See for loop. The only valid index is 0. If I load the page and write for example s into departure input I can select for example Sydney, New South Wales, Australia. After selection I get in console index 1 (which is wrong), GoogleMapItems[LoopIndex] returns arrival (which is wrong) and places are undefined which is correct because there is nothing in arrival autocomplete input. This is typical closure issue.

    With my code change and selection from departure autocomplete I get loop index 0, GoogleMapItems[LoopIndex] returns departure, I get complete information for place, map is zoomed to Sydney and code fails because variable points is undefined.

    So, variable points has to be defined somewhere and for loop has to be expanded to handle also other autocomplete parts of page.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题