【问题标题】:InvalidValueError: setMap: not an instance of Map, and not an instance of StreetViewPanoramaInvalidValueError:setMap:不是 Map 的实例,也不是 StreetViewPanorama 的实例
【发布时间】:2014-07-17 07:49:00
【问题描述】:

当我测试我的站点跨浏览器并在 Safari 中尝试时,我的仪表板中的这个错误突然出现。它适用于 Chrome、Firefox 和 IE9,但适用于 Safari:

这是错误,我不知道发生在哪里

InvalidValueError: setMap: not an instance of Map, and not an instance of StreetViewPanorama     main:25

这是初始化函数:

var map;

    function initialize() {

        geocoder = new google.maps.Geocoder();
        geocode = new google.maps.Geocoder();

        LatLang = new google.maps.LatLng(38.50, -90.50);
        var addresse = {
            zoom: 4,
            center: LatLang,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map'), addresse);

        // Bounds for North America
        var strictBounds = new google.maps.LatLngBounds(
                  new google.maps.LatLng(15.70, -160.50),
                  new google.maps.LatLng(68.85, -55.90));

        // Listen for the dragend event
        google.maps.event.addListener(map, 'dragend', function () {
            if (strictBounds.contains(map.getCenter())) return;
            // We're out of bounds - Move the map back within the bounds

            var c = map.getCenter(),
                  x = c.lng(),
                  y = c.lat(),
                  maxX = strictBounds.getNorthEast().lng(),
                  maxY = strictBounds.getNorthEast().lat(),
                  minX = strictBounds.getSouthWest().lng(),
                  minY = strictBounds.getSouthWest().lat();

            if (x < minX) x = minX;
            if (x > maxX) x = maxX;
            if (y < minY) y = minY;
            if (y > maxY) y = maxY;

            map.setCenter(new google.maps.LatLng(y, x));
        });

        // Limit the zoom level
        google.maps.event.addListener(map, 'zoom_changed', function () {
            if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
        });

    }

【问题讨论】:

  • 这将有助于了解您的代码的哪一行导致了此异常,即调用地图库并遇到此情况的行。在调试器中逐行遍历代码,直到发生异常,或打开 Break On Unhandled Exceptions(例如在 Chrome 开发工具中)以捕获发生的异常,然后将堆栈跟踪回溯到代码以识别最后一行运行良好的代码。

标签: javascript google-maps safari


【解决方案1】:

你需要了解一些 safaris 和 javascripts quark 来解决这个问题。

var t = 5;
var t
console.log(t) //undefined in chrome, firefox, etc. But 5 in safari.

您还应该知道,在新的 html5 规范中,如果您有类似 &lt;div id="map"&gt;&lt;/div&gt; 的内容,这将创建一个全局变量 mapwindow.map

在您的代码中,我看到您将map 定义为全局变量(可能用于调试)。

如果此脚本在 &lt;body&gt;...&lt;/body&gt; 渲染后运行,其中包含您的 &lt;div id="map"&gt;&lt;/div&gt;window.map 或(全局 map),则初始化为 "&lt;div id="map"&gt;&lt;/div&gt;",并且当您再次声明 var mapmap在 Safari 中变为 &lt;div id="map"&gt;&lt;/div&gt;,在其余浏览器中变为 undefined

这是错误的原因。要解决此问题,请将 id 更改为 map 以外的其他值,或者在将其声明为全局变量时执行 var map = "";。或者,在正文之前运行脚本。

【讨论】:

    猜你喜欢
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 2020-02-13
    • 2019-10-28
    • 2016-03-07
    • 2019-05-17
    • 2013-10-19
    相关资源
    最近更新 更多