Ways to obtain the latitudes and longitudes for various routes between a starting point and a destination

At the moment, I am successfully retrieving all the latitude and longitude coordinates from the source to destination location.

However, I am only able to obtain 1 path using this method.

Now, I would like to have the ability to choose a specific route path among different paths available between the source and destination locations
.

Furthermore, I intend to store all these latitude and longitude coordinates in my database.

Database structure :

Rid Lat Lon

I am utilizing ASP.NET C# technology.

How can I provide an option to select a path and then retrieve all the corresponding latitude and longitude coordinates along that path.

Additionally, I need to save all the latitude and longitude data into my database using C# code.

How can I accomplish this task?

The following is the code snippet I am currently using:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Geocoding service</title>
    <style>
        html, body, #map-canvas {
            height: 100%;
            min-height: 600px;
            min-width: 700px;
            margin: 0px;
            padding: 0px;
        }

        #map-canvas {
            height: 50%;
        }

        #panel {
            position: absolute;
            top: 5px;
            left: 50%;
            margin-left: -180px;
            z-index: 5;
            background-color: #fff;
            padding: 5px;
            border: 1px solid #999;
        }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
</head>
<body>
    <div id="panel">
        <label>
            Origin
          <input id="origin" type="text" value="">
        </label>
        <label>
            Destination
          <input id="destination" type="text" value="">
        </label>
        <input type="button" value="GetDirections" onclick="calcRoute()">
    </div>
    <div id="map-canvas"></div>
    <div id="vertex-container">
        <label>Points</label>
        <ul id="vertex">
        </ul>
    </div>
    <script type="text/javascript">
        var directionsDisplay;
        var directionsService = new google.maps.DirectionsService();
        var map;

        function initialize() {
            directionsDisplay = new google.maps.DirectionsRenderer();

            var mapOptions = {
                zoom: 7,
                center: new google.maps.LatLng(25.5911, 86.1611)
            };
            map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
            directionsDisplay.setMap(map);
        }

        function calcRoute() {
            var start = document.getElementById('origin').value;
            var end = document.getElementById('destination').value;
            var request = {
                origin: start,
                destination: end,
                travelMode: google.maps.TravelMode.DRIVING
            };
            directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                    if (response.routes && response.routes.length > 0) {
                        var routes = response.routes;
                        for (var j = 0; j < routes.length; j++) {
                            var points = routes[j].overview_path;
                            var ul = document.getElementById("vertex");
                            for (var i = 0; i < points.length; i++) {
                                var li = document.createElement('li');
                                li.innerHTML = getLiText(points[i]);
                                ul.appendChild(li);
                            }
                        }
                    }
                }
            });
        }
        function getLiText(point) {
            var lat = point.lat(),
                lng = point.lng();
            return "lat: " + lat + " lng: " + lng;
        }

        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</body>
</html>

Answer №1

To enable Google Maps to provide multiple route options, you need to construct your google.maps.DirectionsRequest object with the provideRouteAlternatives property set to true. Here's an example:

var request = {
    origin: start,
    destination: end,
    travelMode: google.maps.TravelMode.DRIVING,
    provideRouteAlternatives : true
};

Upon receiving a response, the google.maps.DirectionsResult object will contain the routes, which is an array of DirectionsRoute objects (usually only one if provideRouteAlternatives is set to false).

After obtaining the routes using:

var routes = response.routes;

You can iterate through the elements in routes to access different paths.

When invoking

directionsDisplay.setDirections(response)
, Google Maps will display the route at index 0 by default. To render other paths, you must specify the routeIndex property within the
google.maps.DirectionsRendererOptions
object passed to the google.maps.DirectionsRenderer constructor.

For rendering all paths on the map, you can use the following approach:

var routes = response.routes;
for (var j = 0; j < routes.length; j++) {
    var directionsDisplay = new google.maps.DirectionsRenderer({ map: map, directions: response, routeIndex: j });
    directionsDisplays.push(directionsDisplay);
    var points = routes[j].overview_path;
    var ul = document.getElementById("vertex");
    for (var i = 0; i < points.length; i++) {
        var li = document.createElement('li');
        li.innerHTML = getLiText(points[i]);
        ul.appendChild(li);
    }
}

If you wish to customize the color of the polylines representing the various routes, this can also be configured within the DirectionsRendererOptions object.

The complete code snippet would look like this:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Geocoding service</title>
    <style>
      html, body, #map-canvas { height: 100%; min-height: 600px; min-width: 700px; margin: 0px; padding: 0px }
      #map-canvas { height: 50%; }
      #panel { position: absolute; top: 5px; left: 50%; margin-left: -180px; z-index: 5; background-color: #fff; padding: 5px; border: 1px solid #999; }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
</head>
<body>
    <div id="panel">
      <label>Origin
          <input id="origin" type="text" value="">
      </label>
      <label>Destination
          <input id="destination" type="text" value="">
      </label>
      <input type="button" value="GetDirections" onclick="calcRoute()">
    </div>
    <div id="map-canvas"></div>
    <div id="vertex-container">
        <label>Points</label>
        <ul id="vertex">
        </ul>
    </div>
    <script type="text/javascript">
        var directionsDisplays = [];
        var directionsService = new google.maps.DirectionsService();
        var map;

        function initialize() {

            var mapOptions = {
                zoom: 7,
                center: new google.maps.LatLng(48.85727000, 2.35238)
            };
            map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
        }

        function calcRoute() {
            var start = document.getElementById('origin').value;
            var end = document.getElementById('destination').value;
            var request = {
                origin: start,
                destination: end,
                provideRouteAlternatives: true,
                travelMode: google.maps.TravelMode.DRIVING
            };
            directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    if (response.routes && response.routes.length > 0) {
                        var routes = response.routes;
                        for (var j = 0; j < routes.length; j++) {
                            var directionsDisplay = new google.maps.DirectionsRenderer({ map: map, directions: response, routeIndex: j });
                            directionsDisplays.push(directionsDisplay);
                            var points = routes[j].overview_path;
                            var ul = document.getElementById("vertex");
                            for (var i = 0; i < points.length; i++) {
                                var li = document.createElement('li');
                                li.innerHTML = getLiText(points[i]);
                                ul.appendChild(li);
                            }
                        }
                    }
                }
            });
        }
        function getLiText(point) {
            var lat = point.lat(),
                lng = point.lng();
            return "lat: " + lat + " lng: " + lng;
        }

        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</body>
</html>

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

The functionality of Angular Datepicker is disrupted when scrolling through the page

Coding in HTML <div class="col-5 col-md-3 px-0 daterange-picker"> <div class="form-group"> <div class="input-group"> <input type="text" id="second ...

Is there a way to change an element's display to 'block'? (see more information below)

I'm having an issue with my event listener for a button that is supposed to change the css of #popUpForm. It seems to only work when I add inline css directly to #popUpForm. Is there a way to achieve this without using inline css and instead setting t ...

What is the best way to search for and isolate an array object within an array of objects using Javascript?

I am attempting to narrow down the list based on offerings const questions = [ { "id": 2616, "offerings": [{"code": "AA"},{"code": "AB"}]}, { "id": 1505, "offerings": [ ...

There seems to be an issue with Jquery not triggering the Webservice method in the Firefox browser, despite it working successfully in Chrome

Currently, I have an issue where a webservice method called via ajax in jQuery is functioning correctly in Chrome and IE browsers but not in Firefox. Here is the jQuery code: $("#btnUpdate").click(function () { var objEmp = { employeeID: $("#Em ...

Display or conceal component based on specific URL in React.js navigation bar

Hey there, I'm facing an issue with hiding certain links in the navbar when users visit specific pages. For instance, on the Landing page, I want to hide the Orders and Basket links and only show the Login link. I'm having trouble figuring out ho ...

Populate a shopping cart with items using AngularJS

Greetings from an Angular newbie! I'm currently working on developing a shopping cart specifically designed for college students. The objective is to input the name and price of items into a text field and upon clicking a button, have the item added t ...

What is the best way to display information in a newly added row of a datatables table?

Working on ASP.NET gridview conversions with datatables.net plug-in. The reason behind this is complex and subject to debate. But, I need assistance with a specific issue. The process of converting the gridview using Javascript was simple and effective. H ...

Reduce the amount of ajax calls

Currently, I have implemented checkboxes that serve as search filters on a website. Every time a user checks a filter box, an ajax request is triggered to fetch data from the server and display it. The issue arises when users select multiple checkboxes in ...

Creating a single Vuetify expansion panel: A step-by-step guide

Is there a way to modify the Vuetify expansion panel so that only one panel can be open at a time? Currently, all panels can be closed which is causing issues. I would like the last opened panel to remain open. I also want to prevent closing the currently ...

Using Node.js to Send Parameters in a POST Request

I have a node.js application with an express framework and a POST route defined as follows: app.post('/test', function(req, res){ //res.send(req.body.title + req.body.body) console.log(req.params); console.log(req.body); console.log(req.bod ...

Tips for inserting SVG images into PDF documents

Is there a way to generate a PDF upon clicking the "generate PDF" button? The PDF should display an image containing highlighted squares corresponding to the user's selections on the webpage. I've been struggling to include the SVG in the PDF as ...

Learn the process of triggering an Ajax request by clicking on a Table row

I am facing an issue with my table. Whenever I click on a row, the <TR> element gets assigned the class "selected". My goal is to capture the content of the first <TD> element in that row (which represents an ID), and then make an Ajax request. ...

Create a unique Bitcoin address using a derivation scheme

Starting with a derivation scheme that begins with tpub... for the testnet, I am looking to generate bitcoin addresses from this scheme. I also need a method that will work for the mainnet. Is there a library available that can assist me with this task? ...

Ways to retrieve all data from a specific column in a database

I have a table for companies and I initially used the query select * from company. However, I now only need to retrieve all the company names from this table and store them in a string array. The following code snippet only retrieves one row of company n ...

The latest version of Material UI, v4, does not currently support React 18

Looking to incorporate MUI (Material UI) into my website design. Encountering difficulties with installing this library, receiving the error message below: -npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While ...

Locate the index position of an element in one array based on a corresponding element in a

I am seeking a way to determine the index and group that an item belongs to within a parent json group. Is there a method for achieving this? I am willing to modify the json format if necessary. I made an attempt using JSON.stringify(), but it seems to be ...

using a function as an argument in the map method within a React component

I have a challenge where I am trying to display blog posts retrieved from my database. However, for each item, I also need to execute a download image function. I attempted to include the function within the .map function but encountered some errors. I am ...

The voting system will increase or decrease by 1 to 5 during each round

Recently, I added a voting system to my website inspired by this source. It's functioning well, but there is an issue where each vote can sometimes count for more than one. You can view the source code on the original website and test it out live here ...

"Unleashing the Power of MongoDB's Dynamic $in

Is there a way to dynamically pass a list of strings to a $in clause in MongoDB? I attempted the following code, but it didn't work and I haven't been able to locate more information other than an example with hardcoded values. The restrictedUs ...

How to retrieve the column names of a table using Web SQL?

Working on extracting column lists from Web SQL (Chrome's local database). One approach is to gather information from sqlite_master. SELECT name, sql FROM sqlite_master WHERE type="table" AND name = "'+name+'"; As an example, here is a sam ...