传递值后停止运行函数

时间:2013-11-13 02:13:00

标签: javascript

我正在尝试阻止displayDistance函数运行,直到我单击按钮。它继续运行该函数,我假设因为值被传递给它所以它会自动调用它我猜?我需要它在窗口加载时显示当前的纬度/经度,然后在按钮点击后显示到每个位置的距离。现在它在窗口加载

上显示所有内容
    window.addEventListener("load", setupEventHandlers, false);
    window.addEventListener("load", displayLocation, false);

    function setupEventHandlers() {

        console.log("Inside setupEventHandlers function that is fired on the window load event");


        var displayButtonReference = document.getElementById("butCalculate");
        displayButtonReference.addEventListener("click", displayDistance, false);
    }


    //-------------------------------------------------------------------------------
    // Name:            displayLocation()
    // Description:     
    //-------------------------------------------------------------------------------
    function displayLocation() {

        console.log("displayLocation function called!");

        //Call getCurrentPosition() method to retrieve current position data
        //This is an asynchronous call. 
        //When completed it calls the cb_GetCurrentPosition_Success callback function
        //navigator.geolocation.getCurrentPosition(cb_GetCurrentPosition_Success);
        navigator.geolocation.getCurrentPosition(cb_GetCurrentPosition_Success,
                                          cb_GetCurrentPosition_Error,
                                          {
                                              enableHighAccuracy: true,
                                              maximumAge: 5000
                                          }
                                         );

    }

    //-------------------------------------------------------------------------------
    // Name:            cb_GetCurrentPosition_Success
    // Description:     Callback function if GeoLocation info retrieved successfully
    //-------------------------------------------------------------------------------
    function cb_GetCurrentPosition_Success(positionObject) {

        console.log("cb_GetCurrentPosition_Success callback function called!");

        //Show returned positionObject in Inspect Element Console
        console.dir(positionObject);

        //1. Declare variables 
        var accuracy,
            distanceInKilometers,
            distanceInFeet,
            distanceInMiles,
            displayString,
            currentLat,
            currentLong;

        //Extract geolocation data from returned object


        currentLat = positionObject.coords.latitude;
        currentLong = positionObject.coords.longitude;


        console.log("distanceInFeet = " + distanceInFeet);

        distanceInFeet = calculateDistanceInFeet(currentLat, currentLong)



        //Display retrieved Geolocation data
        document.getElementById("divLat").innerHTML = currentLat;
        document.getElementById("divLon").innerHTML = currentLong;

    }

    //---------------------------------------------------------------------------------------
    // Name:            cb_GetCurrentPosition_Error
    // Description:     Callback function if there is a problem retrieving GeoLocation info 
    //---------------------------------------------------------------------------------------
    function cb_GetCurrentPosition_Error(err) {

        var errorMessage;

        if (err.code == 1) {
            errorMessage = "You chose not to share your location info.";
        }
        else if (err.code == 2) {
            errorMessage = "Location information currently unavailable!";
        }
        else if (err.code == 3) {
            errorMessage = "Timed out waiting to receive location information!";
        }
        else {
            errorMessage = "Unknown error occured";
        }
    }

    // ---------------------------------------------------------------------------------------
    // name: calculateDistanceInFeet
    // source: http://www.codecodex.com/wiki/Calculate_distance_between_two_points_on_a_globe
    // ---------------------------------------------------------------------------------------
    function calculateDistanceInFeet(parcurrentLat, parcurrentLon) {

        console.log("calculateDistanceInFeet function called!");
        console.log("parcurrentLat = " + parcurrentLat);
        console.log("parcurrentLon = " + parcurrentLon);








        var distanceInKilometersToRamsey,
            distanceInKilometersToPicnic,
            distanceInFeetToRamsey,
            distanceInFeetToPicnic,
            Lat1 = 35.303209,       //Ramsey Coordinates
            Lon1 = -83.182745,
            Lat2 = 35.314455,       //Picnic Shelter Coordinates
            Lon2 = -83.188011;


        //Distance to Ramsey
        //Code retrieved from source shown above - don't modify
        //-------------------------------------------------------
        var R1 = 6371; // km
        var dLat1 = (Lat1 - parcurrentLat) * Math.PI / 180;
        var dLon1 = (Lon1 - parcurrentLon) * Math.PI / 180;
        var a1 = Math.sin(dLat1 / 2) * Math.sin(dLat1 / 2) +
        Math.cos(parcurrentLat * Math.PI / 180) * Math.cos(Lat1 * Math.PI / 180) *
        Math.sin(dLon1 / 2) * Math.sin(dLon1 / 2);
        var c1 = 2 * Math.asin(Math.sqrt(a1));
        distanceInKilometersToRamsey = R1 * c1;
        //---------------------------------------------------------
        //end of code to not modify

        //Distance to Picnic
        //Code retrieved from source shown above - don't modify
        //-------------------------------------------------------
        var R2 = 6371; // km
        var dLat2 = (Lat2 - parcurrentLat) * Math.PI / 180;
        var dLon2 = (Lon2 - parcurrentLon) * Math.PI / 180;
        var a2 = Math.sin(dLat2 / 2) * Math.sin(dLat2 / 2) +
        Math.cos(parcurrentLat * Math.PI / 180) * Math.cos(Lat2 * Math.PI / 180) *
        Math.sin(dLon2 / 2) * Math.sin(dLon2 / 2);
        var c2 = 2 * Math.asin(Math.sqrt(a2));
        distanceInKilometersToPicnic = R2 * c2;
        //---------------------------------------------------------
        //end of code to not modify




        //3. Do calculations
        distanceInFeetToRamsey = distanceInKilometersToRamsey * 1000 * 3.2808;
        distanceInFeetToPicnic = distanceInKilometersToPicnic * 1000 * 3.2808;

        var passedDistance = displayDistance(distanceInFeetToRamsey, distanceInFeetToPicnic);

        console.log("distanceInFeetToRamsey = " + distanceInFeetToRamsey);
        console.log("distanceInFeetToPicnic = " + distanceInFeetToPicnic);
    }

    function displayDistance(parRamsey, parPicnic) {

        if (parRamsey >= 5280) {
            var distanceInMilesToRamsey = parRamsey / 5280;

            document.getElementById("divDistance1").innerHTML = distanceInMilesToRamsey.toFixed(2) + "miles";


        }
        else {
            document.getElementById("divDistance1").innerHTML = parPicnic.toFixed(2) + "feet";
        }

        if (parPicnic >= 5280) {
            var distanceInMilesToPicnic = distanceInFeetToPicnic / 5280;

            document.getElementById("divDistance2").innerHTML = distanceInMilesToPicnic.toFixed(2) + "miles";


        }
        else {
            document.getElementById("divDistance2").innerHTML = parPicnic.toFixed(2) + "feet";
        }
    }

1 个答案:

答案 0 :(得分:0)

displayDistance由load事件间接调用:

加载调用displayLocation:

window.addEventListener("load", displayLocation, false);

displayLocation调用cb_GetCurrentPosition_Success(通过回调):

navigator.geolocation.getCurrentPosition(cb_GetCurrentPosition_Success,
                                      cb_GetCurrentPosition_Error,
                                      {
                                          enableHighAccuracy: true,
                                          maximumAge: 5000
                                      }
                                     );

cb_GetCurrentPosition_Success调用calculateDistanceInFeet:

distanceInFeet = calculateDistanceInFeet(currentLat, currentLong)

calculateDistanceInFeet调用displayDistance:

var passedDistance = displayDistance(distanceInFeetToRamsey, distanceInFeetToPicnic);