【发布时间】:2023-03-27 18:07:01
【问题描述】:
我发现了一段非常聪明的代码,用于在给出两个参数时使用谷歌地图计算驾驶时间和距离。我正在使用它来使用存储在数据库中的数据创建里程报告。
我的问题是我需要在同一个循环中使用此函数两次,但是当我这样做时它会关闭循环并且根本不显示任何信息。
请看下面的函数
function get_driving_information($start, $finish, $raw = false)
{
if(strcmp($start, $finish) == 0)
{
$time = 0;
if($raw)
{
$time .= ' seconds';
}
return array('distance' => 0, 'time' => $time);
}
$start = urlencode($start);
$finish = urlencode($finish);
$distance = 'unknown';
$time = 'unknown';
$url = 'http://maps.googleapis.com/maps/api/directions/xml?origin='.$start.'&destination='.$finish.'&sensor=false';
if($data = file_get_contents($url))
{
$xml = new SimpleXMLElement($data);
if(isset($xml->route->leg->duration->value) AND (int)$xml->route->leg->duration->value > 0)
{
if($raw)
{
$distance = (string)$xml->route->leg->distance->text;
$time = (string)$xml->route->leg->duration->text;
}
else
{
$distance = (int)$xml->route->leg->distance->value / 1000 / 1.609344;
$time = (int)$xml->route->leg->duration->value/ 60;
}
}
else
{
throw new Exception('Could not find that route');
}
return array('distance' => $distance, 'time' => $time);
}
else
{
throw new Exception('Could not resolve URL');
}
}
try
{
$info = get_driving_information('fy1 4bj', 'ls1 5ns');
echo $info['distance'].' miles ' . 'That\'s about ' .$info['time'].' minutes drive from you';
}
catch(Exception $e)
{
echo 'Caught exception: '.$e->getMessage()."\n";
}
这是只有在我注释掉第二个函数时才会起作用的代码。
$sql="SELECT * FROM mileage";
$result=mysqli_query($con,$sql);
?><table style="width:100%" border=1px><?php
$i=0;
while($row = mysqli_fetch_array($result))
{
$i=$i+1;
if (isset($row['Start'])){$start = $row['Start'];}
if (isset($row['Site'])){$finish2 = $row['Site'];}
if (isset($lastsite)) {$finish=$lastsite;}
if (isset($start) && isset($finish)){
$info = get_driving_information($start, $finish);}
if (isset($start) && isset($finish2)){
//$info2 = get_driving_information($start, $finish2);
}
if ($i>1){
?>
<td><?php echo $start; ?></td> <td><a target="_blank" href="https://www.google.co.uk/maps/dir/<?php echo $start . "/" . $lastsite ?>">
Distance: <?php $drive=$info['distance'];
echo $drive; ?></td></tr> <?php
}?>
<tr><td> <?php echo $start ?></td><td><?php echo $finish2 ?>
</td><td><a target="_blank" href="https://www.google.co.uk/maps/dir/<?php echo $start . "/" . $finish2 ?>">
Distance:
<?php
$drive2=$info2['distance'];
echo $drive2;
?> </td></tr><tr><td> <?php echo $finish2 ?></td><?php
$lastsite=$finish2;
}?>
</table>
【问题讨论】:
-
任何错误抛出?也许增加错误报告可能表明一些事情。
-
nope no error_reporting(E_ALL);
-
您可能将一个空白字符串作为目标传递给 google。如果 $row['Site'] 是一个空白字符串,它仍然会将 isset 评估为 TRUE(因为它没有设置为 null)。我会尝试检查或回显您的数据库输出以进行验证。您可能想改用 !empty() 。否则,您可能会将其他类型的无效输入传递给 google API,在这种情况下,在您的代码中调用无效对象资源会导致致命错误。
-
感谢 Daielml01,问题是其中一个邮政编码不是有效地址。
标签: php mysql function while-loop