我曾经在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>