任何人都可以帮忙。我只需要一个简单的脚本。我有一张表格张贴到另一页。两个表格是:
fromaddress和toaddress
我唯一需要的是一个脚本,它显示了以km为单位的距离以及使用谷歌地图所需的时间。我找到了几十个脚本,但我无法使用它。地图已经存在,这段代码看起来很完美。
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key=AIzaSyDdDwV6_l5n2bS3gM6NBCla3RFLtIFc_HE&sensor=false"></script><script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
var start = "<? echo $_POST[fromaddress]; ?>";
var end = "<? echo $_POST[toaddress]; ?>";
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
$(document).ready(function(){
initialize();
});
</script>
但是我如何显示距离和时间。最好的选择是使用php值来获取它:
$distance = some-code;
$time = some-code-too;
非常感谢你的帮助。
答案 0 :(得分:7)
您需要使用不同的API。首先,不要使用JS而是PHP,这里的代码片段应该适合你;)
$from = "Więckowskiego 72, Łódź";
$to = "Gazowa 1, Łódź";
$from = urlencode($from);
$to = urlencode($to);
$data = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&sensor=false");
$data = json_decode($data);
$time = 0;
$distance = 0;
foreach($data->rows[0]->elements as $road) {
$time += $road->duration->value;
$distance += $road->distance->value;
}
echo "To: ".$data->destination_addresses[0];
echo "<br/>";
echo "From: ".$data->origin_addresses[0];
echo "<br/>";
echo "Time: ".$time." seconds";
echo "<br/>";
echo "Distance: ".$distance." meters";
输出:
To: Gazowa 1, 91-076 Łódź, Poland
From: Więckowskiego 72, Łódź, Poland
Time: 206 seconds
Distance: 1488 meters
答案 1 :(得分:1)
您可以通过累计所有腿来计算完整的路线持续时间和距离:
function computeTotals(result) {
var totalDist = 0;
var totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
totalDist = totalDist / 1000.
document.getElementById("total").innerHTML = "total distance="+totalDist.toFixed(2) + " km ("+(totalDist*0.621371).toFixed(2)+" miles), time="+totalTime+" seconds";
}
这样称呼:
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
computeTotals(response);
}
});