简体   繁体   English

我如何获取所有行车方式(例如行车,公交,骑车,步行)的距离和时长,并将其存储在数据库中

[英]how can i get distance and duration for all travel modes like driving,transit,cycling,walking in my page,and storing the same in db

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 我只成功显示和存储单个出行方式的数据,但现在我想存储所有出行方式的距离和持续时间之类的数据,这是代码,我需要执行哪些更改,请提前感谢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. 在您的请求中将MODE更改为Walking,Transit,Bicycling。首先使用浏览器上的Google Directions API端点检查输出。 Walking and Bicycling results are not available for every pair of locations. 步行和骑车的结果不适用于每对地点。

Appending the last part of your travelMode: google.maps.TravelMode."Change here". 在travelMode的最后部分附加:google.maps.TravelMode。“在此处更改”。 enter link description here If iteration(loop) is not possible repeat the code thrice. 在此处输入链接描述。如果不可能进行迭代(循环),请重复三次代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过谷歌地图与PHP获得步行或驾驶距离 - How to get walking or driving distance via google maps with php 如何使我的SlickJS Carousal在3张图像之间循环,并在循环时将它们全部可见? - How can I get my SlickJS Carousal to cycle between 3 images and have them all visible while cycling? 如何使用Google Distance Matrix API获取总行驶距离? - How to get the total driving distance with Google Distance Matrix API? 如何在JavaScript中获取以KM为单位的总距离 - How can i get the total distance in KM in my javascript 我的oauth2回调页面可以是相同的html页面吗? 以及我如何获得令牌? - Can my oauth2 callback page be the same html page? and how do I get the token? 我怎样才能让旋转木马继续骑自行车? - How can I keep carousel keep cycling? 我如何在我的cordova应用程序中喜欢一个Facebook页面? - How can I like a facebook page in my cordova app? 为什么我滚动到顶部总是动画? 我怎样才能立即到达顶部? - Why is my scroll to top always animated? And how can I instantly travel to top? 公交出行方式的路线限制 - Limits for Directions with Transit Travel Mode 如何通过在Coldfusion代码中放置一个函数来使所有链接滚动到页面顶部 - How can I get all my links to scroll to the top of the page by placing one function in a coldfusion code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM