我想使用Map V3库获取两点之间的距离, 我想从用户那里获取经度和纬度 这可能是什么问题?
我是JS的新手
<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>
感谢进阶...
答案 0 :(得分:2)
在上面的代码中,您正在为变量分配值,恰好在单击提交按钮之前。 相反,您应该将这些分配移到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;