我正在使用Google Distance Matrix API来计算从一个点到另一个点的行驶距离+时间。
我想将if..elseif..else语句添加到距离搜索的结果中,根据距离的大小(例如<或> 10 km)来改变答案,但我是JS的新手,可以'似乎要弄清楚将语句粘贴到我的代码中的位置。有小费吗?
这是我的代码:
$(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.METRIC,
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("We can't seem to find "
+ origin + ". Are you sure you entered a valid postcode and place?");
} else {
var distance = response.rows[0].elements[0].distance;
var duration = response.rows[0].elements[0].duration;
var distance_value = distance.value;
var distance_text = distance.text;
var duration_value = duration.value;
var duration_text = duration.text;
var kilometer = distance_text.substring(0, distance_text.length - 3);
$('#result').html("It is " + kilometer + " kilometer from " + origin + " to " + destination + " and it takes " + duration_text + " to drive.");
}
}
}
$('#distance_form').submit(function(e){
event.preventDefault();
var origin = $('#origin').val();
var destination = $('#destination').val();
var distance_text = calculateDistance(origin, destination);
});
});
一个选项是在callback
函数中使用条件逻辑,如下所示:
function callback(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
$('#result').html(err);
return;
}
if (response.rows[0].elements[0].status !== "OK") {
$('#result').html("We can't seem to find " + origin + ". Are you sure you entered a valid postcode and place?");
return;
}
var origin = response.originAddresses[0];
var destination = response.destinationAddresses[0];
var distance = response.rows[0].elements[0].distance;
var duration = response.rows[0].elements[0].duration;
var distance_value = distance.value;
var distance_text = distance.text;
var duration_value = duration.value;
var duration_text = duration.text;
var kilometer = distance_text.substring(0, distance_text.length - 3);
if (distance_value > 10000) {
$('#result').html('Distance is greater than 10km');
} else {
$('#result').html('Distance is less than 10km');
}
}
响应验证在函数的开头完成,如果请求没有返回所需的状态,则提前return
并停止执行该函数。一旦这些验证语句不在考虑范围内,您就可以从响应中提取所有必要的数据,然后根据您提取的任何值执行条件语句。
在我的例子中,这是看起来像:
if (distance_value > 10000) {
$('#result').html('Distance is greater than 10km');
} else {
$('#result').html('Distance is less than 10km');
}
我检查距离值是否大于10000米(10公里)并根据它显示不同的结果。
Here is a JSBin有一个工作的例子。