How can I find the distance between two sets of coordinates using JavaScript?

My current task involves calculating the distance in kilometers between two sets of latitude and longitude coordinates, with the goal of displaying this distance in a label or paragraph on a webpage.

  • I have an address from which I can determine the lat1 and lon1 values successfully.
  • To find the lat2 and lon2 coordinates for my current location, I am also able to accomplish this step.

Once I have obtained the values for lat1, lon1, lat2, and lon2, my next objective is to calculate the distance between these pairs of coordinates. However, upon executing my code snippet below, the calculated distance is displayed as NaN when alerted. I am uncertain about the issue at hand and would appreciate guidance on correcting it. Moreover, I would like to confirm if my approach is correct for this purpose.

<!DOCTYPE html>
<html>
<style>
body {
  margin: 0;
  padding: 0;
  font: 12px sans-serif;
}
h1, p {
  margin: 0;
  padding: 0;
}
#map_div{
    width:400px;
    height:400px;
    margin: 0 auto;
}
#outer {
    width:400px;
    height:50px;
    margin:0 auto;
    text-align:center;
}
#outer input[type="text"] {
    display: block;
    margin: 0 auto;
}

</style>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3&amp;sensor=false"></script>

<div id="outer">
<p id="distance_text">this is 201 km away from</p>
<input type="text" name="location" value="Current Location"><br>
<div id="map_div"></div>
</div>

...

</html>

The existing placeholder showing "201 km" needs to be replaced with the actual calculated distance value. You can access the code on this jsfiddle link.

Answer №1

To determine distance using Google Maps, you will need to use the Google Maps distance method with LatLng objects.

Here is an example:

const from = new google.maps.LatLng(lat1, lng1);
const to = new google.maps.LatLng(lat2, lng2);
const distance =  google.maps.geometry.spherical.computeDistanceBetween(from,to)

Check out this functional JSfiddle. Remember to include your API key in the map script tag: https://jsfiddle.net/ruokyanv/

If you want to change the distance displayed, you can inject a JavaScript file into your HTML and utilize jQuery $:

var distance = `this is ${distance} km away from`
$('#distance_text').val(distance)

Please inform me if the issue continues.

Answer №2

If you're looking to utilize location mapping functionality, the HERE maps API is a reliable choice.

let routeURL = "https://route.ls.hereapi.com/routing/7.2/calculateroute.json?apiKey="+ apiKey +"&mode=balanced;car&waypoint0=geo!"+startingPoint+"&waypoint1=geo!"+endingPoint;
let xhr = new XMLHttpRequest();
xhr.open( "GET", routeURL, false ); 
xhr.send( null );
let routeData = JSON.parse(xhr.responseText);
let totalDistance = (routeData.response.route[0].summary.distance); 

The variables startingPoint and endingPoint represent the geographic coordinates, specifically latitude and longitude.

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

Why is my "npm install" pulling in unnecessary libraries that I didn't even mention?

I've listed my dependencies in package.json as follows: { "cookie-parser": "~1.0.1", "body-parser": "~1.0.0", "express": "~3.5.0", "socket.io":"1.0", "mongodb":"2.2.21", "request":"2.79.0", "q":"1.4.1", "bcryptjs":"2.4.0", "jsonw ...

What is the method to choose the following CSS element?

There are two div elements in my HTML code: <body> <div id="one"></div> <div></div> </body> I am looking to hide the div elements after the one with id="one" using CSS. I attempted this method: #one:after{display: ...

How can the color of the wishlist icon be modified in Reactjs when the item is available in the database?

Is there a way to change the color of the wishlist icon based on whether the item is in the database? If the item is present, its color should be brown, and if it's not present, the color should be black. Additionally, I want the ability to toggle be ...

transform a nested JavaScript object into a one-dimensional array

There is a JavaScript object in the following format: { "draw": "", "columns": [ { "data": "userid", "name": "", "searchable": true, "search": { "value": "", "regex": false } } ] } I want to tra ...

Unusual behavior observed with AngularJS checkboxes

Our group of friends is collaborating on a new project. This is my second time working with AngularJS, and we're currently utilizing version 1.2.3. Although I have some experience, there are moments when I find AngularJS's behavior perplexing, a ...

When I click the button, it deletes the DOM element and hides it, preventing me from

I'm facing a simple issue that I can't quite wrap my head around. Whenever I input a value into the form and click the button to run the function, the 'loading' element disappears and doesn't reappear. Here is the JavaScript code ...

Update the observability status of one observable using a different observable

Upon running the following code, you'll notice that an xhr request is being sent to the console regardless of whether I am subscribed to the subject or not. I would prefer for these requests not to be made if I am not subscribed. // To start, install ...

The angular2-webpack-starter kicks off with a simple static page

When starting my project using angular2-webpack-starter, the initial loading of index.html allows us to create our own components. However, in my case, I am looking to first direct users to a static page without any Angular code before clicking a button th ...

The div I'm trying to position at the bottom is currently wedged between other divs

My goal is to move the gray rectangle (<div class="brand"> </div>) below the other elements automatically. Currently, it's stuck between the header and two other body divs. Being a beginner, I'm unsure how to fix this. I've tried ...

How to temporarily disable CSS hover effects

I have a menu with some links <ul id="nav"> <li> <a href="#">Project</a> <div class="subs"> <div> <ul> <li> <h3>Save</h3> <ul> <li> <a i ...

React Array Not Behaving Properly When Checkbox Unchecked and Item Removed

When using my React Table, I encountered an issue with checkboxes. Each time I check a box, I aim to add the corresponding Id to an empty array and remove it when unchecked. However, the current implementation is not functioning as expected. On the first c ...

Error encountered in Clash of Clans API when attempting to retrieve information

VM100:1 Uncaught SyntaxError: Unexpected token 'E', "Error: " is not valid JSON at JSON.parse (<anonymous>) at Object.success (ajax.js:15:21) at c (Jquery.js:2:25266) at Object.fireWith [as resolveWith] (Jquery.js: ...

Adjusting the visible options in ngOptions causes a disruption in the selected value of the dropdown menu

I have successfully implemented a feature that allows users to convert temperature values displayed in a drop-down menu to either Celsius or Fahrenheit. For this functionality, I am using a select input with ng-options as shown below: <select ng-model ...

Using jQuery to change date format from mm/dd/yy to yyyy-dd-mm

I need to transform a date in mm/dd/yy format from an ajax response into yyyy-mm-dd format using jquery. Is there a built-in function in jquery that can handle this conversion for me? ...

Retrieve JSON information using AJAX

As I am new to JSON and Ajax, the question I have may seem basic. When I try to display data from my JSON object containing 'name', 'task', 'date', and 'status' using Ajax, it does not show up on my page. Below is m ...

What is the syntax for invoking a function within a nested function in TypeScript?

Is there a way to call the function func2 from within the sample function of function func1? Any suggestions on how to achieve that? class A { public func1() { let sample = function() { //call func2... but ...

What are the best practices for implementing image-slice in node.js?

I attempted to utilize image-slice to divide an image into multiple parts using Node.js. I tried installing npm i image-to-slices, sudo port install cairo, npm i canvas, and brew install pkg-config cairo pango libpng jpeg giflib. However, I still encounte ...

Is there a way to go about installing node_modules?

After running the npm i command to install node_modules in my vue.js project, I encountered the following error message: npm ERR! code E404 npm ERR! 404 Not Found - GET https://registry.npmjs.org/@fds%2flima-ticket-validator - Not found npm ERR ...

Combine angular ui router templates using grunt into a single file

Currently, I am working on an angular-ui-router project that consists of 150 files scattered all over. My goal is to create a grunt task that will merge all these files into a single index.html file structured like this: <script type="text/ng-template" ...

Carrying over additions in arrays using only Javascript

I'd like to implement a basic array addition with carryover. Additionally, I need to display the carryover and result values. For instance: e.g var input = [[0,0,9],[0,9,9]]; var carryover = []; var result = []; Thank you! ...