Mapping Service by Google - Navigate from your current location to desired destination

I have a script that currently displays a route for either car or transit depending on the user's selection. I am looking to adapt this script to set the origin as the user's current location and route from there to a set latitudes and longitudes destination.

Unfortunately, I haven't been able to figure out how to integrate this functionality into my script. Any assistance would be greatly appreciated!

      function initMap() {
        var directionsDisplay = new google.maps.DirectionsRenderer;
        var directionsService = new google.maps.DirectionsService;
          
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 14,
          center: {lat: *VALUE*, lng: *VALUE*}
        });
        directionsDisplay.setMap(map);
        directionsDisplay.setPanel(document.getElementById('right-panel'));

        calculateAndDisplayRoute(directionsService, directionsDisplay);
        document.getElementById('mode').addEventListener('change', function() {
          calculateAndDisplayRoute(directionsService, directionsDisplay);
        });
      }

      function calculateAndDisplayRoute(directionsService, directionsDisplay) {
        var selectedMode = document.getElementById('mode').value;
        directionsService.route({
          origin: {lat: *VALUE*, lng: *VALUE*},  // User's Current Location.
          destination: {lat: *VALUE*,lng: *VALUE*},  // Set Destination Location.
          travelMode: google.maps.TravelMode[selectedMode],
           transitOptions: {
           arrivalTime: new Date(1489242600000),
           routingPreference: 'FEWER_TRANSFERS'
        },
            unitSystem: google.maps.UnitSystem.IMPERIAL,
             provideRouteAlternatives: true
        }, function(response, status) {
            
          if (status == 'OK') {
            directionsDisplay.setDirections(response);
          } else {
            window.alert('Directions request failed due to ' + status);
          }
        });
      }

Answer №1

When using the Google Directions API, it is important to understand the parameters you can include. Typically, for creating a route with multiple stops, you will need to specify the origin, destination, and possibly waypoints.

Click here to learn more about adding waypoints in Google Directions API.

In the provided link, there is an example demonstrating how to select and include multiple waypoints. To determine the location coordinates, Geolocation can be utilized to obtain latitude and longitude values. These values can then be integrated into the calculateAndDisplay function within the origin parameter as needed.

directionsService.route({
          origin: //input either lat/long or a specific location name
          destination: //input either lat/long or a specific location name
          waypoints: // waypoints field requires an Array of locations or lat/long coordinates
          optimizeWaypoints: true,
          travelMode: 'DRIVING'
},

Explore this link for additional examples on working with directions and waypoints in Google Maps JavaScript API.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can CSS be used to separate elements within a div from the overall page styles, similar to how an iFrame functions?

Is there a way to isolate elements within a div, similar to how it would behave in an iFrame? I am facing issues with the global SharePoint styles affecting my app inside SharePoint. I want to completely disable these global styles so that my app only use ...

Is it possible to locate an element using regex in Python while using Selenium?

Is it possible to interact with a dynamically generated dropdown list using Selenium if I only know the phrase present in its id or class name? Can Selenium locate an element using regex and click on it accordingly? ...

Looking to retrieve the dynamic "Publish Date" value from a webpage using HtmlUnit in Java?

As part of a coding exercise, I am currently working on a project that involves comparing the current system date with dates on various web pages to determine if there are any new updates. While most of the pages work as expected, there is one particular p ...

Should custom directives be utilized for templating within AngularJS applications?

Thinking about optimizing my AngularJS app, I'm considering creating custom directives for the navigation bar and footer which appear on every page. This way, I can easily modify them without having to update each individual html file. Do you think th ...

The improper utilization or replacement of Jest mock in an Angular standalone component's unit test is causing issues

Presented here is a streamlined Ionic/Angular component with unnecessary code removed. import { IonicModule, ModalController } from '@ionic/angular'; @Component({ selector: 'my-component', templateUrl: 'my-component.html' ...

What is the best way to integrate ngx-translate's pipe for global translation?

I'm currently utilizing the ngx-translate package in order to internationalize my Angular application. When translating text using the translate pipe like so: {{ 'title' | translate }} An issue arises when attempting to use this pipe in ot ...

Locate the present position of the slider element

I am currently in the process of creating a website that features pages displayed in a slider format. Each page has its own unique ID, but all share a common class called 'section'. However, I am encountering difficulty in identifying the ID of t ...

What is the process to access array elements in AngularJS?

When coding in HTML, <select class="element-margin-top" ng-model="vm.selectedRole" ng-options="(roleName,enabled) in vm.roleNames"> <option value="">All Roles</option>{{vm.roles[0]}} </select> I am tryin ...

The Kenburn zoom image effect fails to function

I want to implement a zoom effect on an image using the Ken Burns effect when it is clicked. However, the code I have written does not seem to be working as expected. Here is the code snippet: $(document).ready(function () { $('.kenburns').on( ...

Utilizing AJAX in Wordpress to Dynamically Update HREF Links

My website now has AJAX functionality, and you can see a live example at www.mathewhood.com. I am interested in changing the URL format when clicked from To something like , without the /sitefiles/ for security reasons. Below is my code. If anyone is ex ...

The issue lies with the Cookies.get function, as the Typescript narrowing feature does not

Struggling with types in TypeScript while trying to parse a cookie item using js-cookie: // the item 'number' contains a javascript number (ex:5) let n:number if(typeof Cookies.get('number')!== 'undefined'){ n = JSON.pars ...

Is it possible to use an ngClick function in one directive to toggle data in another?

Currently, I am in the process of developing a weather application using Angular 1.5.8 where users should have the option to switch between imperial and metric units for temperature and wind speed. The toggle feature along with all the weather data fetche ...

Displaying API response array object in React application

Currently, I am attempting to retrieve information from an API, parse the response content, and then display it in a loop. However, I have encountered a warning message: webpackHotDevClient.js:138 ./src/App.js Line 20: Expected an assignment or function ...

Step-by-step guide on permanently updating the text of select options with JavaScript

Here is the code for a select option with different values: <select id="test" onchange="changeContent()"> <option>1</option> <option>2</option> <option>3</option> </select> The javascript function that chan ...

Arranging the data in my JSON reply

{ "JsonResult": { "List": [{ "Subject": "Something", "Type": 0, "TypeDescription": "Referral" }], } } When I hit my service, I receive a sample JSON response. After that, there is a button with ...

Clear the Material-UI textfield upon form submission

After submitting the form, how can I clear the value from the TextField? All of the components in my code are functional components, not class ones. The example below shows one of the TextFields, with others similar to it. Currently, setting type='sea ...

The basic shapes in the scene are just out of sight

Sorry for the easy question, but I'm having trouble getting the BoxGeometry to show up in the scene. The red background is displaying correctly. var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(0, window.innerWidth / window.inn ...

Animating scrollTop using jQuery is a useful feature for creating

I am facing an issue with several section tags within a div that has overflow set to hidden. The structure of the code is as follows: <div id="viewport"> <section> content </section> <section> content </ ...

Using Typescript to Declare Function and React Component Types

Currently challenging myself to delve into Typescript (ugh). Usually, I can deduce the appropriate type by analyzing the return values. Nonetheless, in this particular scenario, that method is proving ineffective. type SomeReactAProps = { Type1: ReactEle ...