-2

I put in bold what I need changed in my app, I can't figure out how to make it work, using the current location of the user on the site to center the map and use as the Origin value for the Directions API, and also I have a static value as the Destination, but I want to change it to a "clicked on"

Essentially, disregard the waypoints, but I want this to load the map at the users location, enter that value as the ORIGIN and instead of having a static destination, I want the user to click, and then it would run, giving the directions from where they are to where they clicked

" `var waypts = new Array();
<!-- var directionsService; -->
<!-- var directionsDisplay; -->
var bool = false, bool1 = false;
function initMap() {
  var directionsService = new google.maps.DirectionsService;
  var directionsDisplay = new google.maps.DirectionsRenderer;
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 6,
    center: {lat: CURRENT LOCATION, lng: CURRENT LOCATION}
  });
  directionsDisplay.setMap(map);
  calculateAndDisplayRoute(directionsService, directionsDisplay);


}

function calculateAndDisplayRoute(directionsService, directionsDisplay) {


  var locations = new Array(I have waypoints I enter here)
  var channel_id = KEY;
    var api_key = 'KEY';
    var bin = [];

    var j=0, k=0;
    for(i=1; i<=locations.length; i++){
        $.getJSON('http://api.thingspeak.com/channels/' + channel_id + '/field/' + i + '/last',
            function(data) { 
                if(data > 0)  {
                    waypts.push({
                      location: '' + locations[j++],
                      stopover: true
                      });
                }
            k++; if(k==locations.length) { show(directionsService, directionsDisplay); }
            });

    }

    function show(directionsService, directionsDisplay){
console.log(waypts);
  directionsService.route({
    origin: 'NEED CURRENT VALUE',
    destination: 'CLICK ON MAP',
    waypoints: waypts,
    optimizeWaypoints: true,
    travelMode: 'DRIVING'
  }, function(response, status) {
    if (status === 'OK') {
      //document.getElementById('waypoints').innerHTML = response.routes[0].waypoint_order;
      directionsDisplay.setDirections(response);
      var route = response.routes[0];
      var summaryPanel = document.getElementById('directions-panel');
      //summaryPanel.innerHTML = '';
      // For each route, display summary information.
      console.log(route);
      for (var i = 0; i < route.legs.length; i++) {
        var routeSegment = i + 1;
        <!-- summaryPanel.innerHTML += Route.legs[i]; -->
        <!-- document.getElementById("directions-panel").innerHTML= route.legs[i].start_address + '<br>'; -->
        //summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + 
        //'</b><br>';
        //document.getElementById("ul_list").innerHTML+= '<li>'+route.legs[i].start_address +'</li>'; 
        for (var j = 0; j < route.legs[i].steps.length; j++) {
            document.getElementById("ul_list").innerHTML+= '<li>'+route.legs[i].steps[j].instructions +'</li>'; 
        }
        //document.getElementById("ul_list").innerHTML+=  '<li>'+route.legs[i].end_address +'<li>';
        //document.getElementById("#buttet2").innerHTML= route.legs[i].end_address + '<br>'; 
        //summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';

      }
      document.getElementById("ul_list").innerHTML+= '<li>'+route.legs[i].start_address +'</li>'; 
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });

  bool = true;
}

</script>
</body>
</html>`
  • 1
    Can you elaborate on how your code "doesn't work"? What were you expecting, and what actually happened? If you got an exception/error, post the line it occurred on and the exception/error details. Please [edit] these details in or we may not be able to help. – Claudia May 02 '18 at 01:57
  • Oh, and also, you may wish to investigate the `` " ` `` at the start of the first line - I'd be surprised if you're not getting notified of syntax errors at least. – Claudia May 02 '18 at 01:59
  • Possible duplicate of [Center map on user's location (Google Maps API v3)](https://stackoverflow.com/questions/37101616/center-map-on-users-location-google-maps-api-v3) – MrUpsidown May 02 '18 at 09:16

1 Answers1

1

You can use the HTML5 Geolocation object to get the user's current location (if the browser supports it, and the user has granted the app permission to use their location) as a google.maps.LatLng object that can be set as the origin for the Directions request. You can then set a click event listener on the google.maps.Map object to get the LatLng for the location of the click and then call the route() method of the DirectionsService

Here is a simple sample JSBin that finds the user's location but defaults to Los Angeles if geolocation fails. The origin is a green circle. You can then click on the map for a red circle, and then the directions are plotted

The code:

<!DOCTYPE html>
<html>
  <head>
    <title>Geolocation</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <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;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      // Note: This example requires that you consent to location sharing when
      // prompted by your browser. If you see the error "The Geolocation service
      // failed.", it means you probably did not give permission for the browser to
      // locate you.
      var map;
      function initMap() {

        var origin = new google.maps.LatLng(34.051659,-118.249085);

        map = new google.maps.Map(document.getElementById('map'), {
          center:  origin,
          zoom: 14,
          gestureHandling: "greedy"
        });

        var marker1 = new google.maps.Marker({
            icon: {path: google.maps.SymbolPath.CIRCLE,
              scale: 5,
              strokeColor: '#338833',
              strokeOpacity: 0.5
            },
            animation:  google.maps.Animation.BOUNCE,
            map: map,
            position: origin,
            title: "start"
        });

        var marker2 = new google.maps.Marker({
            icon: {path: google.maps.SymbolPath.CIRCLE,
              scale: 5,
              strokeColor: '#FF0000',
              strokeOpacity: 0.5
            },
            animation:  google.maps.Animation.BOUNCE,
            map: map,
            title: "finish"
        });

        // Try HTML5 geolocation.
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            origin = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            map.setCenter(origin);
            marker1.setPosition(origin);
          }, function() {
            alert("Error: The Geolocation service failed. Using default location");
          });
        } else {
          alert("Error: Your browser doesn't support geolocation. Using default location");
        }

        var directionsService = new google.maps.DirectionsService();
        var directionsRenderer = new google.maps.DirectionsRenderer();
        directionsRenderer.setMap(map);

        map.addListener('click', function(event) {
            var destination = event.latLng;
            marker2.setPosition(destination);
            directionsService.route({
                origin: origin,
                destination: destination,
                travelMode: 'DRIVING'
            }, function(response, status) {
              if (status === 'OK') {
            directionsRenderer.setDirections(response);
              } else {
                window.alert('Directions request failed due to ' + status);
              }
            });
        });
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=YOUR_KEY">
    </script>
  </body>
</html>
Preston
  • 856
  • 5
  • 6
  • Thanks! I apologize if I didn't give a ton of info, I'm learning. I'm wondering if I can ask one more thing. I understand what you posted, and that's what I'm looking to do, but I'm a little lost on where I would implement this in my code, keeping all of the other functions. Would you be able to let me know how to put this into the code I pasted? That would be such a huge help. I need to keep the waypoints and all that, but if you wouldn't mind taking a look at my code and pasting the script you gave me into place where it would work with what I'm doing? Thanks again, thank for lookin out :) – Jesse Teindl May 02 '18 at 15:09