2013-05-17 15 views
0

感謝您在此論壇的幫助,我幾乎完成了我的任務,即搜索起點和多個標記之間的最短路線。但是,我的距離測量只是採用Haversine公式,但它沒有顯示兩點之間的真實佈線距離。我正在嘗試結合之前在Google Map中已經開發的開發功能,使用DirectionServices獲得兩點之間的最短距離。從下面的主頁,我找到了計算每條路線距離的方法。 http://ratan.com.np/calculate-distance-location-longitude-latitude-google-maps-v3-route/使用Google Maps API v3的DirectionsService查找並顯示最接近的標記路線

,我已經反覆檢查我的代碼,但我仍然不知道爲什麼代碼失敗......它返回一個語法錯誤「意外的標記<」 ....

誰能幫我承擔代碼一看...看到任何概念的錯誤在我修改後的方案....非常非常感謝......

點擊一個按鈕來調用「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()函數N到計算路徑距離

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); 
?> 
+0

您是否嘗試過只通過代碼運行的一個標誌,看是否出現錯誤?基於你對代碼的快速瀏覽,我幾乎可以保證你在'DirectionsService'中遇到'OVER_QUERY_LIMIT'錯誤。嘗試在循環中調用地圖服務時這很常見。這聽起來像你正試圖解決「旅行推銷員」問題。改爲使用Google的DistanceMatrix服務(https://developers.google.com/maps/documentation/javascript/distancematrix)。我相信這會給你帶來更好的結果。 –

+0

感謝您的建議。我也看到了DistanceMatrix功能,但我想要的是循環200個以上的目的地並獲得距離最近的那個。似乎distancematrix只能處理每個請求25個目的地,這對我來說是不夠的... 如果問題來自'Over_Query_Limit'問題,我試圖修改$ SQL_Query以僅返回五個最接近的標記進一步計算...任何建議如何做到這一點? –

+0

我通過SQL查詢進一步減少了trig站的數量,使其成爲查詢中的五個。我可以在Map上放置所有五個標記,並計算computeTotalDistance()函數中每個路徑的距離(在函數的末尾添加'alert(total_dist)')。然而,我發現total_dist值無法傳遞迴Submit2()和caluRoute2()函數(通過在執行calcRoute2()和computeTotalDistance()函數後添加alert(total_dist)來檢查。javascript中是否存在任何問題,像關閉問題??? –

回答

2

DistanceMatrix不返回路線轉由轉彎的方向。你必須使用DirectionsService。所以,你想要做的是先將你的出發地和目的地先交給Matrix,然後找到最短的路線。找到最短路線後,通過路線服務路線獲取轉由轉彎的信息。

如果您需要循環多條路線,則可能必須使用高級服務。 Google限制免費訪問其服務以防止濫用。

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

感謝您的建議。示例是我想要做的... 但是,我有一些問題 在循環jQuery AJAX JSON中的所有五個標記...也許我更好地根據您的suggsted代碼添加一個新問題來詳細說明它... 感謝您的幫助。 –

+0

GeoCoder對象在您的jsfiddle的例子? – nurettin

+0

@nurettin這是遺留在前一個小提琴的代碼。當我構建示例時,我通常會分叉類似的東西。謝謝你的提醒,我糾正了小提琴。 –

0

如果你試圖去多個位置行進距離和不需要的路線,使用DistanceMatrix

+0

感謝您的建議......我花了一些時間嘗試使用'距離矩陣',通過放置一個原點和五個目的地來使用參數'results [j]找到路線的距離。 distance.text'。但我發現功能不起作用,我懷疑'results [j] .distance.text'是一個文本而不是真正的距離來比較。是真的嗎?如果是的話...這種方法對我來說是行不通的,因爲我必須用最短的距離顯示路線,而不是顯示所有路線與面板上的距離。 –

相關問題