gpt4 book ai didi

javascript - 2 点之间的距离

转载 作者:行者123 更新时间:2023-12-01 00:37:19 26 4
gpt4 key购买 nike

我想使用Map V3库获取两点之间的距离,我想从用户那里获取纬度和经度。

这里可能出了什么问题?

<div class="form">
<form action="LatLng" method="post" id="LatLng" class="LatLng">
<h2>Source</h2>
<input type="text" id="latitude" placeholder="Latitude" value="" class="txt">
<input type="text" id="longitude" placeholder="Longitude" value="" class="txt">
<h2>Destination</h2>
<input type="text" id="Dlatitude" placeholder="Latitude" value="" class="txt">
<input type="text" id="Dlongitude" placeholder="Longitude" value="" class="txt">
<input type="submit" value="submit" name="submit" class="txt2">

</form>
</div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry"></script>

<script>
var srcLatitude = document.getElementById('latitude').value;
var srcLongitude = document.getElementById('longitude').value;
var destLatitude = document.getElementById('Dlatitude').value;
var destLongitude = document.getElementById('Dlongitude').value;
document.querySelector('form.LatLng').addEventListener('submit', function (e){
var lat1 = parseFloat(srcLatitude);
var lon1 = parseFloat(srcLongitude);
var lat2 = parseFloat(destLatitude);
var lon2 = parseFloat(destLongitude);

var p1 = new google.maps.LatLng(lat1, lon1);
var p2 = new google.maps.LatLng(lat2, lon2);

alert(calcDistance(p1, p2));

//calculates distance between two points in km's
function calcDistance(p1, p2) {
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(6);
}
});
</script>

最佳答案

在上面的代码中,您在单击提交按钮之前为变量赋值。相反,您应该将这些分配移至 EventListener 函数内。

var srcLatitude = document.getElementById('latitude').value;
var srcLongitude = document.getElementById('longitude').value;
var destLatitude = document.getElementById('Dlatitude').value;
var destLongitude = document.getElementById('Dlongitude').value;

关于javascript - 2 点之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58014934/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com