Расстояние между 2 точками - PullRequest
0 голосов
/ 19 сентября 2019

Я хочу получить расстояние между двумя точками, используя библиотеку 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>

Спасибо заранее ...

1 Ответ

2 голосов
/ 19 сентября 2019

В приведенном выше коде вы присваиваете значения переменным задолго до нажатия кнопки «Отправить».Вместо этого вы должны переместить эти назначения в функцию 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;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...