問題描述
誰能幫忙.我只需要一個簡單的腳本.我有一個表格張貼到另一個頁面.兩個表單域是:
Can anyone please help. I just need a simple script. I have a form posted to another page. two formfields are:
fromaddress 和 toaddress
fromaddress and toaddress
我唯一需要的是一個腳本,它可以顯示以公里為單位的距離以及使用谷歌地圖所需的時間.我找到了幾十個腳本,但我無法讓它工作.地圖已經有了這個代碼,看起來很完美.
The only thing I need is a script that shows me the distance in km and the time it takes using google maps. I have found dozens of scripts but I cannot get it working. The map is already there with this code which seems to work perfect.
<script type="text/javascript" src="http://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 值中,例如:
But how do i display the distance and the time. Best option is to get it in a php value like:
$distance = some-code;
$time = some-code-too;
非常感謝您的幫助.
推薦答案
您需要為此使用不同的 API.首先,不要使用 JS 而是使用 PHP,這是應該對你有用的代碼片段;)
You need to use different API for that. First of all, don't use JS but PHP, here's the code snippet that should work for you ;)
$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
這篇關于使用谷歌地圖、PHP 和 MySQL 從 A 點到 B 點的距離的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!