简体   繁体   中英

let user get direction to specific location from his location in my website

I tried to combine this links with each other " https://developers.google.com/maps/documentation/javascript/geolocation " and " https://developers.google.com/maps/documentation/javascript/examples/directions-panel " but there is a problem with combining together by pushing user current location to a inner html of "div" and then get it back to push it into start of direction path

  <script> var infoWindow; function initMap() { var directionsDisplay = new google.maps.DirectionsRenderer; var directionsService = new google.maps.DirectionsService; var map = new google.maps.Map(document.getElementById('map'), { zoom: 18, center: { lat: 30.0879217, lng: 31.3439407 } }); infoWindow = new google.maps.InfoWindow; // Try HTML5 geolocation. if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { document.getElementById("position1").innerHTML=position.coords.latitude; document.getElementById("position2").innerHTML=position.coords.longitude; var pos = { lat: position.coords.latitude, lng: position.coords.longitude }; infoWindow.setPosition(pos); infoWindow.setContent('Location found.'); infoWindow.open(map); map.setCenter(pos); }, function() { handleLocationError(true, infoWindow, map.getCenter()); }); } directionsDisplay.setMap(map); calculateAndDisplayRoute(directionsService, directionsDisplay); document.getElementById('mode').addEventListener('change', function () { calculateAndDisplayRoute(directionsService, directionsDisplay); }); } function calculateAndDisplayRoute(directionsService, directionsDisplay) { var selectedMode = document.getElementById('mode').value; var x=document.getElementById("position1").innerHTML; var y=document.getElementById("position2").innerHTML; directionsService.route({ origin: { lat: 30.0879217, lng: 31.3439407 }, // Haight. destination: { lat: Number(x), lng: Number(y) }, // Ocean Beach. // Note that Javascript allows us to access the constant // using square brackets and a string value as its // "property." travelMode: google.maps.TravelMode[selectedMode] }, function (response, status) { if (status == 'OK') { directionsDisplay.setDirections(response); } else { window.alert('Directions request failed due to ' + status); } }); } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCb0QRzb5LcbAkUbRH3kRDv4WNVDRMBeq4&callback=initMap"> </script> 
 <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <title>Travel modes in directions</title> <style> /* Always set the map height explicitly to define the size of the div * element that contains the map. */ #map { height: 100%; } /* Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; } #floating-panel { position: absolute; top: 10px; left: 25%; z-index: 5; background-color: #fff; padding: 5px; border: 1px solid #999; text-align: center; font-family: 'Roboto', 'sans-serif'; line-height: 30px; padding-left: 10px; } </style> </head> <body> <div id="position1" ></div> <div id="position2"></div> <div id="floating-panel"> <b>Mode of Travel: </b> <select id="mode"> <option value="DRIVING">Driving</option> <option value="WALKING">Walking</option> <option value="BICYCLING">Bicycling</option> <option value="TRANSIT">Transit</option> </select> </div> <div id="map"></div> 

You can try something like this:

<script>
    var  infoWindow;
    function initMap() {
        // Try HTML5 geolocation.
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            document.getElementById("position1").innerHTML=position.coords.latitude;
            document.getElementById("position2").innerHTML=position.coords.longitude;
            var pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };

            var directionsDisplay = new google.maps.DirectionsRenderer;
            var directionsService = new google.maps.DirectionsService;
            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 18,
                center: { lat: 30.0879217, lng: 31.3439407 }
            });

            infoWindow = new google.maps.InfoWindow;

            infoWindow.setPosition(pos);
            infoWindow.setContent('Location found.');
            infoWindow.open(map);
            map.setCenter(pos);
            directionsDisplay.setMap(map);
            calculateAndDisplayRoute(directionsService, directionsDisplay);
            document.getElementById('mode').addEventListener('change', function () {
                calculateAndDisplayRoute(directionsService, directionsDisplay);
            });
          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
          });
        }


    }
    function calculateAndDisplayRoute(directionsService, directionsDisplay) {
      var selectedMode = document.getElementById('mode').value;
      var x=document.getElementById("position1").innerHTML;
      var y=document.getElementById("position2").innerHTML;

      directionsService.route({
        origin: { lat: 30.0879217, lng: 31.3439407 },  // Haight.
        destination: { lat: Number(x), lng: Number(y) },  // Ocean Beach.
        // Note that Javascript allows us to access the constant
        // using square brackets and a string value as its
        // "property."
        travelMode: google.maps.TravelMode[selectedMode]
      }, function (response, status) {
        if (status == 'OK') {
          directionsDisplay.setDirections(response);
        } else {
          window.alert('Directions request failed due to ' + status);
        }
      });
    }
  </script>

  <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCb0QRzb5LcbAkUbRH3kRDv4WNVDRMBeq4&callback=initMap">
  </script>

Your code crash because you tried to read your position in the calculateAndDisplayRoute before the browser calls your callback where you initialize the lat and long HTML's objects.

Tell me if you have some questions or comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM