Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/445.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用Google Maps API计算从已知点到路线中最近点的距离_Javascript_Google Maps_Google Maps Api 3 - Fatal编程技术网

Javascript 如何使用Google Maps API计算从已知点到路线中最近点的距离

Javascript 如何使用Google Maps API计算从已知点到路线中最近点的距离,javascript,google-maps,google-maps-api-3,Javascript,Google Maps,Google Maps Api 3,我正在做一个显示多条路线的地图的项目。我需要能够搜索一个地址,并返回到每个路线内最近点的距离。从已知点测量距离很容易,但我需要知道从已知点到路线上最近点的距离 下面是绘制3条路线和一个半径为50公里的圆圈的单点的代码。我需要测量每条路线上从该点到最近点的距离 <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /

我正在做一个显示多条路线的地图的项目。我需要能够搜索一个地址,并返回到每个路线内最近点的距离。从已知点测量距离很容易,但我需要知道从已知点到路线上最近点的距离

下面是绘制3条路线和一个半径为50公里的圆圈的单点的代码。我需要测量每条路线上从该点到最近点的距离

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta charset="utf-8" />
<title>Waypoints in directions</title>
<!-- Latest compiled and minified CSS -->

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" />

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css" />

<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

<style>

html, body, #map-canvas {
    height: 100%;
    margin: 0px;
    padding: 0px
}

#map-canvas {
    float:left;
    width:70%;
    height:100%;
}

#panel {
    position: absolute;
    top: 5px;
    left: 50%;
    margin-left: -180px;
    z-index: 5;
    background-color: #fff;
    padding: 5px;
    border: 1px solid #999;
}

#control_panel {
    float:right;
    width:30%;
    text-align:left;
    padding-top:20px;
}

</style>

</head>
<body>

<div id="map-canvas"></div>
<div id="control_panel">

    <div class="container" style="width:auto;">
        <h1>Trips:</h1>


        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">Blue Run</h3>
            </div>
            <div class="panel-body">
                <ol>
<li><strong>Autosystems (University)</strong><br />300 University Ave, Plant 1 Belleville, ON K8N 5T7</li><li><strong>Fanuc America</strong><br />3900 West Hamlin Road Rochester Hills, MI 48309</li>                </ol>
            </div>
        </div>

        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">Big Run</h3>
            </div>
            <div class="panel-body">
                <ol>
<li><strong>Asyst Technologies</strong><br />5811 - 99th Avenue Kenosha, WI 53144</li><li><strong>Autosystems America Inc</strong><br />46600 Port St Plymouth, MI 48170</li>                </ol>
            </div>
        </div>

        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">Slow Run</h3>
            </div>
            <div class="panel-body">
                <ol>
<li><strong>A B Automation</strong><br />2155 North Talbot Road Windsor, ON N9A 6J3</li><li><strong>Autosystems America Inc</strong><br />46600 Port St Plymouth, MI 48170</li><li><strong>Industrial Automation</strong><br />2968 Waterview Rochester Hills, MI 48309</li><li><strong>Arkema Inc.</strong><br />4350 Campground Rd Louisville, KY 40216</li>                </ol>
            </div>
        </div>
    </div>

</div>

<input type="hidden" name="lat" id="lat" value="" />
<input type="hidden" name="lng" id="lng" value="" />

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<api-key>"></script>
<script type="text/javascript">

// Initialize some variables
var directionsService = new google.maps.DirectionsService();
var num, map, data;
var requestArray = [], renderArray = [];

// A JSON Array containing some people/routes and the destinations/stops
var jsonArray = {
    "Blue Run": ["300 University Ave, Plant 1 Belleville, ON K8N 5T7","3900 West Hamlin Road Rochester Hills, MI 48309"],
    "Big Run": ["5811 - 99th Avenue Kenosha, WI 53144","46600 Port St Plymouth, MI 48170"],
    "Slow Run": ["2155 North Talbot Road Windsor, ON N9A 6J3","46600 Port St Plymouth, MI 48170","2968 Waterview Rochester Hills, MI 48309","4350 Campground Rd Louisville, KY 40216"]
}

// 16 Standard Colours for navigation polylines
var colourArray = ['navy', 'red', 'green', 'grey', 'fuchsia', 'black', 'white', 'lime', 'maroon', 'purple', 'aqua', 'silver', 'olive', 'blue', 'yellow', 'teal'];

// Let's make an array of requests which will become individual polylines on the map.
function generateRequests(){

    requestArray = [];

    for (var route in jsonArray){
        // This now deals with one of the people / routes

        // Somewhere to store the wayoints
        var waypts = [];

        // 'start' and 'finish' will be the routes origin and destination
        var start, finish

        // lastpoint is used to ensure that duplicate waypoints are stripped
        var lastpoint

        data = jsonArray[route]

        limit = data.length
        for (var waypoint = 0; waypoint < limit; waypoint++) {
            if (data[waypoint] === lastpoint){
                // Duplicate of of the last waypoint - don't bother
                continue;
            }

            // Prepare the lastpoint for the next loop
            lastpoint = data[waypoint]

            // Add this to waypoint to the array for making the request
            waypts.push({
                location: data[waypoint],
                stopover: true
            });
        }

        // Grab the first waypoint for the 'start' location
        start = (waypts.shift()).location;
        // Grab the last waypoint for use as a 'finish' location
        finish = waypts.pop();
        if(finish === undefined){
            // Unless there was no finish location for some reason?
            finish = start;
        } else {
            finish = finish.location;
        }

        // Let's create the Google Maps request object
        var request = {
            origin: start,
            destination: finish,
            waypoints: waypts,
            travelMode: google.maps.TravelMode.DRIVING
        };

        // and save it in our requestArray
        requestArray.push({"route": route, "request": request});
    }

    processRequests();
}

function processRequests(){

    // Counter to track request submission and process one at a time;
    var i = 0;

    // Used to submit the request 'i'
    function submitRequest(){
        directionsService.route(requestArray[i].request, directionResults);
    }

    // Used as callback for the above request for current 'i'
    function directionResults(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {

            // Create a unique DirectionsRenderer 'i'
            renderArray[i] = new google.maps.DirectionsRenderer();
            renderArray[i].setMap(map);

            // Some unique options from the colorArray so we can see the routes
            renderArray[i].setOptions({
                preserveViewport: true,
                suppressInfoWindows: true,
                polylineOptions: {
                    strokeWeight: 4,
                    strokeOpacity: 0.8,
                    strokeColor: colourArray[i]
                },
                markerOptions:{
                    icon:{
                        path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
                        scale: 4,
                        strokeColor: colourArray[i]
                    },
                    clickable: true,
                    title: 'Boo yeah!'
                }
            });

            // Use this new renderer with the result
            renderArray[i].setDirections(result);
            // and start the next request
            nextRequest();
        }

    }

    function nextRequest(){
        // Increase the counter
        i++;
        // Make sure we are still waiting for a request
        if(i >= requestArray.length){
            // No more to do
            return;
        }
        // Submit another request
        submitRequest();
    }

    // This request is just to kick start the whole process
    submitRequest();
}

// Called Onload
function init() {

    var address = "320 Elizabeth St Midland, ON L4R 4L6";
    var geo = new google.maps.Geocoder;
    geo.geocode({'address':address},function(results, status){
        if (status == google.maps.GeocoderStatus.OK) {
            var latitude = results[0].geometry.location.lat();
            var longitude = results[0].geometry.location.lng();

            // Some basic map setup (from the API docs) 
            var mapOptions = {
                //center: new google.maps.LatLng(50.677965, -3.768841),
                center: new google.maps.LatLng(latitude, longitude),
                zoom: 10,
                mapTypeControl: true,
                streetViewControl: true,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                travelMode: google.maps.TravelMode.DRIVING,
                //unitSystem: google.maps.UnitSystem.IMPERIAL
                unitSystem: google.maps.UnitSystem.METRIC
            };

            map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

            var circle = {
                strokeColor: '#AA0000',
                strokeOpacity: 0.6,
                strokeWeight: 2,
                fillColor: '#CCCCCC',
                fillOpacity: 0.35,
                map: map,
                radius: 50000,
                center: new google.maps.LatLng(latitude, longitude)
            };

            var pickupSpot = new google.maps.Circle(circle);

            // Start the request making
            generateRequests()
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

// Get the ball rolling and trigger our init() on 'load'
google.maps.event.addDomListener(window, 'load', init);

</script>

</body>
</html>

方向上的航路点
html,正文,#地图画布{
身高:100%;
边际:0px;
填充:0px
}
#地图画布{
浮动:左;
宽度:70%;
身高:100%;
}
#面板{
位置:绝对位置;
顶部:5px;
左:50%;
左边距:-180px;
z指数:5;
背景色:#fff;
填充物:5px;
边框:1px实心#999;
}
#控制面板{
浮动:对;
宽度:30%;
文本对齐:左对齐;
填充顶部:20px;
}
旅行:
蓝跑
  • 自动系统(大学)
    美国法努克大学路300号贝尔维尔工厂1号,位于密歇根州罗切斯特山哈姆林西路3900号,邮编:48309
  • 大跑
  • Asyst Technologies
    威斯康星州基诺沙第99大道5811号,邮编:53144
  • 美国汽车系统公司
    密歇根州普利茅斯港街46600号,邮编:48170
  • 慢跑
  • A B Automation
    2155北塔尔博特路温莎,N9A 6J3
  • 美国汽车系统公司
    46600圣普利茅斯港,密苏里州48170工业自动化,KY 40216 //初始化一些变量 var directionsService=new google.maps.directionsService(); var-num、map、data; var requestArray=[],renderArray=[]; //包含一些人员/路线和目的地/站点的JSON数组 var jsonArray={ “蓝跑”:[“密歇根州罗切斯特山哈姆林西路3900号,K8N 5T7上贝尔维尔1号工厂300大学大道,邮编:48309”], “Big Run”:[“威斯康星州基诺沙大道5811-99号,邮编53144”,“密歇根州普利茅斯港街46600号,邮编48170”], “慢跑”:[“温莎塔尔博特北路2155号,N9A 6J3”,“密歇根州圣普利茅斯港46600号,邮编48170”,“密歇根州罗切斯特山水景城2968号,邮编48309”,“肯塔基州路易斯维尔坎普兰路4350号,邮编40216”] } //导航多段线的16种标准颜色 var colorArray=[‘海军蓝’、‘红’、‘绿’、‘灰’、‘紫’、‘青’、‘褐’、‘紫’、‘水’、‘银’、‘橄榄’、‘蓝’、‘黄’、‘青绿色’]; //让我们创建一个请求数组,这些请求将成为地图上的单个多段线。 函数生成器请求(){ requestArray=[]; for(jsonArray中的var路由){ //现在,它处理其中一个人/路线 //存放路标的地方 var-waypts=[]; //“开始”和“结束”将是路线的起点和终点 开始,结束 //lastpoint用于确保剥离重复的航路点 var lastpoint 数据=jsonArray[路由] 限制=数据长度 对于(var航路点=0;航路点<限制;航路点++){ if(数据[航路点]==最后一点){ //最后一个航路点的副本-不用麻烦了 继续; } //为下一个循环准备最后一点 lastpoint=数据[航路点] //将其添加到阵列的航路点,以发出请求 推({ 位置:数据[航路点], 中途停留:对 }); } //抓取“开始”位置的第一个航路点 开始=(waypts.shift()).location; //抓取最后一个航路点作为“终点”位置 finish=waypts.pop(); if(finish==未定义){ //除非出于某种原因没有完工位置? 完成=开始; }否则{ finish=finish.location; } //让我们创建GoogleMaps请求对象 var请求={ 来源:start, 目的地:完成, 航路点:航路点, travelMode:google.maps.travelMode.DRIVING }; //并将其保存在我们的请求数组中 push({“route”:route,“request”:request}); } processRequests(); } 函数processRequests(){ //计数器跟踪请求提交,并一次处理一个请求; var i=0; //用于提交请求“i” 函数submitRequest(){ 路由(requestArray[i].request,directionResults); } //用作当前“i”的上述请求的回调 函数方向结果(结果、状态){ if(status==google.maps.directionstatus.OK){ //创建唯一的DirectionsRenderer“i” renderArray[i]=新的google.maps.DirectionsRenderer(); renderArray[i].setMap(map); //colorArray提供了一些独特的选项,因此我们可以查看路线 renderArray[i].setOptions({ 对,, suppressInfoWindows:对, 多段线选项:{ 冲程重量:4, 笔划不透明度:0.8, strokeColor:colorArray[i] }, 标记选项:{ 图标:{ 路径:google.maps.SymbolPath.BACKWARD\u CLOSED\u箭头, sc
    // Use this new renderer with the result
    renderArray[i].setDirections(result);
    // and start the next request
    var polyline = getPolyline(result);
    var marker = new google.maps.Marker({
        position: getClosestPoint(referencePt, polyline),
        map: map,
        icon: iconArray[i]
    });
    nextRequest();