javascript - 如何在一张 map 上规划多个地点的路线?

标签 javascript jquery google-maps

我有多个源和目标,对应源 A、C 和目标 B、D。我需要用不同的 map 标记图标显示 A 和 B、C 和 D 之间的路线。请帮助我做到这一点

提前致谢。 这是我尝试用于单一源和目标标记的代码。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Find a route using Geolocation and Google Maps API</title>
    <script src="http://maps.google.com/maps/api/js?sensor=true"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>
      function calculateRoute(from, to) {
        // Center initialized to Naples, Italy
        var myOptions = {
          zoom: 10,
          center: new google.maps.LatLng(40.84, 14.25),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        // Draw the map
        var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);

        var directionsService = new google.maps.DirectionsService();
        var directionsRequest = {
          origin: from,
          destination: to,
          travelMode: google.maps.DirectionsTravelMode.DRIVING,
          unitSystem: google.maps.UnitSystem.METRIC
        };
        directionsService.route(
          directionsRequest,
          function(response, status)
          {
            if (status == google.maps.DirectionsStatus.OK)
            {
              new google.maps.DirectionsRenderer({
                map: mapObject,
                directions: response
              });
            }
            else
              $("#error").append("Unable to retrieve your route<br />");
          }
        );
      }

      $(document).ready(function() {
        // If the browser supports the Geolocation API
        if (typeof navigator.geolocation == "undefined") {
          $("#error").text("Your browser doesn't support the Geolocation API");
          return;
        }

        $("#from-link, #to-link").click(function(event) {
          event.preventDefault();
          var addressId = this.id.substring(0, this.id.indexOf("-"));

          navigator.geolocation.getCurrentPosition(function(position) {
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({
              "location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
            },
            function(results, status) {
              if (status == google.maps.GeocoderStatus.OK)
                $("#" + addressId).val(results[0].formatted_address);
              else
                $("#error").append("Unable to retrieve your address<br />");
            });
          },
          function(positionError){
            $("#error").append("Error: " + positionError.message + "<br />");
          },
          {
            enableHighAccuracy: true,
            timeout: 10 * 1000 // 10 seconds
          });
        });

        $("#calculate-route").submit(function(event) {
          event.preventDefault();
          calculateRoute($("#from").val(), $("#to").val());
        });
      });
    </script>
    <style type="text/css">
      #map {
        width: 500px;
        height: 400px;
        margin-top: 10px;
      }
    </style>
  </head>
  <body>
    <h1>Calculate your route</h1>
    <form id="calculate-route" name="calculate-route" action="#" method="get">
      <label for="from">From:</label>
      <input type="text" id="from" name="from" required="required" placeholder="An address" size="30" />
      <a id="from-link" href="#">Get my position</a>
      <br />

      <label for="to">To:</label>
      <input type="text" id="to" name="to" required="required" placeholder="Another address" size="30" />
      <a id="to-link" href="#">Get my position</a>
      <br />

      <input type="submit" />
      <input type="reset" />
    </form>
    <div id="map"></div>
    <p id="error"></p>
  </body>
</html>

最佳答案

每次调用 calculateRoute() 时,您都会创建一个新的 map 实例(您已经能够创建多个路线,但您只会看到 1 条路线,因为您只能看到最后一张 map ) 。仅创建单个 Maps 实例:

 function calculateRoute(from, to) {
    //use only  a single maps-instance
    if(!window.mapObject){
      var myOptions = {
      zoom: 10,
      center: new google.maps.LatLng(40.84, 14.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    // Draw the map
    mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
    // you also need only a single    DirectionsService-instance
    directionsService = new google.maps.DirectionsService();

    }

     var directionsRequest = {
        origin: from,
        destination: to,
        travelMode: google.maps.DirectionsTravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC
      };

    directionsService.route(
      directionsRequest,
      function(response, status)
      {
        if (status == google.maps.DirectionsStatus.OK)
        {
          new google.maps.DirectionsRenderer({
            map: mapObject,
            directions: response
          });
        }
        else
          $("#error").append("Unable to retrieve your route<br />");
      }
    );
  }

关于javascript - 如何在一张 map 上规划多个地点的路线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22574616/

相关文章:

javascript - 如何自定义OpenERP 6.1 WebClient HTML DOM?

javascript - 通过 Angular 显示json数据

javascript - 如何解决此问题以将图像从 HTML div 元素添加到谷歌地图标记弹出内容?

google-maps - 如何在 flutter 中找到从当前位置到其他一些地方的最近位置?

javascript - 我在哪里插入 - google.maps.event.trigger(map, 'resize' );

javascript - 使用javascript对具有相同属性的div进行分组

javascript - Node.js Nodemailer 对象数组到 CSV 文件作为电子邮件中的附件

javascript - 消除嵌入表格时的鼠标悬停事件问题

javascript - 根据 Chrome 的 JavaScript 控制台,没有 JavaScript 错误,但我的页面无法正常工作

javascript - Chart.JS 数据集标签格式不同