未捕获的ReferenceError:未定义mapCenterAt

时间:2013-08-21 18:06:52

标签: jquery google-maps

我收到错误Uncaught ReferenceError:mapCenterAt未使用以下脚本定义:

<script>
jQuery(document).ready(function ($) {

    // Map Markers
    var mapMarkers = [{
        address: "217 Summit Boulevard, Birmingham, AL 35243",
        html: "<strong>Alabama Office</strong><br>217 Summit Boulevard, Birmingham, AL 35243<br><br>
        <a href='#' onclick='mapCenterAt({latitude: 33.44792, longitude: -86.72963, zoom: 16}, event)'>[+] zoom here</a>",
        icon: {
            image: "img/pin.png",
            iconsize: [48, 48],
            iconanchor: [48, 48]
        }
    }];

    // Map Initial Location
    var initLatitude = 37.09024;
    var initLongitude = -95.71289;

    // Map Extended Settings
    var mapSettings = {
        controls: {
            panControl: true,
            zoomControl: true,
            mapTypeControl: true,
            scaleControl: true,
            streetViewControl: true,
            overviewMapControl: true
        },
        scrollwheel: false,
        markers: mapMarkers,
        latitude: initLatitude,
        longitude: initLongitude,
        zoom: 5
    };

    var map = $("#googlemaps").gMap(mapSettings);

    // Map Center At
    var mapCenterAt = function(options, e) {
        e.preventDefault();
        $("#googlemaps").gMap("centerAt", options);
    }
});
</script>   

mapCenterAt在脚本底部定义,但在页面上执行onclick时会抛出错误。 mapCenter是否需要以不同的方式定义才能使用onclick?

1 个答案:

答案 0 :(得分:0)

jQuery的文档就绪处理程序创建了一个不同的作用域,因此内联onclick处理程序无法使用mapCenterAt函数,因为它位于全局范围内,比文档就绪范围更高。

您必须使用全局范围:

window.mapCenterAt = function(options, e) {
    e.preventDefault();
    $("#googlemaps").gMap("centerAt", options);
}

或创建一个合适的事件处理程序:

<script>
jQuery(document).ready(function ($) {
    // Map Markers
    var mapMarkers = [{
        address: "217 Summit Boulevard, Birmingham, AL 35243",
        html: "<strong>Alabama Office</strong><br>217 Summit Boulevard, Birmingham, AL 35243<br><br><a href='#' id='mapButton'>[+] zoom here</a>",
        icon: {
            image: "img/pin.png",
            iconsize: [48, 48],
            iconanchor: [48, 48]
        }
    }];

    // Map Initial Location
    var initLatitude = 37.09024;
    var initLongitude = -95.71289;

    // Map Extended Settings
    var mapSettings = {
        controls: {
            panControl: true,
            zoomControl: true,
            mapTypeControl: true,
            scaleControl: true,
            streetViewControl: true,
            overviewMapControl: true
        },
        scrollwheel: false,
        markers: mapMarkers,
        latitude: initLatitude,
        longitude: initLongitude,
        zoom: 5
    };

    var map = $("#googlemaps").gMap(mapSettings);

    $(document).on('click', '#mapButton', function(e) {
        e.preventDefault();
        $("#googlemaps").gMap("centerAt", {latitude: 33.44792, longitude: -86.72963, zoom: 16});
    });
});
</script>