【问题标题】:Elabel undefined error in Google Maps V3Google Maps V3 中的 Elabel 未定义错误
【发布时间】:2013-07-04 04:45:04
【问题描述】:

我一直在将我的脚本从 V2 移植到 V3,但遇到了障碍。我收到一个 Elabel 未定义错误,但我不确定我为什么会收到这个错误。我已将 Elabel.js 更新为 V3,这里是...ELABLE.JS我不确定这是否不是 ELabel.js 的好副本或什么。我尝试了几个不同的其他副本,但没有成功。

这是使用 V2 的工作示例

V2 EXAMPLE

这是 V3 示例。正如您在 V3 中看到的那样,范围环没有绘制,地图没有更新,表格也没有填充。我知道它与 ELabel.js 有关,但我不知道为什么,也找不到导致我收到未定义错误的问题。我知道这与此有关,因为当我删除 ELable.js 的脚本包含时,我在 V2 上遇到了与在 V3 上看到的相同的问题。

V3 EXAMPLE

由于代码太长,这里就不贴了,相关代码的链接在下面的链接中。第 135 行是 ELabel 错误的来源。这在 V2 中效果很好,但在 V3 中效果不佳。所以我不知道我是否忽略了从 V2 到 V3 的一些变化。

EXAMPLE CODE

那么任何人都可以就我为什么会收到这个未定义的错误提供任何见解,并阐明我可能做错了什么和忽略了什么?

-谢谢

【问题讨论】:

  • 整个页面看起来像是十年前写的,可以改头换面。全局命名空间使用得很好,包含了 jQuery 但很少使用——许多功能将大大简化。实际问题必须是范围或加载顺序。由于 ELabel 是在全局命名空间中定义的,因此不太可能是作用域。这也不是明显的加载顺序,但您可以尝试将<script src="elabel2.js" ...> 移动到文档头部。从 621 到 947 的大脚本也应该放在头上(小心)。
  • 另外,看看updateHTML()。当数组已经分配给result时,resp.split("|")被调用了多少次?
  • @Beetroot-Beetroot 是的,代码是几年前编写的。我没有写。我只是想尽我所能用我所知道的来更新它。所以我没有太多的背景。我已经移动了一些东西并更好地组织了订单,但我仍然收到错误消息。这是更新的地图代码nsgmap.js,这是整页V3 Map 需要注意的一点是,我可以让 Elabel 错误消失,从而改变订单,但随后我得到了一个未定义的 llcetner。我想不通。
  • 德克萨斯人,六个doDrawCircle() 命令块不在函数内。尝试将其移入initialize()UpdateKML(); 也是。
  • @Beetroot-Beetroot 感谢我做出这些更改的建议。我正在取得进展,因为表格现在正在填充数据。我现在收到关于这条线的“地图未定义”map.removeOverlay(nyLayer); 假设绘制范围环并倒计时并使用新数据自动更新地图。在我的原始帖子中查看我的 V2 示例与 V3 示例。 V2 是它的工作方式。这是更新的代码nsgmap.js 导致该错误的原因。我确信这是导致其余两个问题的原因。

标签: javascript google-maps google-maps-api-3 google-maps-api-2


【解决方案1】:

德克萨斯人,这是我本地文件中的 te 脚本,它可以显示圆圈和标签。所有 ajax 方面都未经测试。

下面的脚本应该粘贴到文档头部,紧接在结束</head>标签之前。

这取代了其他各种内联脚本。文档正文中唯一剩下的脚本应该是 google analytics(2 个脚本)和 StatCounter(1 个脚本)。不应删除任何外部脚本。

<script>
var map;

jQuery(function($) {
    var llCenter = new google.maps.LatLng(32.8297,-96.6486);
    var URLToKML = 'http://www.mesquiteweather.net/NSGMap/GMStrikes.kml';
    var Sec2Update = 30;
    var KMLdate = 1372820133;
    //var NSdate = 1372927434;
    var NSdate = 0; //Force KML file creation on first update
    var TZString = 'CDT';
    var TZOffset = -5;

    var nyLayer;
    var lcolor = 'white';//This defines the line color for the target circle

    //Check if user wants debug mode
    dbg = (gup('dbg')=='y') ? 'y' : 'n';
    var force = (gup('force')=='y') ? 'y' : 'n';  //Force updates regardless of NSStrikes.txt date

    var mapReady = false;

    function initialize() {
        var mapOptions = {
            center: llCenter,
            panControl: false,
            zoom: 6,
            mapTypeControl: true,
            mapTypeControlOptions: {
                style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
            },
            zoomControl: true,
            zoomControlOptions: {
                style: google.maps.ZoomControlStyle.SMALL,
                position: google.maps.ControlPosition.RIGHT_TOP
            },
            mapTypeId: google.maps.MapTypeId.HYBRID
        };

        map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

        var radarOptions = {
            gmap: map,
            name: 'Radar',
            position: google.maps.ControlPosition.TOP_RIGHT,
            action: function(){
                if (map.overlayMapTypes.length==0) {
                    map.overlayMapTypes.push(null); // create empty overlay entry
                    map.overlayMapTypes.setAt("1", tileNEX);
                }
                else {
                    map.overlayMapTypes.clear();
                }
            }
        }
        var radarButton = new buttonControl(radarOptions);
        tileNEX = new google.maps.ImageMapType({
            getTileUrl: function(tile, zoom) {
                return "http://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q-900913/" + zoom + "/" + tile.x + "/" + tile.y +".png?"+ (new Date()).getTime();
            },
            tileSize: new google.maps.Size(256, 256),
            opacity: 0.70,
            name: 'NEXRAD',
            isPng: true
        });

        function MyLogoControl() {
            var logo = $('<img/>').attr('src', 'images/watermark_MW_GMap.png').css('cursor', 'pointer').get(0);
            google.maps.event.addDomListener(logo, 'click', function() {
                window.location = 'http://www.mesquiteweather.net';
            });
            return logo;
        }
        var logoControlDiv = $('<div/>').css('padding','5px').append(MyLogoControl()).get(0);
        logoControlDiv.index = 0; // used for ordering
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(logoControlDiv);
        var nyLayer = new google.maps.KmlLayer(URLToKML + "?rand=" + (new Date()).valueOf(), {
            suppressInfoWindows: false,
            map: map,
            preserveViewport: true
        });

        google.maps.event.addListenerOnce(map, 'idle', function() {
            //You can add circles, or change other parameters
            //radials should be set to true for the maximum distance if you want radials
            //doDrawCircle(circleUnits, center, circleRadius, lineColor, lineWidth, lineOpacity, fillColor, fillOpacity, opts, radials)
            doDrawCircle('MI', llCenter,  62, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
            doDrawCircle('MI', llCenter, 124, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
            doDrawCircle('MI', llCenter, 187, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
            doDrawCircle('MI', llCenter, 249, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
            doDrawCircle('MI', llCenter, 312, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
            doDrawCircle('MI', llCenter, 374, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
            //doDrawCircle('MI', llCenter, 374, lcolor, 1, .7, '#00FF00', 0, { clickable: false }, true);   // This would add the radials

            UpdateKML();//Get the first set of data
        });
    }

    //Function to draw circles
    function doDrawCircle(circleUnits, center, circleRadius, liColor, liWidth, liOpa, fillColor, fillOpa, opts, radials) {
        var polyLineOptions = {
            map: map,
            path: null,//added with jQuery.extend()
            strokeColor: liColor,
            strokeOpacity: liOpa,
            strokeWeight: liWidth
        };
        var bounds = new google.maps.LatLngBounds();
        var circlePoints = [];
        var d = circleRadius / ((circleUnits == 'KM') ? 6378.8 : 3963.189);
        var d2r = Math.PI/180;
        var lat1 = d2r * center.lat();//radians
        var lng1 = d2r * center.lng();//radians
        for (var a=0; a<361; a++ ) {
            var tc = d2r * a;
            var sin_lat1 = Math.sin(lat1),
                cos_lat1 = Math.cos(lat1),
                sin_d = Math.sin(d),
                cos_d = Math.cos(d),
                sin_tc = Math.sin(tc),
                cos_tc = Math.cos(tc);
            var y = Math.asin(sin_lat1 * cos_d + cos_lat1 * sin_d * cos_tc);
            var dlng = Math.atan2(sin_tc * sin_d * cos_lat1, cos_d - sin_lat1 * Math.sin(y));
            var x = ((lng1 - dlng + Math.PI) % (2 * Math.PI)) - Math.PI ; // MOD function
            var point = new google.maps.LatLng(y/d2r, x/d2r);
            circlePoints.push(point);
            bounds.extend(point);
            if(a==0) {
                var offset = new google.maps.Size((circleRadius < 100) ? -5 : -8, 0);
                //ELabel(map, point, html, classname, pixelOffset, percentOpacity, isFloatShadow, overlap);
                var label = new ELabel(map, point, circleRadius, "style1", offset, 100, false);
                label.setMap(map);
            }
            if (radials && ((a==0) || (a==45) || (a==90) || (a==135) || (a==180) || (a==225) || (a==270) || (a==315))) {
                new google.maps.Polyline($.extend({}, polyLineOptions, {
                    path: [center, point]
                }));
            }
        }
        new google.maps.Polyline($.extend({}, polyLineOptions, {
            path: circlePoints
        }));
        map.fitBounds(bounds);//This sets the map bounds to be as big as the target circles, comment out if you don't want it
    }

    //This function is called on page load to start the refresh of the strikes
    function cycle() {
        setInterval(CountDown, 1000);
    }
    var intvl = Sec2Update;

    function CountDown() {
        intvl -= 1;
        if(intvl < 1) {
            intvl = Sec2Update;
            UpdateKML();
        }
        $("#cntdwn").html(intvl);
    }

    //This calls genkml.php on every refresh cycle to generate a new kml file
    function UpdateKML() {
        $.ajax({
            url: 'genkml.php',
            type: "GET",
            data: {
                force: force,
                ofd: KMLdate,
                nsd: NSdate, 
                dbg: dbg
            },
            cache: false,
            dataType: '',//????
        }).done(function(resp, textStatus) {
            var $debugDiv = $("#div1");
            if (dbg == 'y') {//Check if we want debug info
                if (!$debugDiv.length) {//Check if debug div exists, if not add it to end of body
                    $debugDiv = $("<div/>").attr('id', 'div1').appendTo('body');
                }
                var tmpresp = resp || ' ';
                $debugDiv.html('Response Status: ' + textStatus + '<br />' + tmpresp);
            } else {//Else empty the debug div
                $debugDiv.empty();
            }
            var dates = resp.split("|")[0].split("~");
            KMLdate = dates[0];
            NSdate = dates[1];
            updateHTML(resp);//This calls the updateHTML function if info was returned
        });

        if(map) {
            if(nyLayer) {
                map.removeOverlay(nyLayer); //Remove overlays
            }

            //nyLayer = new KmlLayer(URLToKML + "?rand="+(new Date()).valueOf() );
            nyLayer = new google.maps.KmlLayer(URLToKML + "?rand=" + (new Date()).valueOf(), {
                suppressInfoWindows: false,
                map: map,
                preserveViewport: true
            });
        }
        // Time overlayed on map - could be in updateHTML() to just show when .kml read last
        $('#currenttime').innerHTML = CurrentTime ("B", "12a", true, TZOffset);
    }

    function CurrentTime (type, hours, secs, ofs) {
        /*
        type (char)           hours (char)      secs (bool)     ofs (num)
        "U"-UTC               "24"=24 hr time   true=hh:mm:ss   0=hours from UTC
        "B"-User's Browser    "12"=12 hr time   false=hh:mm
        "S"-Web Site          "12a"=am/pm
        */
        if (type  == null){ type  = "B"; }     // These are the defaults
        if (hours == null){ hours = "12a"; }
        if (secs  == null){ secs  = true; }
        if (ofs   == null){ ofs   = 0; }
        var currentHour = 0;
        var currentMinute = 0;
        var currentSecond = 0;
        var time = [];
        var currentDate = new Date();

        if (type == "U") {
            currentHour = currentDate.getUTCHours();// UTC
        } else if (type == "B") {
            currentHour = currentDate.getHours();// Viewer's time
        } else {
            currentHour = currentDate.getUTCHours() + ofs;// your local time
            if(currentHour < 0) { currentHour = currentHour + 24;}
        }

        currentMinute = currentDate.getMinutes();
        currentMinute = (currentMinute < 10 ? "0" : "") + currentMinute;

        if (hours == "24") {
            if(currentHour == 24) { currentHour = 0 };// use if wanting 24 hour time
            currentHour = (currentHour < 10 ? "0" : "") + currentHour;
        } else if (hours == "12") {
            if(currentHour == 0) currentHour = 12;
            currentHour = (currentHour < 10 ? "0" : "") + currentHour;
        } else {
            if(currentHour == 0) currentHour = 12;// else no leading zero for am/pm
        }

        time.push(currentHour, currentMinute);

        if (secs) {
            currentSecond = currentDate.getSeconds();
            currentSecond = (currentSecond < 10 ? "0" : "") + currentSecond;
            time.push(currentSecond);
        }

        time = time.join(' : ');

        if(hours == "12a") {
            time = time + " " + (currentHour > 12 ? "PM" : "AM");
        }
        return time;
    }

    //This function is only used if you leave the debug checkbox below
    //  You can remove this function and the checkbox and set the debug
    //  mode using the dbg=y query parameter
    function debug(obj){
        if (obj.checked) {
            dbg = 'y';
        } else {
            dbg = 'n';
            $('#div1').empty();
        }
    }
    //This function is only used if you leave the Force Update checkbox below
    //  You can remove this function and the checkbox and set the force
    //  mode using the force=y query parameter
    function forceupdate(obj) {
        force = (obj.checked) ? 'y' : 'n';
    }
    //This function parses out the query parameter value
    function gup( name ) {
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);
        return results ? results[1] : "";
    }
    /*
    You can add custom HTML code here and get access to the additional data that is returned everytime the page calls genkml.php.  
    In the example below, result is an array that holds 16 values (17, if in debug mode) with each of the values explained below.
    */
    function updateHTML(resp) {
        var result = resp.split("|");
        if (result.length < 16) return;//Make sure there is data
        document.getElementById('q1').innerHTML = result[1];//Number of strikes in first quarter of diplay time
        document.getElementById('q2').innerHTML = result[2];//Number of strikes in second quarter of diplay time
        document.getElementById('q3').innerHTML = result[3];//Number of strikes in third quarter of diplay time
        document.getElementById('q4').innerHTML = result[4];//Number of strikes in fourth quarter of diplay time
        document.getElementById('numicp').innerHTML = result[6];//Number of IC+ strikes
        document.getElementById('numicn').innerHTML = result[5];//Number of IC- strikes
        document.getElementById('numcgp').innerHTML = result[7];//Number of CG+ strikes
        document.getElementById('numcgn').innerHTML = result[8];//Number of CG- strikes
        document.getElementById('ds').innerHTML = result[9];//Total displayed strikes
        document.getElementById('ta').innerHTML = result[10];//Total strikes in NSStrikes
        document.getElementById('dt').innerHTML = result[11];//Display time
        document.getElementById('numicpd').innerHTML = result[13];//Number of IC+ strikes
        document.getElementById('numicnd').innerHTML = result[12];//Number of IC- strikes
        document.getElementById('numcgpd').innerHTML = result[14];//Number of CG+ strikes
        document.getElementById('numcgnd').innerHTML = result[15];//Number of CG- strikes
        document.getElementById('tu').innerHTML = Date();//Number of CG- strikes
        document.getElementById('sec2up').innerHTML = Sec2Update;//Number of CG- strikes
        var dt = result[11] / 4;
        document.getElementById('q1t').innerHTML = [0, dt].split('-');//Set time frame headers
        document.getElementById('q2t').innerHTML = [dt, 2*dt].split('-');
        document.getElementById('q3t').innerHTML = [2*dt, 3*dt].split('-');
        document.getElementById('q4t').innerHTML = [3*dt, dt].split('-');
    }

    //Onload event caller. Does not intefere with OnLoad event in Body tag.
    //Put this is after all functions to be called
    function addLoadEvent(func) {
        $(window).on('load', func);
    }

    initialize();
    FADING_SCROLLER.changecontent();
});
</script>

<script type="text/javascript">
/***********************************************
* Fading Scroller- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************
* Wrapped as module by Beetroot-Beetroot
* Converted to use jQuery calls by Beetroot-Beetroot
* Note: The "proper" approach would be to use the 'color' jQuery plugin
***********************************************/
var FADING_SCROLLER = (function($) {//Module patttern
    var delay = 5000; //set delay between message change (in miliseconds)
    var maxsteps = 10; //number of steps to take to change from start color to endcolor
    var stepdelay = 200; //time in miliseconds of a single step
    //**Note: maxsteps*stepdelay will be total time in miliseconds of fading effect
    var startcolor = [201,201,201]; //start color (red, green, blue)
    var endcolor = [0,0,0]; //end color (red, green, blue)
    var fadelinks = 1;  //should links inside scroller content also fade like text? 0 for no, 1 for yes.

    // *** No need to edit below this line ***
    var faderdelay = 0;
    var index = 0;

    function changecontent() {
        var $fscroller = $("#fscroller").css('color', "rgb(" + startcolor.join(', ') + ")");
        var $content = $fscroller.find(".NWSinfo div").hide().eq(index).show().end();
        if(fadelinks) linkcolorchange(1);
        colorfade(1, 15);
        index = (index + 1) % $content.length;
    }

    function linkcolorchange(step) {
        $("#fscroller a").each(function() {
            $(this).css('color', getstepcolor(step));
        });
    }

    // Rafael Raposo edited function
    var fadecounter;
    function colorfade(step) {
        if(step<=maxsteps) {    
            $("#fscroller").css('color', getstepcolor(step));
            if (fadelinks)
                linkcolorchange(step);
            step++;
            fadecounter = setTimeout(function() {
                colorfade(step);
            }, stepdelay);
        } else {
            clearTimeout(fadecounter);
            $("#fscroller").css('color', "rgb(" + endcolor.join(', ') + ")");
            setTimeout(changecontent, delay);
        }
    }
    //Rafael Raposo's new function
    function getstepcolor(step) {
      var diff, newcolor = [];
      for(var i=0; i<3; i++) {
        diff = startcolor[i] - endcolor[i];
        if(diff > 0) {
           newcolor[i] = startcolor[i] - (Math.round((diff/maxsteps)) * step);
        } else {
           newcolor[i] = startcolor[i] + (Math.round((Math.abs(diff)/maxsteps)) * step);
        }
      }
      return "rgb(" + newcolor.join(', ') + ")";
    }

    // *** Expose public methods here ***
    return {
        changecontent: changecontent
    };
})(jQuery);
</script>

我只更改了 javascript,没有更改 CSS 或 HTML。包括了一些 cmets,但考虑到更改的范围还不够。

您将看到我将主脚本包装在 $(function(){...}) 结构中,并将 Fading Scroller 脚本包装为模块。这样做是为了防止污染全局命名空间和脚本之间污染的可能性。我将map 留在了全局命名空间中,以防在任何其他脚本中需要它。

我还对 ajaxWDwx.js 的本地副本进行了一些更改,但我认为其中任何一个都不相关。

【讨论】:

  • @Beetroo-Beetroot 谢谢!我知道这需要一些时间,而且您不必经历所有这些麻烦。戒指看起来很棒。让我玩这个,看看我是否可以将它与我迄今为止的工作相结合。当您查看页面时,您查看了原始来源。这是它的布局方式。 ExAMPLE 这就是为什么我说 NSGMAP.js 是该脚本的严格地图代码,因为我将它与脚本标签一起包含在头部中。使事物更清洁,更易于维护。
  • 德州人,一旦开始,我就下定决心要取得成果。是的,您必须根据需要更新所有原始文件。最好将我的代码视为一套可供您借鉴的想法。
  • @Beetroo-Beetroot 哈!是的,我知道一旦你开始,这是一个挑战。 Gmaps 对我来说是一个陡峭的学习曲线,所以我理解。非常感谢你,这将是一个巨大的帮助,给我一些可以玩的东西和一些指导。我会让你知道它是如何工作的。我现在正在玩它。
猜你喜欢
  • 2011-04-26
  • 2012-06-07
  • 2011-02-19
  • 1970-01-01
  • 2014-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
相关资源
最近更新 更多