本文介绍了我如何获得所有旅行模式的距离和持续时间,例如驾驶、交通、骑自行车、在我的页面中行走,并将其存储在 db 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只成功显示和存储了单一出行模式的数据,但现在我想存储所有出行模式的距离和持续时间等数据,这是代码,我需要执行哪些更改,提前致谢映射器.html

<头><title></title><style type="text/css">身体{字体系列:Arial;字体大小:10pt;}</风格><身体><script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script><script type="text/javascript">var 来源,目的地;var routeArr = [];var 方向显示;//整个地图渲染或显示.var globalResponse;var DirectionsService = new google.maps.DirectionsService();//用于利用 API 提供的方向服务google.maps.event.addDomListener(window, 'load', function () {//充当页面加载函数新 google.maps.places.SearchBox(document.getElementById('txtSource'));新的 google.maps.places.SearchBox(document.getElementById('txtDestination'));DirectionDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });});函数 GetRoute(){var kolkata = new google.maps.LatLng(22.7383075, 88.454424);//地图的中心var mapOptions = {//设置地图的视图变焦:7,中心:加尔各答};map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);//地图视图的变量方向显示.setMap(地图);//地图视图DirectionsDisplay.setPanel(document.getElementById('dvPanel'));//面板视图//------------------------------方向和路线----------------------------------------------source = document.getElementById("txtSource").value;destination = document.getElementById("txtDestination").value;var request =//变量请求{//路线服务来源:来源,目的地:目的地,provideRouteAlternatives: 真,旅行模式:google.maps.TravelMode.DRIVING};DirectionsService.route(request, function (response, status){//RouteService如果(状态 == google.maps.DirectionsStatus.OK){globalResponse = 响应;routeArr = [];for(i=0;i";}document.getElementById("dvDistance").innerHTML = s;DirectionsDisplay.setDirections(响应);}//这是 AJAX 请求var httpRequest;if (window.XMLHttpRequest) {//Mozilla、Safari、IE7+ ...httpRequest = new XMLHttpRequest();} else if (window.ActiveXObject) {//IE 6 及更早版本httpRequest = new ActiveXObject("Microsoft.XMLHTTP");}httpRequest.onreadystatechange = function() {//这里是用来处理响应的函数名if (httpRequest.readyState == 4 && httpRequest.status == 200) {//200 OK 响应代码.//4 是收到完整的响应警报(httpRequest.responseText);}};httpRequest.open("POST", "mapdb.php", true);//这里 true 表示异步调用服务器,即不重新加载页面httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");httpRequest.send("source=" + source + "&destination=" + destination + "&sel=" + sel + "&i=" + i + "&routes=" + JSON.stringify(routeArr)));});//-----------------------------距离和持续时间-------------------------------------var service = new google.maps.DistanceMatrixService();//API 提供的不同服务service.getDistanceMatrix({来源:[来源],目的地:[目的地],旅行模式:google.maps.TravelMode.DRIVING,单位系统:google.maps.UnitSystem.METRIC,避开高速公路:假,避免通行费:假},功能(响应,状态){if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {/*var distance = globalResponse.rows[0].elements[0].distance.text;//根据 API 提供的数据计算距离var duration = globalResponse.rows[0].elements[0].duration.text;//根据API提供的数据计算时长var distance = globalResponse.routes[0].legs[0].distance.text;var duration = globalResponse.routes[0].legs[0].duration.text;var dvDistance = document.getElementById("dvDistance");//此变量用于获取路线距离并将其显示在网页上.dvDistance.innerHTML = "";dvDistance.innerHTML += "距离:" + 距离 + "
";dvDistance.innerHTML += "Duration:" + duration;//+ " "+typeof response.routes.length;*/}别的 {alert("无法通过道路找到距离.");}});var sel = document.getElementById('modes').value;//用户更喜欢哪种模式}<table border="0" cellpadding="0" cellspacing="3"><tr><td colspan="2">来源:<input type="text" id="txtSource" style="width: 200px"/>&nbsp;目的地:<input type="text" id="txtDestination" style="width: 200px"/>&nbsp;出行方式:<select id="modes"><option value="驾驶" >驾驶</option><option value="cycling">骑行</option><option value="transit">Transit</option><option value="walking"selected>Walking</option></选择><br/><input type="button" value="Get Route" onclick="GetRoute()"/><小时/></td></tr><tr><td colspan="2"><div id="dvDistance">

</td></tr><tr><td><div id="dvMap" style="width: 800px; height: 500px">

</td><td><div id="dvPanel" style="width: 500px; height: 500px">

</td></tr><br>

 mapdb.php<?phpif(isset($_POST['source'], $_POST['destination'], $_POST['sel'], $_POST['i']) && count($_POST['routes'])){$routes_array = json_decode($_POST['routes'], true);//创建连接$conn = new mysqli("localhost", "root", "", "testdb");//检查连接如果 ($conn->connect_error){die("连接失败:" . $conn->connect_error);}$i = $_POST['i'];$sel = $_POST['sel'];$source = $_POST['source'];$destination = $_POST['目的地'];$query = "INSERT INTO trip(source, destination, mode, num_routes) VALUES('{$source}', '{$destination}', '{$sel}', '{$i}')";if($conn->query($query)){$trip_id = $conn->insert_id;foreach($routes_array 作为 $route){$distance = $route[0];$duration = $route[1];$query = "INSERT INTO route(trip_id, distance, duration) VALUES({$trip_id}, '{$distance}', '{$duration}')";//以公里为单位的距离和持续时间$conn->查询($查询);}echo "Sumeet!!!成功";}别的{echo "出错了!!!无法插入记录";}//关闭连接$conn->close();}?>
解决方案

在您的请求中将 MODE 更改为 Walking , Transit, Bicycling.首先使用浏览器上的 google 路线 API 端点检查输出.并非每对位置都提供步行和骑自行车的结果.

附加您的旅行模式的最后一部分:google.maps.TravelMode.在此处更改".在此处输入链接描述如果无法进行迭代(循环),则重复三次代码.

I only succeded in displaying and storing the data of a single travel mode but now i want to store the data like distance and duration from all travel modes,here is the code,what changes do i need to perform,thanks in advance mapper.html

<html>
<head>
    <title></title>
    <style type="text/css">
        body
        {
        font-family: Arial;
        font-size: 10pt;
        }
    </style>
</head>
<body>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
    <script type="text/javascript">
        var source, destination;
        var routeArr = [];
        var directionsDisplay;                                                      // The whole map rendering or displaying.
        var globalResponse;
        var directionsService = new google.maps.DirectionsService();                // For Availing the Direction Services provided by APIs

        google.maps.event.addDomListener(window, 'load', function () {              //  This acts as a pageload Function
            new google.maps.places.SearchBox(document.getElementById('txtSource'));
            new google.maps.places.SearchBox(document.getElementById('txtDestination'));
            directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
        });

        function GetRoute()
        {
            var kolkata = new google.maps.LatLng(22.7383075, 88.454424);  // Center of the Map
            var mapOptions = {                                           // Setting the View of the Map
                zoom: 7,
                center: kolkata
            };

            map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);   // Variable for map view

            directionsDisplay.setMap(map);                                              // Map view

            directionsDisplay.setPanel(document.getElementById('dvPanel'));             //Panel View


            //------------------------------DIRECTIONS AND ROUTE------------------------------------------------------

            source = document.getElementById("txtSource").value;
            destination = document.getElementById("txtDestination").value;

            var request =                        // variable request
            {                                   // DirectionsService
                origin: source,
                destination: destination,
                provideRouteAlternatives: true,
                travelMode: google.maps.TravelMode.DRIVING
            };

            directionsService.route(request, function (response, status){   // RouteService
                if (status == google.maps.DirectionsStatus.OK)
        {
                    globalResponse = response;
                    routeArr = [];

                    for(i=0;i<globalResponse.routes.length;i++)
        {

                        routeArr.push([globalResponse.routes[i].legs[0].distance.text, globalResponse.routes[i].legs[0].duration.text]);
                    }
                    var s = 'Possible routes are: <br />';
                    for(i = 0; i < routeArr.length; ++i)
        {

            routeArr[i][0] = routeArr[i][0].trim();
            routeArr[i][0] = routeArr[i][0].substring(0,routeArr[i][0].length-3)
            routeArr[i][1] = routeArr[i][1].split(' ');
            if(routeArr[i][1].length==2)
            {
                routeArr[i][1]=parseInt(routeArr[i][1][0]);
            }
            else
            {
                routeArr[i][1]=parseInt(routeArr[i][1][0])*60 + parseInt(routeArr[i][1][2]);
            }
                        s += "Distance: " + routeArr[i][0] + ", " + "Duration: " + routeArr[i][1] + "<br />";

                    }

                    document.getElementById("dvDistance").innerHTML = s;
                    directionsDisplay.setDirections(response);


                }

                // Here's the AJAX request
                var httpRequest;
                if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
                    httpRequest = new XMLHttpRequest();
                } else if (window.ActiveXObject) { // IE 6 and older
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                }
                httpRequest.onreadystatechange = function() {                           // here the function name that is designed to handle the response
                    if (httpRequest.readyState == 4 && httpRequest.status == 200) {          //200 OK response code. // 4 is complete response received
                        alert(httpRequest.responseText);
                    }
                };
                httpRequest.open("POST", "mapdb.php", true);       // here true means asynchronously server is called,i.e,without page reloading
                httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                httpRequest.send("source=" + source + "&destination=" + destination + "&sel=" + sel + "&i=" + i + "&routes=" + JSON.stringify(routeArr));

            });

            //-----------------------------DISTANCE AND DURATION----------------------------------------------------

            var service = new google.maps.DistanceMatrixService();          // Different Services Provided by APIs
            service.getDistanceMatrix({
                origins: [source],
                destinations: [destination],
                travelMode: google.maps.TravelMode.DRIVING,
                unitSystem: google.maps.UnitSystem.METRIC,
                avoidHighways: false,
                avoidTolls: false
            }, function (response, status){
                if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
                   /*var distance = globalResponse.rows[0].elements[0].distance.text;    //  Distance Calculation From data provide by APIs
                    var duration = globalResponse.rows[0].elements[0].duration.text;      //  Duration Calculation From data provide by APIs
                    var distance = globalResponse.routes[0].legs[0].distance.text;
                    var duration = globalResponse.routes[0].legs[0].duration.text;
                    var dvDistance = document.getElementById("dvDistance");         // This Variable is for Fetching the Routes distance and displaying it on web page.
                    dvDistance.innerHTML = "";
                    dvDistance.innerHTML += "Distance: " + distance + "<br />";
                    dvDistance.innerHTML += "Duration:" + duration;//+ " "+typeof response.routes.length;*/

                }else {
                    alert("Unable to find the distance via road.");
                }
            });
        var sel = document.getElementById('modes').value;                      // which mode the user is preferring

        }
    </script>
    <table border="0" cellpadding="0" cellspacing="3">
        <tr>
            <td colspan="2">
                Source:
                <input type="text" id="txtSource"  style="width: 200px" />
                &nbsp; Destination:
                <input type="text" id="txtDestination" style="width: 200px" />
                &nbsp; Travel Mode:
                <select id="modes">
                    <option value="driving" >Driving</option>
                    <option value="cycling">Cycling</option>
                    <option value="transit">Transit</option>
                    <option value="walking"selected>Walking</option>
                </select>
                <br />
                <input type="button" value="Get Route" onclick="GetRoute()" />
                <hr />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <div id="dvDistance">
                </div>
            </td>
        </tr>
        <tr>
            <td>
                <div id="dvMap" style="width: 800px; height: 500px">
                </div>
            </td>
            <td>
                <div id="dvPanel" style="width: 500px; height: 500px">
                </div>
            </td>
        </tr>
    </table>
    <br>
</body>
 mapdb.php
<?php
if(isset($_POST['source'], $_POST['destination'], $_POST['sel'], $_POST['i']) && count($_POST['routes']))
{
    $routes_array = json_decode($_POST['routes'], true);

                                                    // Create connection
    $conn = new mysqli("localhost", "root", "", "testdb");
                                                    // Check connection
    if ($conn->connect_error)
{
         die("Connection failed: " . $conn->connect_error);
    }

$i = $_POST['i'];
$sel = $_POST['sel'];
    $source = $_POST['source'];
    $destination = $_POST['destination'];
    $query = "INSERT INTO trip(source, destination, mode, num_routes) VALUES('{$source}', '{$destination}', '{$sel}', '{$i}')";
    if($conn->query($query)){

        $trip_id = $conn->insert_id;
        foreach($routes_array as $route){
            $distance = $route[0];
            $duration = $route[1];
            $query = "INSERT INTO route(trip_id, distance, duration) VALUES({$trip_id}, '{$distance}', '{$duration}')";  //distance in km and durtion
            $conn->query($query);
        }
        echo "Sumeet!!!Success";
    }
else
{
        echo "Something went wrong!!! Record couldn't be inserted";
    }

    // Close connection
    $conn->close();
}

?>
解决方案

Change the MODE to Walking , Transit, Bicycling in your request.First check the output using google directions APIs endpoint on your browser.Walking and Bicycling results are not available for every pair of locations.

Appending the last part of your travelMode: google.maps.TravelMode."Change here".enter link description hereIf iteration(loop) is not possible repeat the code thrice.

这篇关于我如何获得所有旅行模式的距离和持续时间,例如驾驶、交通、骑自行车、在我的页面中行走,并将其存储在 db 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-15 13:07