如何从访问者的当前位置获取方向到我在嵌入式谷歌地图中的位置

时间:2016-03-26 11:38:24

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

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

<!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>

2 个答案:

答案 0 :(得分:1)

我使用-geolocation-and-the-google-maps-api /从https://www.sitepoint.com/find-a-route-y略微修改代码,使用select 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>

答案 1 :(得分:0)

<!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>