Ways to retrieve the latitude and longitude coordinates between the starting point and the destination

I need to retrieve all the latitude and longitude coordinates from Google Maps.

For instance: If I input the latitudes and longitudes of a source and destination, and a path is drawn on the map like below:

Now, I want to obtain all the latitude and longitude points between point A (source) and B (destination), and store them in a database.

If my car deviates from this path, I want it to trigger an action like sending me an email.

I am working on development using ASP.NET C#.

How can I retrieve all the latitude and longitude values?

I am currently utilizing the script below:

  <script>
        function initialize() {
            var map = new google.maps.Map(document.getElementById('map_canvas'), {
                zoom: 8,
                center: new google.maps.LatLng(22.304634, 73.161070),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }),
       directions = new google.maps.DirectionsService(),
       displayer = new google.maps.DirectionsRenderer({
            draggable: true
        });

            displayer.setMap(map);
            directions.route({
                origin: new google.maps.LatLng(22.304634, 73.161070),
                destination: new google.maps.LatLng(23.022242, 72.548844),
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            }, function (result) {
                displayer.setDirections(result);
            });
        }
        google.maps.event.addDomListener(window, 'load', initialize);
        google.maps.event.addListener(displayer, 'directions_changed', some_method);
    </script>

Answer №1

To successfully send the data stored in the overview_path property of the google.maps.DirectionsRoute object to the server and save it in the database, you need to iterate over this property first.

Here is an example demonstrating how to loop through the overview_path:

<!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(48.85727000, 2.35238)
            };
            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>

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

Obtain the result of two "Synchronous" nested queries using Express and Mongoose

I need to fetch an array of elements structured like this: ApiResponse = [ {_id: 1, name: Mike, transactions: 5}, {_id: 2, name: Jhon, Transactions: 10} ] The user data is retrieved from a query on the "Users" schema, while the tr ...

`There is an issue with updating the canvas in a Windows Form application`

Recently, I've been working on a sorting visualization algorithm in C# and I've encountered an issue with refreshing the canvas element. Although I attempted to refresh the canvas every time I redraw, the results were not visually appealing. I a ...

Updating the appearance of tabs in React Native Navigation dynamically during runtime

I am currently working with the startTabBasedApp API, which includes three tabs in my app. I have a requirement to change the background color of the tabBar for specific screens dynamically. Is it possible to achieve this at runtime? For instance: Scree ...

Impressive javascript - extract file from formData and forward it

Presented here is my API handler code. // Retrieve data. const form = formidable({ multiples: true }); form.parse(request, async (err: any, fields: any, files: any) => { if (!drupal) { return response.status(500).send('Empty ...

Tips for implementing a client-side event when an asp:menu item is clicked

Currently, I'm incorporating the <asp:Menu> control into my website and populating it with data from a table in my Sql Server database using an XML data source. Now, I am looking to implement a client-side event when a user clicks on a menu item ...

Using the POST method in Node.js is not functioning properly on the Replit server when using express

Recently diving into the world of backend development, I have been utilizing Node.js on a Replit server with express to host an application for handling files: However, hitting a roadblock when attempting to execute a post request! var express = ...

Single-page application powered by WordPress and universal JavaScript

Can a WordPress single-page application be created using isomorphic/universal JavaScript approaches (utilizing frameworks like React and Angular2)? ...

Repeating items must be unique; duplicates are not permitted on ng-repeat

The data retrieved from the service request is in JSON format and looks like this: { "entries": [{ "id": 2081, "name": "BM", "niceName": "bodmas" }] }, { "id": 8029, "name": "Mas", "niceName" ...

Error: Unable to execute $(...).stellar since it is not a recognized function

Having some trouble implementing the stellar plugin. I've included all the necessary js, but keep getting an error in the dev tools console: 'Uncaught TypeError: $(...).stellar is not a function'. Here's what I have in the head tags: ...

XPathSelectorError: The provided xpath expression is invalid and unable to locate the specified element

Here is an HTML snippet element: <a ng-click="nodes.setViewType('tiles',true)"> <span class="fa fa-check Tick-Inactive" ng-class="nodes.viewType == 'tiles'? 'Tick-Active':'Tick-Inactive'" style="">< ...

Reacts Router Link does not refresh page content

My React and Redux application features a Movie component that displays movie data fetched from an API. To enhance user experience, I decided to create a Similar Movies section at the bottom of the page. This section contains components that allow users t ...

Is there any other factor aside from the lack of a CSRF token in an AJAX request with Django that could lead to a 403 error?

The primary reason behind the django + ajax 403 error is usually the absence of a csrf token. However, in my scenario, the csrf token is present and a similar ajax function is working fine. I will also provide the backend view function that handles the res ...

Exploring the concept of inheritance and nested views within AngularJS

I've encountered a challenge while setting up nested views in AngularJS. Utilizing the ui-router library has been beneficial, but I'm facing issues with separate controllers for each view without proper inheritance between them. This results in h ...

What is the best way to pass the double-clicked row as a parameter to a function, when the row is dynamically created in the code?

I am facing an issue with adding rows to an empty table using a button and attaching a dblclick event listener to each row. The challenge arises when I need to execute a function that requires the specific row being double-clicked. In tables already popu ...

ways to validate the calling function in jquery

One of the challenges I'm facing is identifying which function is calling a specific error function that is used in multiple places within my code. Is there a method or technique to help determine this? ...

Code snippet for fetching JavaScript file using Angular's caching mechanism

Currently in my project, I am utilizing $.getScript to dynamically load specific sections of code. Here's a snippet of how it looks: var mainJs = "/main.js"; $.getScript( mainJs ) .then(function () { console.log("main.js loaded"); }); ...

When continuously looped, the Selenium MoveToElement() action unexpectedly scrolls to the top

Currently, I'm working on a script that navigates through a feed by moving from one post to another using the MoveToElement() method. My code snippet looks like this: Actions action = new Actions(driver); while (true) { List<IWebElement> p ...

Enhance your webpage with dynamic styling using third-party CSS animation

Apologies for any similarity to other questions on this topic. I have searched extensively, but any assistance would be greatly appreciated. I am utilizing a new animation library from Animista to animate specific elements on a test website. Animating ele ...

How can AngularJS service methods be assigned to controller $scope for use in an ng-repeat loop in the view?

As part of my development process, I decided to refactor my controller code in order to make it more reusable across multiple controllers. The original version of the controller (colorController.js) worked perfectly fine before I attempted to refactor it i ...

Reply in Loopback on remote method beforeRemote hook is to be sent

In my application, I am utilizing loopback v3. The specific use case I am tackling involves validating the presence of a token in the request header. If the token is invalid, I need to send an appropriate message in a standardized format. My approach has b ...