我正在尝试在 javascript 中使用计时器,每 5 秒从 cshtml 中的其他对象轮询某些数据,并将其更新到 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 秒更新一次 map 上的焦点,因此我尝试将其设为全局变量
var mapProp = {
center: new google.maps.LatLng(51.508742, -0.120850),
zoom: parseInt(5),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
但是,脚本似乎一直给我一个 google is undefined 的错误。
无论如何我可以解决我的问题吗?
例如,我想每 5 秒更新一次 new google.maps.LatLng(51.508742, -0.120850) 中的参数。
最佳答案
这是工作代码,
<!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>
关于javascript - JavaScript 中函数未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19267269/