javascript 在WayPoints中传递Lat Long数组Google Maps API 3

y3bcpkx1  于 2023-05-05  发布在  Java
关注(0)|答案(3)|浏览(135)

如何在waypoints对象中传递一个Latitude和Longitude数组,然后将其传递给directionservice对象以绘制路线?
如果我想通过一个单一的纬度,我们将通过它如下

waypoints: 
[{
     location:new google.maps.LatLng(42.496403,-124.413128),
     stopover:false
}],

但是我如何传递一个纬度和经度的数组呢?
请找到我尝试过的代码(它抛出了一个脚本错误):

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Lat long way points (LatLng)</title>
<style type="text/css"> 
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript"> 
  var directionDisplay;
  var directionsService = new google.maps.DirectionsService();
  var map;

  function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    var chicago = new google.maps.LatLng(41.850033, -87.6500523);
    var myOptions = {
      zoom: 6,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: chicago
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);
    calcRoute();
  }

  function calcRoute() {
      var first=new google.maps.LatLng(42.496403,-124.413128);
      var second=new google.maps.LatLng(42.496401,-124.413126);
      var values=[first,second];
      alert(values[0]);
      alert(values[1]);
      var waypts=[];
      alert(values.length); 
    for(var i=0;i<=values.length;i++)
    {
     waypts.push({location:values[i],stopover:true}); 
    }
     alert(waypts);
    var request = {
        origin: "1521 NW 54th St, Seattle, WA 98107 ",
        destination: "San Diego, CA",
        waypoints: waypts,
        optimizeWaypoints: true,
        travelMode: google.maps.DirectionsTravelMode.WALKING
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
        var route = response.routes[0];
        var summaryPanel = document.getElementById("directions_panel");
        summaryPanel.innerHTML = "";
        // For each route, display summary information.
        for (var i = 0; i < route.legs.length; i++) {
          var routeSegment = i + 1;
          summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
          summaryPanel.innerHTML += route.legs[i].start_address + " to ";
          summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
          summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
        }
      } else {
        alert("directions response "+status);
      }
    });
  }
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="float:left;width:70%;height:100%;"></div>
<div id="control_panel" style="float:right;width:30%;text-align:left;padding-top:20px">
<div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div>
</div>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"> 
</script> 
<script type="text/javascript"> 
</script> 
</body>
</html>
5f0d552i

5f0d552i1#

这是如何添加多个航路点

waypoints: [{location: first, stopover: false},
                        {location: second, stopover: false}],

示例的完整代码

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
        <title>Lat long way points (LatLng)</title>
        <style type="text/css"> 
            html { height: 100% }
            body { height: 100%; margin: 0px; padding: 0px }
        </style>
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
        <script type="text/javascript">
            var directionDisplay;
            var directionsService = new google.maps.DirectionsService();
            var map;

            function initialize() {
                directionsDisplay = new google.maps.DirectionsRenderer();
                var chicago = new google.maps.LatLng(41.850033, -87.6500523);
                var myOptions = {
                    zoom: 6,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    center: chicago
                };
                map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
                directionsDisplay.setMap(map);
                calcRoute();
            }

            function calcRoute() {
                var first = new google.maps.LatLng(42.496403, -124.413128);
                var second = new google.maps.LatLng(42.496401, -124.413126);

                var request = {
                    origin: "1521 NW 54th St, Seattle, WA 98107 ",
                    destination: "San Diego, CA",
                    waypoints: [{location: first, stopover: false},
                        {location: second, stopover: false}],
                    optimizeWaypoints: true,
                    travelMode: google.maps.DirectionsTravelMode.WALKING
                };
                directionsService.route(request, function (response, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setDirections(response);
                        var route = response.routes[0];
                        var summaryPanel = document.getElementById("directions_panel");
                        summaryPanel.innerHTML = "";
                        // For each route, display summary information.
                        for (var i = 0; i < route.legs.length; i++) {
                            var routeSegment = i + 1;
                            summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
                            summaryPanel.innerHTML += route.legs[i].start_address + " to ";
                            summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
                            summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
                        }
                    } else {
                        alert("directions response " + status);
                    }
                });
            }
        </script>
    </head>
    <body onload="initialize()">
        <div id="map_canvas" style="float:left;width:70%;height:100%;"></div>
        <div id="control_panel" style="float:right;width:30%;text-align:left;padding-top:20px">
            <div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div>
        </div>
        <script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
        </script> 
        <script type="text/javascript">
        </script> 
    </body>
</html>
s6fujrry

s6fujrry2#

这里的例子应该有所帮助:https://developers.google.com/maps/documentation/javascript/directions?hl=cs#Waypoints
有效地将waypoints对象分配给数组,例如:

waypoints : waypointsArray

其中阵列包含多个航路点对象,例如:

{
      location: LatLng,
      stopover:true
  }

希望这能帮上忙。

qvk1mo1f

qvk1mo1f3#

最受欢迎的解决方案对我不起作用,因为代码的某些部分似乎已经过时了。因此,我发布了我的代码。以下解决方案在2023年对我有效。
只需将script标签中的XXXXXXXXXXXX替换为Google Maps API密钥,然后在浏览器中运行示例,您就可以开始了:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Lat long way points (LatLng)</title>
    <style>
        /* Optional: Makes the sample page fill the window. */
        html,
        body {
            height: 100%;
            margin: 0;
            padding: 0;
        }

        #container {
            height: 100%;
            display: flex;
        }

        #sidebar {
            flex-basis: 15rem;
            flex-grow: 1;
            padding: 1rem;
            max-width: 30rem;
            height: 100%;
            box-sizing: border-box;
            overflow: auto;
        }

        #map {
            flex-basis: 0;
            flex-grow: 4;
            height: 100%;
        }

        #directions-panel {
            margin-top: 10px;
        }
    </style>
</head>
<body>
<div id="container">
    <div id="map"></div>
    <div id="sidebar">
        <div>
            <b>Start:</b>
            <select id="start">
                <option value="Halifax, NS">Halifax, NS</option>
                <option value="Boston, MA">Boston, MA</option>
                <option value="New York, NY">New York, NY</option>
                <option value="Miami, FL">Miami, FL</option>
            </select>
            <br/>
            <b>Waypoints:</b> <br/>
            <i>(Ctrl+Click or Cmd+Click for multiple selection)</i> <br/>
            <select multiple id="waypoints">
                <option value="montreal, quebec">Montreal, QBC</option>
                <option value="toronto, ont">Toronto, ONT</option>
                <option value="chicago, il">Chicago</option>
                <option value="winnipeg, mb">Winnipeg</option>
                <option value="fargo, nd">Fargo</option>
                <option value="calgary, ab">Calgary</option>
                <option value="spokane, wa">Spokane</option>
            </select>
            <br/>
            <b>End:</b>
            <select id="end">
                <option value="Vancouver, BC">Vancouver, BC</option>
                <option value="Seattle, WA">Seattle, WA</option>
                <option value="San Francisco, CA">San Francisco, CA</option>
                <option value="Los Angeles, CA">Los Angeles, CA</option>
            </select>
            <br/>
            <input type="submit" id="submit"/>
        </div>
        <div id="directions-panel"></div>
    </div>
</div>

<script src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXX&callback=initMap" defer></script>
<script>
    function initMap() {
        const directionsService = new google.maps.DirectionsService();
        const directionsRenderer = new google.maps.DirectionsRenderer();
        const map = new google.maps.Map(document.getElementById("map"), {
            zoom: 6,
            center: { lat: 41.85, lng: -87.65 },
        });

        directionsRenderer.setMap(map);
        document.getElementById("submit").addEventListener("click", () => {
            calculateAndDisplayRoute(directionsService, directionsRenderer);
        });
    }

    function calculateAndDisplayRoute(directionsService, directionsRenderer) {
        const waypts = [];
        const checkboxArray = document.getElementById("waypoints");

        for (let i = 0; i < checkboxArray.length; i++) {
            if (checkboxArray.options[i].selected) {
                waypts.push({
                    location: checkboxArray[i].value,
                    stopover: true,
                });
            }
        }

        directionsService
            .route({
                origin: document.getElementById("start").value,
                destination: document.getElementById("end").value,
                waypoints: waypts,
                optimizeWaypoints: true,
                travelMode: google.maps.TravelMode.DRIVING,
            })
            .then((response) => {
                directionsRenderer.setDirections(response);

                const route = response.routes[0];
                const summaryPanel = document.getElementById("directions-panel");

                summaryPanel.innerHTML = "";

                // For each route, display summary information.
                for (let i = 0; i < route.legs.length; i++) {
                    const routeSegment = i + 1;

                    summaryPanel.innerHTML +=
                        "<b>Route Segment: " + routeSegment + "</b><br>";
                    summaryPanel.innerHTML += route.legs[i].start_address + " to ";
                    summaryPanel.innerHTML += route.legs[i].end_address + "<br>";
                    summaryPanel.innerHTML += route.legs[i].distance.text + "<br><br>";
                }
            })
            .catch((e) => window.alert("Directions request failed due to " + status));
    }

    window.initMap = initMap;
</script>
</body>
</html>

上述解决方案可从以下官方来源获得:Google Maps - Waypoints in Directions

相关问题