Skip to content
Advertisement

calculate distance between two coordinates in javascript?

I am trying to calculate distance between two lats and longs in KM and show that distance in label or paragraph.

  • I have an address from which I need to figure out lat1 and lon1. I am able to figure this out.
  • I need to find lat2 and lon2 of my current location. I am able to figure this out as well.

Now once I have lat1, lon1, lat2 and lon2 – I need to find distance between these coordinates. Below is my code but it is giving distance as NaN once I alert it. I am not sure what’s wrong here. Also is this the right way I am doing here?

JavaScript

I need to replace 201 km with actual distance after calculating it. Here is my jsfiddle

Advertisement

Answer

You can use google maps distance method but it require LatLng objects

Try this:

JavaScript

This is the working JSfiddle You may have to add API key in map script tag: https://jsfiddle.net/ruokyanv/

change p tag distance: yes you can inject js file in your html and use jquery $:

JavaScript

Let me know if the issue still persists.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement