I tried to look for exactly what I mentioned in the question, but I couldn't find such code example which can find/generate the directions from current location to specified destination using only latitude and longitude (of both entities) as core parameters.

I don't have any other parameter of any entity(either source or destination) that could assist in generating directions.

I have done this code so far and also previously:

<script>
        function initMap() {
            var directionsService = new google.maps.DirectionsService;
            var directionsDisplay = new google.maps.DirectionsRenderer;
            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 7,
                center: {lat: 41.85, lng: -87.65}
            });
            directionsDisplay.setMap(map);
            var onChangeHandler = function() {
                calculateAndDisplayRoute(directionsService, directionsDisplay);
            };
            document.getElementById('start').addEventListener('change', onChangeHandler);
            document.getElementById('end').addEventListener('change', onChangeHandler);
        }
        function calculateAndDisplayRoute(directionsService, directionsDisplay) {
            directionsService.route({
                origin: document.getElementById('start').value,
                destination: document.getElementById('end').value,
                travelMode: 'DRIVING'
            }, 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=[API_Key]&callback=initMap">
        </script>

But this code requires the destination and source location's name like "st louis, mo" or "oklahoma city, ok", and I have only latitude and longitude of current location and destination.

Could anyone guide on this ?

2

There are 2 best solutions below

0
On

DirectionsRequest take as parameters in origin and destination 3 formats:

LatLng: var myLatLng = new google.maps.LatLng({lat: -34, lng: 151});

LatLngLiteral: {lat: -34, lng: 151}

Place generally as a query "oklahoma city" but other formats can be accepted.

You should comply to this formats and it will work. I recommend LatLng format in your case.

2
On

Refer to the Google Maps Directions documentation section Directions Requests.

fields

  • origin (required) specifies the start location from which to calculate directions. This value may be specified as a String (for example, "Chicago, IL"), as a LatLng value or as a google.maps.Place object. If you use a google.maps.Place object, you can specify a place ID, a query string or a LatLng location. You can retrieve place IDs from the Geocoding, Place Search and Place Autocomplete services in the Google Maps JavaScript API. For an example using place IDs from Place Autocomplete, see Place Autocomplete and Directions.
  • destination (required) specifies the end location to which to calculate directions. The options are the same as for the origin field described above.

...

In order to use only latitude and longitude (of both entities) as core parameters, use LatLng values.

First, add variables with scope outside the functions for the inputs above the initMap function:

var map, startInput, endInput;

function initMap() {
    startInput = document.getElementById('start');
    endInput = document.getElementById('end');

Then when adding directions to the map, use latLng objects like below, parsing the input with String.split() to separate the latitude and longitude values into arrays to be referenced when creating the LatLng objects:

var startParts = startInput.value.split(',');
var endParts = endInput.value.split(',');
if (startParts.length > 1 && endParts.length > 1) {
    var origin = new google.maps.LatLng(startParts[0], startParts[1]);
    var destination = new google.maps.LatLng(endParts[0], endParts[1]);
    directionsService.route({
         origin: origin,
         destination: destination,
    ...}

And if the browser supports geolocation, that can be used to get the location of the user's browser:

window.onload = function() {
  var startPos;

  if (navigator.geolocation) {
    var geoSuccess = function(position) {
      startPos = position;
      document.getElementById('startLat').innerHTML = startPos.coords.latitude;
      document.getElementById('startLon').innerHTML = startPos.coords.longitude;
    };
    var geoError = function(error) {
      console.log('Error occurred. Error code: ' + error.code);
    // error.code can be:
    //   0: unknown error
    //   1: permission denied
    //   2: position unavailable (error response from location provider)
    //   3: timed out
    };
    navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
  }
};

Try this snippet with user input :

//global variables 
var map, startInput, endInput;

function initMap() {
  startInput = document.getElementById('start');
  endInput = document.getElementById('end');

  var directionsService = new google.maps.DirectionsService;
  var directionsDisplay = new google.maps.DirectionsRenderer;
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 7,
    center: {
      lat: 41.85,
      lng: -87.65
    }
  });
  directionsDisplay.setMap(map);
  var onChangeHandler = function() {
    calculateAndDisplayRoute(directionsService, directionsDisplay);
  };
  document.getElementById('start').addEventListener('change', onChangeHandler);
  document.getElementById('end').addEventListener('change', onChangeHandler);
  document.getElementById('increment').addEventListener('click', function() {
    var endInputParts = endInput.value.split(',');
    if (endInputParts.length > 1) {
      endInputParts[1] = parseFloat(endInputParts[1]) + 1;
      endInput.value = endInputParts.join(',');
      onChangeHandler();
    }
  });
}

function calculateAndDisplayRoute(directionsService, directionsDisplay) {
  var startParts = startInput.value.split(',');
  var endParts = endInput.value.split(',');
  if (startParts.length > 1 && endParts.length > 1) {
    var origin = new google.maps.LatLng(startParts[0], startParts[1]);
    var destination = new google.maps.LatLng(endParts[0], endParts[1]);
    directionsService.route({
      origin: origin,
      destination: destination,
      travelMode: 'DRIVING'
    }, function(response, status) {
      if (status === 'OK') {
        directionsDisplay.setDirections(response);
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });
  }
}
/*
 * use google maps api built-in mechanism to attach dom events
 */
google.maps.event.addDomListener(window, "load", initMap);
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<input id="start" type="text" value="41.43206,-81.38992" />
<input id="end" type="text" value="41.43206,-88.38992" />
<button id="increment"> To Longitude += 1</button>
<div id="map" style="height: 300px;"></div>