2013-10-09 69 views
0

我想在我的JavaScript中使用计时器来每隔5秒从cshtml中的其他对象轮询某些数据,并将其更新到javascript中的函数中。函数在javascript中未定义

我已经探索了用下面的代码,但它似乎扔初始化的错误是不确定

function initialize() { 

    var mapProp = { 
     center: new google.maps.LatLng(51.508742, -0.120850), 
     zoom: parseInt(5), 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 
    var map = new google.maps.Map(document.getElementById("googleMap") 
     , mapProp); 


} 

$(document).ready(function() { 
    initialize(); 
}); 
window.setInterval(function() { 
    /// call your function here 
    initialize(); 
}, 5000); 

然而,这工作完全正常

function initialize() { 

    var mapProp = { 
     center: new google.maps.LatLng(51.508742, -0.120850), 
     zoom: parseInt(5), 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 
    var map = new google.maps.Map(document.getElementById("googleMap") 
     , mapProp); 


} 

$(document).ready(function() { 
    initialize(); 
}); 

因为我想使变量全球这样我可以更新地图上每5秒钟,我试图使它成为一个全局变量的焦点

var mapProp = { 
     center: new google.maps.LatLng(51.508742, -0.120850), 
     zoom: parseInt(5), 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 

但是,似乎脚本不断给我一个错误的谷歌是未定义的。

无论如何,我可以解决我的问题。

例如,我想每5秒更新一次google.maps.LatLng(51.508742,-0.120850)中的参数。

+0

如果你使用'var'关键字在函数内部则是*不*全局变量,它的作用范围包括该功能。 –

+0

没有什么全局变量 - 它设置局部变量 - 全局变量是键入**没有var **或显式为一个窗口属性=>'window.myVariable =“东西”;' –

+3

您是否包含脚本? –

回答

1

这里是工作的代码,

<!DOCTYPE html> 
<html> 
    <head> 
     <script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false"> 
     </script> 
     <script src="http://code.jquery.com/jquery-1.9.0.min.js"></script> 
     <script> 
      var mapProp; 
      $(document).ready(function(){initialize();}) 
      function initialize() 
      { 
       mapProp = changeMapProp(); 
       var map=new google.maps.Map(document.getElementById("googleMap") 
       ,mapProp); 
      } 
      function changeMapProp() { 
       mapProp = { 
        center:new google.maps.LatLng(52.508742,-0.120850), 
        zoom:5, 
        mapTypeId:google.maps.MapTypeId.ROADMAP 
       }; 
       return mapProp; 
      } 
      window.setInterval(function() { 
       /// call your function here 
       initialize(); 
      }, 5000); 

     </script> 
    </head> 

    <body> 
     <div id="googleMap" style="width:500px;height:380px;"></div> 

    </body> 
</html> 
1

尝试:

var mapProp; 
var map; 

var initialize = function() { 

    mapProp = { 
     center: new google.maps.LatLng(51.508742, -0.120850), 
     zoom: parseInt(5), 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 
    map = new google.maps.Map(document.getElementById("googleMap") 
     , mapProp); 

} 

$(document).ready(function() { 

    setTimeout(initialize, 5000); 

}); 
+0

调试器在window.setinterval函数初始化时显示错误 – aceminer

+0

现在你可以试试,回答更新。 – Salim

1

你不能让var mapProp全球,因为它会触发center: new google.maps...直去,你google变量不会到位,但(这就是为什么你会得到谷歌未定义)。

关于初始化定义,把你的setInterval里面你$(document).ready功能。