所以首先我得到了这两个 p 标签
<p id="pos"></p>
<p id="dist"></p>
我将我的位置放在“pos”中,将我与纽约之间的距离放在“dist”中。我得到了这两个按钮来触发 JS 功能:
<button onclick="getLocation()">Get position</button>
<button onclick="calcDistance()">Calculate distance to NY</button>
这是所有脚本:
var x=document.getElementById("pos");
var d=document.getElementById("dist");
var startPos;
function getLocation(){
navigator.geolocation.getCurrentPosition(function(position) {
startPos = position;
x.innerHTML= "<h3>Your position</h3>" +
"Latitude: " + startPos.coords.latitude +
"<br>Longitude: " + startPos.coords.longitude;
});
};
function calcDistance(){
var distt = calculateDistance(startPos.coords.latitude, startPos.coords.longitude, 40.28371627, -73.994901);
d.innerHTML = distt.toFixed(1);
};
function calculateDistance(lat1,lon1,lat2,lon2) {
var R = 6371;
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}
我的 calcDistance 按钮不起作用,我不知道问题出在哪里。我试图只在 calculateDistance() 中输入数字,但它仍然不起作用。怎么来的?