简体   繁体   English

Google Maps V3中的Elabel未定义错误

[英]Elabel undefined error in Google Maps V3

I have been porting a script I have from V2 to V3 and I have hit a snag. 我一直在将自己的脚本从V2移植到V3,但遇到了麻烦。 I am getting an Elabel undefined error but I am not sure why I am getting this. 我收到一个Elabel未定义错误,但是我不确定为什么会收到这个错误。 I have updated the Elabel.js to V3 which is here... ELABLE.JS I am not sure if this is not a good copy of ELabel.js or what. 我已经将Elabel.js更新到了这里的V3 ... ELABLE.JS我不确定这不是ELabel.js的好副本还是什么。 I have tried a couple of different other copies with no success. 我尝试了其他两个不同的副本,但均未成功。

Here is the working example of it using V2 这是使用V2的工作示例

V2 EXAMPLE V2示例

Here is the V3 example. 这是V3示例。 As you can see in V3 the range rings are not drawn and the map doesn't update and the table doesn't populate. 正如您在V3中看到的那样,没有绘制范围环,地图也没有更新,表格也没有填充。 I know it is related to the ELabel.js but I am not sure why and I can't find the issue to why I am getting the undefined error. 我知道它与ELabel.js有关,但是我不确定为什么,并且找不到为什么我得到未定义错误的问题。 I know it is related to this because when I remove the script include for the ELable.js I have the same problems on V2 that I am seeing on V3. 我知道这与此有关,因为当我删除ELable.js的脚本包含时,我在V2上遇到的问题与在V3上遇到的问题相同。

V3 EXAMPLE V3示例

Since the code is too long to post here, the link to the relevant code is in the link below. 由于代码太长,无法在此处发布,因此下面的链接中包含指向相关代码的链接。 Line 135 is where the ELabel error is coming from. 135行是ELabel错误的来源。 This worked great in V2 but not V3. 在V2中效果很好,但在V3中效果不佳。 So I don't know if I am overlooking something that has changed in V2 to V3. 因此,我不知道我是否忽略了从V2更改为V3的内容。

EXAMPLE CODE 示例代码

So can anyone offer any insight on why I am getting this undefined error and shed some light on what I may be doing wrong and overlooking? 那么,谁能提供我为什么会得到这个不确定的错误的任何见解,并阐明我可能做错了什么而忽略了什么?

-Thanks -谢谢

Texan, here's te script from my local file, which is working as far as getting the circles and labels to show. 德克萨斯州,这是我本地文件中的te脚本,目前为止可以显示圆和标签。 All ajax aspects are untested. 所有ajax方面都未经测试。

The script below should be pasted into the document head, immediately before the closing </head> tag. 下面的脚本应该紧贴在</head>标记之前粘贴到文档头中。

This replaces various other inline scripts. 这将替换其他各种内联脚本。 The only remaining scripts in the document body should be the google analytics (2 scripts) and StatCounter (1 script). 文档正文中唯一剩余的脚本应该是Google Analytics(分析)(2个脚本)和StatCounter(1个脚本)。 No external scripts should be removed. 不应删除任何外部脚本。

<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>

I only changed the javascript, not the CSS or HTML. 我只更改了JavaScript,而不更改了CSS或HTML。 Some comments are included but not really enough considering the scope of the changes. 考虑到更改的范围,其中包含一些注释,但还不够。

You will see I wrapped the main script in a $(function(){...}) structure and the Fading Scroller script as a Module. 您将看到我将主脚本包裹在$(function(){...})结构中,而Fading Scroller脚本作为模块包裹了起来。 This was done to prevent polluting the global namespace and the possibility of contamination between scripts. 这样做是为了防止污染全局名称空间以及防止脚本之间被污染的可能性。 I left map in the global namespace in case it's needed in any of the other scripts. 我将map留在全局名称空间中,以防其他任何脚本需要它。

I also made some changes to a local copy of ajaxWDwx.js but I don't think any of them are relevant. 我还对ajaxWDwx.js的本地副本进行了一些更改,但我认为它们都不相关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM