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.

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog