函数未被调用第一次运行脚本

时间:2013-06-20 16:07:09

标签: javascript variables undefined openlayers scope

我是JavaScript的新手,我有初学者掌握的概念我有一个函数,从kml获取标签并在屏幕上显示(此功能的某些聚类部分由S / O上的某个人提供) 。它适用于除第一个之外的所有加载的kmls。

我确信问题与变量及其范围有关,但对于我的生活,我无法看到我在哪里或如何得到错误,我对代码的更正将是一个很大的帮助,但纠正我的理解(或缺乏)同样有帮助。

非常感谢adavance

这是代码

EDIT 1)我已经多次更改了函数getlabel,只有在下面显示的第一个ajax调用之外加载的kml上才能看到更改。我不知道为什么会发生这种情况。这可能是一个上下文问题,但这超出了我对该主题的理解

var tripid=1;
var myStyles;
var cfarmerid;
var navigate=true;
var edit=false;
var vectors;
var polyControl;
var bound=false;
var mycluster;
var label=" ";



$(document).ready(function(){
    $.ajax({
        type: "POST",url: "temp.php",dataType: "json",
        error: function(e){
            alert('Error: '+e);
        },  

        success: function (data) {
        if(data[0]==="not"){
               window.location = "http://www.g4ema.com/index.html";
            }
            maxlat=data[0];
        maxlon=data[1];
            minlat=data[2];
        minlon=data[3];
        tripid=parseInt(data[4]);



    var bbox=new OpenLayers.Bounds();
        bbox.extend(new OpenLayers.LonLat(minlon,minlat));
        bbox.extend(new OpenLayers.LonLat(maxlat,maxlon));
        bbox.toBBOX();

        map = new OpenLayers.Map("map");
    //var layer=  new OpenLayers.Layer.OSM();


         mycluster = new OpenLayers.Strategy.Cluster(
         {
            threshold: 2, // single clusters are shown as features
            shouldCluster: function(cluster, feature) 
            {
            if (feature.geometry.CLASS_NAME === "OpenLayers.Geometry.Point" &&
                cluster.cluster[0].geometry.CLASS_NAME === "OpenLayers.Geometry.Point") {
                    return OpenLayers.Strategy.Cluster.prototype.shouldCluster.apply(this, arguments);
                } else {
                    return false;
                }
            }
        });


    var layer = new OpenLayers.Layer.Google(
            "Google Hybrid",
            {type: google.maps.MapTypeId.HYBRID, numZoomLevels: 20});
            layer.wrapDateLine=false;
        map.addLayer(layer);

     myStyles = new OpenLayers.StyleMap({ 
         "default": new OpenLayers.Style({ 
            strokeColor: "#00ffff", 
            strokeWidth:5, 
            strokeOpacity:1, 
            fillColor:"#003399", 
            fillOpacity: 1,
            labelYOffset: 15,
            pointRadius: 4,
            label:"${getLabel}", 
            fontColor:"#ff0000"
        }, {
            context: {
                getLabel: function (f) {
                    label=" ";
                    if (f.cluster) { // is a cluster
                        if (f.cluster[0].attributes.label!==" ") {
                            label= " " + f.attributes.count  + " " +
                                f.cluster[0].attributes.label;
                        } else {
                            label= " " ;//+ f.attributes.count + "init";
                        }
                    } else { // is not cluster
                        if (f.attributes.label!==" ") {
                            label= " " + f.attributes.label;

                        }else{
                            label=" ";
                        }
                    }
                    if(!label){label=" ";}
                    return label;
                }

            }
    })
});




      kmlLayer = new OpenLayers.Layer.Vector("Trip", {
                styleMap: myStyles,
                    projection: map.displayProjection,      
                    strategies: [new OpenLayers.Strategy.Fixed(),mycluster],
                    protocol: new OpenLayers.Protocol.HTTP({
                        params:{ tripid:tripid},    
                    url: "kml2.php",
                    readWithPOST:true,
                    //{userid:userid,tripid:tripid},
                    format: new OpenLayers.Format.KML({
                                extractStyles: true,
                                extractAttributes: true             
                            })          
                        })          
                    });

            map.addLayer(kmlLayer);

             var clat=(parseFloat(minlat)+parseFloat(maxlat))/2;
                var clon=(parseFloat(minlon)+parseFloat(maxlon))/2;
                var lonlat = new OpenLayers.LonLat(clon,clat).transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
                map.setCenter(lonlat);
                map.zoomTo(15);

2 个答案:

答案 0 :(得分:0)

首先,我没有看到在您共享的代码的上下文中使用全局范围声明label变量的优势。因为你从getLabel函数返回一个标签,所以我认为你应该在getLabel函数的顶部声明var label;并从函数中返回该局部变量的值。

其次,我可以看到从getLabel返回“undefined”的唯一方法是f.attributes.label未定义。我会尝试一个代码块,例如:

} else { // is not cluster
   if (f.attributes.label != null && typeof(f.attributes.label != "undefined") {
   // if (f.attributes.label) {   // alternate simpler if statement
      label= " " + f.attributes.label;
   } else {
      label = " ";
   }
}

答案 1 :(得分:0)

对于任何看到同样问题的人,

上面的代码是完美无缺的,之所以无法正常工作是因为我之后在$ document.ready()中调用了另一个函数,而这正在改进mycluster变量。对于那些你看过这个并且看不到问题的人,我感到非常抱歉。

但上面的代码将起作用FINE

相关问题