应用程序的整体要点是计算并显示由html输入定义的两个地址之间的距离。我遇到的问题是当点击Calculate
按钮时,它会打开一个带有奇怪URL的新标签, “https://n-u3xjzi7wklp272w6mwu2e3jc3umixhe6rym5h7i-0lu-script.googleusercontent.com/userCodeAppPanel?origin=&destination=”我猜它实际上应该是距离矩阵请求网址,因为奇怪的网址包含origin=&destination=
,但我肯定错了。
这是我的当前代码:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h2>Distance Between two Addresses</h2>
<form id="distance_form">
<label>Origin: </label>
<input id="origin" type="text" name="origin"/>
<br/>
<label>Destination: </label>
<input id="destination" type="text" name="destination"/>
<br/>
<input type="submit" value="Calculate"/>
</form>
<div id="result">
</div>
</body>
<script>
$(function () {
function calculateDistance(origin, destination) {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != 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("Better get on a plane. There are no roads between "
+ origin + " and " + destination);
} else {
var distance = response.rows[0].elements[0].distance;
var distance_value = distance.value;
var distance_text = distance.text;
var miles = distance_text.substring(0, distance_text.length - 3);
$('#result').html("It is " + miles + " miles from " + origin + " to " + destination);
}
}
}
$('#distance_form').submit(function(){
var origin = $('#origin').val();
var destination = $('#destination').val();
var distance_text = calculateDistance(origin, destination);
});
});
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAxmrFQipNODQwlv57BHQxati2jR8_xWdA" async defer></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</html>
答案 0 :(得分:0)
表单提交的默认行为是打开一个新页面,这是导致Apps Script Web应用程序中出现奇怪URL的原因。您可以通过在HTML中添加以下内容来关闭它:
<script>
function preventFormSubmit() {
var forms = document.querySelectorAll('form')
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault()
})
}
} // preventFormSubmit()
window.addEventListener('load', preventFormSubmit)
</script>