Нахождение расстояния в ASP.net Не найдено ни одной ошибки, но также не найден нужный результат - PullRequest
0 голосов
/ 21 декабря 2018

Я использовал этот код скрипта в ASP.net MVC View, в файл также включены справочные файлы jQuery и Google Maps.Он не показывает ни ошибок, ни предупреждений, ни требуемого результата в браузере.Это нормально?Что я должен делать?Мне нужно расстояние в километрах, а также заполнитель с указанием местоположения при наборе адреса.Несколько мест также могут быть обработаны.Любой API, который может сделать это.Спасибо за ваши драгоценные мнения.(* Я обнаружил, что это простой способ найти расстояние, но это разочаровало меня.)

HTML-код

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?libraries=places&language=en&key=AIzaSyDG1cZyGRlcAyUgpVpr5x5xadfKSTLFEjs"></script>

<form id="distance_form">
<div class="form-group">
    <label>Origin:</label>
    <input id="form_places" class="form-control" placeholder="Pick up location" />
    <input id="origin" type="hidden" name="origin" required />

</div>

<div class="form-group">
    <label>Destination:</label>
    <input id="to_places" class="form-control" placeholder="Pick up destination" />
    <input id="destination" type="hidden" name="destination" required />
</div>
<input type="submit" value="Calculate" class="btn btn-Primary" />
 </form>
 <div id="result"></div>

Код сценария

<script>
   (function () {
    google.maps.event.addDomListener(window, 'load', function () {
        var form_places = new google.maps.places.Autocomplete(document.getElementById('form_places'));
        var to_places = new google.maps.places.Autocomplete(document.getElementById('to_places'));

    google.maps.event.addListener(form_places, 'place_changed', function () {
        var form_place = form_place.getPlace();
        var form_address = form_place.formatted_address;
        $('origin').val(form_address);
    });
    google.maps.event.addListener(to_places, 'place_changed', function () {
        var to_place = to_place.getPlace();
        var to_address = to_place.formatted_address;
        $('destination').val(to_address);
    });
});

function CalculateDistance() {
    var origin = $('origin').val();
    var destination = $('destination').val();
    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix(
        {
            origin: ['origin'],
            destination: ['destination'],
            travelmode: google.maps.TravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.metric,
            avoidHighways: false,
            avoidTolls: false
        }, callback);
}
   //get destance result
function callback(response, status) {
    if (!google.maps.DistanceMatrixStatus.OK) {
        $('result').html(err);
    } else {
        var origin = response.originAddresses[0];
        var destination = response.destinationAddresses[0];
        if (response.rows[0].elements[0].status === "ZERO_RESULTS") {
            $('result').html('No roads between' + origin + 'and ' + destination)
        } else {
            var distance = response.rows[0].elements[0].distance;
            var duration = response.rows[0].elements.duration;
            console.log(response.rows[0].elements[0].distance);
            var distance_in_Kilo = distance.value / 1000;
            var duration_text = duration.text;
            var duration_value = duration.value;
            $('#in_kilo').text(distance_in_kilo.ToFixed(2));
            $('#duration_text').text(duration_text.ToFixed(2));
            $('#duration_value').text(duration_value.ToFixed(2));
            $('#form').text(origin);
            $('#to').text(destination);

        }
    }
}
//submit button
$('#distance_form').submit(function (e) {
    e.preventDefault();
    CalculateDistance();
    });
});
</script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...