0

I am using the selectedIndex of a form to assign values to variables

function getIndex() {
var departureAirportIndex = document.getElementById("mySelect").selectedIndex;        

if (departureAirportIndex == 1) {
var lat2 = 13.7563309;
var lon2 = 100.5017651;
}
if (departureAirportIndex == 2){
  var lat2 = 41.977226;
  var lon2 = -87.836723;
}
if (departureAirportIndex == 3){
  var lat2 = -37.663712;
  var lon2 = 144.844788;
}

After assigning the values I would like to use the values in a function which calculates the distance.

function getDistance(lat1, lon1, lat2, lon2, unit) {
  var lat1 = 40.730610;
  var lon1 = -73.935242;
  var unit = "K";
                var radlat1 = Math.PI * lat1/180
                var radlat2 = Math.PI * lat2/180
                var theta = lon1-lon2
                var radtheta = Math.PI * theta/180
                var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
                dist = Math.acos(dist)
                dist = dist * 180/Math.PI
                dist = dist * 60 * 1.1515
                if (unit=="K") { dist = dist * 1.609344 }
                if (unit=="N") { dist = dist * 0.8684 }
                return dist.toFixed(2)

}

How can I use the lat2 and lon2 variables in the second function? After trying several options and reading about scoping I can't get it to work.

2
  • You have to declare them outside the first function, as globals or to pass them as parameters of the second function. Commented Mar 6, 2018 at 20:08
  • Thought about this, but almost everybody is telling me not to declare variables in the global scope Commented Mar 7, 2018 at 19:50

1 Answer 1

3

You can return an object with the coordinates:

function getIndex() {
    var coordinates = {}
    var departureAirportIndex = document.getElementById("mySelect").selectedIndex;        

    if (departureAirportIndex == 1) {
        coordinates.lat = 13.7563309;
        coordinates.lon = 100.5017651;
    }
    if (departureAirportIndex == 2){
        coordinates.lat = 41.977226;
        coordinates.lon = -87.836723;
    }
    if (departureAirportIndex == 3){
        coordinates.lat = -37.663712;
        coordinates.lon = 144.844788;
    }

    return coordinates;
}

function getDistance(lat1, lon1, lat2, lon2, unit) {...}

var coordinates = getIndex();
getDistance(lat1, lon1, coordinates.lat, coordinates.lon, unit);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.