javascript - onclick 移动谷歌地图中心点

标签 javascript jquery google-maps google-maps-api-3

我已经初始化了 Google map load 功能,并且工作正常。还有多个带有簇的标记。我没有在这里放置标记和簇代码。这些是标准代码。我的代码:

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

function initialize() {
    var center = new google.maps.LatLng(59.875405, 10.842099);
    var zoom = 10;
    var map = new google.maps.Map(document.getElementById('map-canvas'), {
        zoom: zoom,
        center: center,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
}
function mapAnimate(){
    var map = google.maps.Map(document.getElementById("map-canvas"));
    google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
        window.setTimeout(function() {
            map.panTo(new google.maps.LatLng(58.9633, 5.7189));
        }, 500);
    });
}

然后我想将 map 移动到另一个中心位置而不重新生成 map 。有一个调用函数 mapAnimate() 的链接。

HTML:

<a href="javascript:void(0);" onclick="mapAnimate()">test</a>

但是它不起作用。我收到这样的错误:

TypeError: c[Eb] is not a function......

实际上我没有得到 map 实例。

最佳答案

在函数外部声明您的 map 变量。这应该可以解决问题。

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

var map;

function initialize() {
    var center = new google.maps.LatLng(59.875405, 10.842099);
    var zoom = 10;
    map = new google.maps.Map(document.getElementById('map-canvas'), {
        zoom: zoom,
        center: center,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
}
function mapAnimate(){

    google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
        window.setTimeout(function() {
            map.panTo(new google.maps.LatLng(58.9633, 5.7189));
        }, 500);
    });
}

但是,如果您从点击事件调用 mapAnimate() 函数,我不明白为什么您需要在 map 对象上使用该监听器。

关于javascript - onclick 移动谷歌地图中心点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22661785/

相关文章:

javascript - "Message": "Invalid web service call, 参数缺失值:\u0027

javascript - AJAX 向 Python Flask 发送请求

google-maps - 如何将动态谷歌地图添加到我的网站?

javascript - 谷歌地图 Ya、Za 和 $a

javascript - 使用 ui-router 时谷歌地图不显示

javascript - 更改 Angular MD 中的选择状态时,$watch 未触发

javascript - 在 IE11 中使用指针事件时防止单击?

Javascript循环创建函数并使用收到的基于PHP查询的id附加值

javascript - Angular Directive 未运行且 templateUrl 未显示

javascript - 如何使用 Id 禁用输入框,同时使用克隆方法在表中添加新行?