简体   繁体   中英

function not being called first time script runs

I am new to JavaScript and I have beginners grip on the concepts I have a function that gets the label from a kml and displays it on screen (some of the clustering part of this function was supplied by someone on S/O). it works perfectly for all the kmls that are loaded except the First one.

I am sure that the problem is something to do with a variable and its scope, but for the life of me i cannot see where or how I am getting an error, I correction to the code would be a great help, but correction to my understanding (or lack there of) just as helpful.

many thanks in adavance

here is the code

EDIT 1) I have changes the function getlabel a number of times and the changes are only seen on kmls loaded outside of the first ajax call shown below. I don't for the life of em understand why this is happening. It may be a context issue, however this is beyond my understanding of the topic

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

First of all, I don't see the advantage of declaring the label variable with global scope in the context of the code you've shared. Since you're returning a label from the getLabel function then I think you should just declare var label; at the top of the getLabel function and return the value of that local variable from the function.

Second, the only way I can see that "undefined" would be returned from getLabel is if f.attributes.label is undefined. I would try a code block such as:

} 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 = " ";
   }
}

For anyone looking this with the same problem,

The above code is faultless, the reason this wasn't working is I was calling another function later in the $document.ready() and this was refining the mycluster variable. I am very sorry for those you have looked at this and couldn't see the problem.

but the above code will work FINE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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