查找并显示通过谷歌地图API V3使用为DirectionsService最接近的标记的路线

问题描述 投票:0回答:2

感谢您在这个论坛的帮助,我几乎完成了我在寻找一个起点,许多标记之间的最短路线分配。然而,我的距离measurment简直是采用半正矢公式,但它没有显示两点之间的真实路由距离。我想结合这已经在谷歌地图合作,以获得使用DirectionServices两点之间最短的距离以前发达的功能。从下面的主页,我发现计算每个路径的距离的方法。 http://ratan.com.np/calculate-distance-location-longitude-latitude-google-maps-v3-route/

我已经反复检查我的代码,但我仍然不知道为什么代码失败......它返回一个语法错误“意外的标记<” ....

谁能帮我拿的代码一看...看到任何概念的错误在我修改后的方案....非常非常感谢...

点击一个按钮来调用“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);
?>
php javascript jquery google-maps-api-3 google-direction
2个回答
2
投票

DistanceMatrix不会返回路线转由转动方向。你必须使用DirectionsService了点。所以,你想要做的是首先通过你的起点和目的地矩阵,并找到最短的路线。你发现后的最短路线传递路线导航服务,以获得转由转信息。

如果通过多条路径需要周期,你可能必须使用一个优质的服务。谷歌限制了它的服务,以防止滥用自由进入。

Here is a working example of the concept

相关的代码:

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);
        }
    });
}

0
投票

如果你试图去多个位置行进距离和不需要的路线,使用DistanceMatrix

© www.soinside.com 2019 - 2024. All rights reserved.