0

感谢这个论坛的帮助,我几乎完成了寻找起点和许多标记之间的最短路线的任务。然而,我的距离测量只是采用Haversine公式,但它没有显示两点之间的真实路由距离。我正在尝试结合先前已在 Google Map 中使用的开发功能,以使用 DirectionServices 获得两点之间的最短距离。从以下主页,我找到了计算每条路线距离的方法。 http://ratan.com.np/calculate-distance-location-longitude-latitude-google-maps-v3-route/

我已经反复检查了我的代码,但我仍然不知道为什么代码失败了......它返回了一个语法错误'unexpected token <'......

谁能帮我看一下代码……看看我修改后的程序中的任何概念错误……非常感谢……

单击一个按钮以调用 'Submit2() 函数

var directionsDisplay;
var directionsService = new google.maps.DirectionsService();

var map;
var origin = null;
var destination = null;
var markersArray = [];

var start_lat = null;
var start_long = null;
var end_lat = null;
var end_long = null;

var station_num = null; 
var trig_name = null;


var total_dist;
var closest_dist;
var closest_marker;


var Submit2=function() {

        var URL2="Search_nearest_trig_advanced.php";    //Call another PHP to load all markers in JSON format
        $.ajax({
            url: URL2,

            type: "POST",
            dataType: "json",
            success: function(data){
                $.each(data, function(i, item) {
                     start_lat = item.start_lat;  //Return the Lat, Lng of the Starting point from Textbox
                     start_long = item.start_long;
                     station_num = item.station_num; 
                     trig_name = item.trig_name;
                     end_lat = item.end_lat;
                     end_long = item.end_long;


                     origin = new google.maps.LatLng(start_lat, start_long); //Origin and Destination parameters are used for Google Direction Services
                     destination = new google.maps.LatLng(end_lat, end_long);   
                     marker = new google.maps.Marker({
                         map: map,
                         position: destination,
                         icon: trigicon,
                         title: trig_name
                     })
                     markersArray.push(marker);
                     calcRoute2();  //find the total distance 'total_dist' for each route

                     if (total_dist > closest_dist) { //Replace the closest_marker by the one with shorter distance
                     closest_dist = total;   
                     closest_marker.setMap(null);
                     closest_marker = marker;
                     } 

                }); 
            },

            error:function(xhr, ajaxOptions, thrownError){ 
                alert(xhr.status); 
                alert(thrownError); 
             }

        }); 

        destination = closest_marker.getPosition();
        calcRoute(); //the original method to show the route


};

调用 calcRoute() 函数计算路线距离

  function calcRoute2() {

  document.getElementById("directions_panel").innerHTML = "";


  directionsDisplay = new google.maps.DirectionsRenderer({
    'map': map,
    'preserveViewport': false,  //Google Map will change the zoom extent to match with the Direction route if set false
    'draggable': true
});


var request = {
    origin: origin,
    destination: destination,
    waypoints: waypoints,
    travelMode: google.maps.DirectionsTravelMode.DRIVING,
    optimizeWaypoints: document.getElementById('optimize').checked,
    avoidHighways: document.getElementById('highways').checked,
    avoidTolls: document.getElementById('tolls').checked
};

directionsService.route(request, function(response, status) {
  if (status == google.maps.DirectionsStatus.OK) {
    directionsDisplay.setDirections(response);
    computeTotalDistance(response);

  }
});

directionsVisible = false;
}

function computeTotalDistance(result) {
    var total_dist = 0;
    var myroute = result.routes[0];
    for (i = 0; i < myroute.legs.length; i++) {
    total_dist += myroute.legs[i].distance.value;
    }
    total_dist = total_dist / 1000 // the distance output is converted to KiloMeter

    }

'search_nearest_trig_advanced.php'

<?php
require_once "dbconnect.php";
require_once "hk1980.php";
    $coor_x = $_POST['hk80_x'];
    $coor_y = $_POST['hk80_y'];
/* Connect to the MySQL database. */
if (!($connection = @ mysql_connect($remotehost, $username, $password)))
    die("Connection failed");
if (!(mysql_select_db($database, $connection)))
    die("Couldn't select testing database");

// Run the query on the connection

$sql_query = "Select station_num, trig_name, X(trig_xy_pos) as X_Coor, Y(trig_xy_pos) as Y_Coor From trig_station";

if (!($sql_result = @ mysql_query($sql_query, $connection)))
    die("Couldn't run query");

while ($row = @ mysql_fetch_array($sql_result, MYSQL_ASSOC))
{   
        $start_east = floatval($coor_x);
        $start_north = floatval($coor_y);
        $hk1980_start = array($start_east, $start_north);   

        $end_east = floatval($row['X_Coor']);
        $end_north = floatval($row['Y_Coor']);
        $hk1980_end = array($end_east,$end_north);

        $wgs84_start = hk1980_to_wgs84($hk1980_start[1],$hk1980_start[0],2);
        $wgs84_end = hk1980_to_wgs84($hk1980_end[1],$hk1980_end[0],2);

        $row_set[] = array("start_lat" => $wgs84_start[0], "start_long" => $wgs84_start[1], "station_num" => $row['station_num'],"trig_name" => $row['trig_name'],"end_lat" => $wgs84_end[0],"end_long" => $wgs84_end[1]);
    }
    echo json_encode($row_set);
?>
4

2 回答 2

2

不返回路线DistanceMatrix转弯指示。你必须为此使用DirectionsService。所以,你要做的就是先把你的出发地和目的地传递给 Matrix,然后找到最短的路线。找到最短路线后,将该路线传递给路线服务以获取转弯信息。

如果您需要在多条路线中骑行,您可能必须使用高级服务。谷歌限制免费访问其服务以防止滥用。

这是该概念的一个工作示例

相关代码:

function calculateDistances() {
    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix({
        origins: [origin], //array of origins
        destinations: destinations, //array of destinations
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        avoidHighways: false,
        avoidTolls: false
    }, callback);
}

function callback(response, status) {
    if (status != google.maps.DistanceMatrixStatus.OK) {
        alert('Error was: ' + status);
    } else {
        //we only have one origin so there should only be one row
        var routes = response.rows[0];
        //need to find the shortest 
        var lowest = Number.POSITIVE_INFINITY;
        var tmp;
        var shortestRouteIdx;
        var resultText = "Possible Routes: <br/>";
        for (var i = routes.elements.length - 1; i >= 0; i--) {
            tmp = routes.elements[i].duration.value;
            resultText += "Route " + destinations[i] + ": " + tmp + "<br/>";
            if (tmp < lowest) {
                lowest = tmp;
                shortestRouteIdx = i;
            }
        }
        //log the routes and duration.
        $('#results').html(resultText);

        //get the shortest route
        var shortestRoute = destinations[shortestRouteIdx];
        //now we need to map the route.
        calculateRoute(origin, shortestRoute)
    }
}

//Calculate the route of the shortest distance we found.
function calculateRoute(start, end) {
    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.TravelMode.DRIVING
    };
    directionsService.route(request, function (result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(result);
        }
    });
}
于 2013-05-18T15:28:45.500 回答
0

如果您尝试获取到多个位置的行驶距离并且不需要路线,请使用DistanceMatrix

于 2013-05-17T16:28:00.900 回答