我正在使用表单的selectedIndex为变量赋值
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;
}
在分配值后,我想使用计算距离的函数中的值。
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)
}
如何在第二个函数中使用lat2和lon2变量?在尝试了几个选项并阅读范围界定后,我无法使其发挥作用。
答案 0 :(得分:3)
您可以使用坐标返回一个对象:
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);