【问题标题】:How to get direction from visitor's current location to my location in embedded google maps如何在嵌入式谷歌地图中获取从访客当前位置到我的位置的方向
【发布时间】:2016-07-14 02:06:30
【问题描述】:

我的网站上有一个嵌入的地图,其中包含指向我的办公室地址的标记点。但是,我需要通过网络浏览器中的地理位置自动向用户显示从他们当前位置到我办公室位置的路线。有可能吗?

<!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(), "govandi"));
        });
      });
    </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" 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>

【问题讨论】:

  • 有可能吗?嗯,是的,一切皆有可能。最大的问题是你想花多少时间在上面?到目前为止,您尝试过什么?
  • @SZenC 我查看了教程,但其中大多数要么展示了如何启用地理定位或预定义路线,但没有合并。
  • 你不能把这两个结合起来吗?
  • @SZenC 我已经添加了代码示例
  • @Dr.Molle 嵌入式地图是指在网页上插入的地图。

标签: javascript google-maps google-maps-api-3 geolocation maps


【解决方案1】:
<!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) {
             var myLatLng = {lat: 19.056, lng: 72.921};

            // Center initialized to Mumbai, India
            var myOptions = {
                zoom: 10,
                center: myLatLng,
                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
                        });

                        $('.distance-in-km').text(response.routes[0].legs[0].distance.value / 1000 + "km");

                        alert( response.routes[0].legs[0].distance.value / 1000 + "km" ); // the distance in metres
                    } 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;
            }

            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) {
                                calculateRoute(results[0].formatted_address, "govandi");
                            } else {
                                var marker = new google.maps.Marker({
                                    position: myLatLng,
                                    title: 'Hello World!'
                                  });

                                marker.setMap(mapObject);

                                $("#error").append("Unable to retrieve your address<br />");
                            }
                        });
                });



                calculateRoute($("#from").val(), "govandi");

            $("#calculate-route").submit(function (event) {
                event.preventDefault();



                calculateRoute($("#from").val(), "govandi");
            });


            $('.verify-location > a').click(function(){
                $('.verify-location').hide();
                $('#calculate-route').show();
            });
        });
    </script>
    <style type="text/css">
        #map {
            width: 500px;
            height: 400px;
            margin-top: 10px;
        }
        #calculate-route {
            display: none;
        }
        .verify-location > a {
            cursor: pointer;
            color: #FCA2A2;
        }
    </style>
</head>

<body>
    <div class="verify-location">Is the your location incorrect? <a>Click here to enter your location manually</a></div>
    <form id="calculate-route" name="calculate-route" action="#" method="get">
        <label for="from">From:</label>
        <input type="text" id="from" name="from" placeholder="An address" size="30" />
         <button type="submit">Submit</button>
    </form>
    <div id="map"></div>
    <p id="error"></p>
    <p class="distance-in-km"></p>
</body>

</html>

【讨论】:

    【解决方案2】:

    我对 https://www.sitepoint.com/find-a-route-y using-the-geolocation-and-the-google-maps-api/ 中的代码进行了轻微修改,以便使用选择 html 表单从用户位置到设置目的地的旅程规划器。

    如果它对任何人有用。

    <!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 somewhere near London
        var myOptions = {
          zoom: 10,
          center: new google.maps.LatLng(53, -1),
          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.TRANSIT,
          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>
      <select id="to">
        <option value="51.5548885,-0.108438">Arsenal's Emirates Stadium</option>
        <option value="51.481663,-0.1931505">Chelsea's Stamford Bridge</option>
      </select>
    
      <br />
    
      <input type="submit" />
      <input type="reset" />
    </form>
    <div id="map"></div>
    <p id="error"></p>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 2017-03-06
      相关资源
      最近更新 更多