Calculate the distance between two points based on the latitude and longitude coordinates of two points [Java]

Source: Internet
Author: User

Reprinted from http://www.189works.com/article-16712-1.html

The key to solving this problem is to understand the space ry model, and then use the mathematical formula to obtain the value between two points. The solution is as follows:

1. Set the two points to P1 and P2 respectively. If the value is expressed in the form of minute-to-second, convert the value to the decimal level. For example, if the latitude of the P1 point is 23 degrees 30 minutes, then its latitude value is converted to decimal degrees in the form of 23.5 degrees. If the value is in decimal format, go to step 2.

2. Convert the longitude and latitude values of two points into radians. For example, if the latitude of P1 is 23.5 degrees, the latitude value is 23.5 * PI/180. Use p1latinrad, p1longinrad, p2latinrad, and p2longinrad.

3. Obtain the latitude difference (dlat) and longitude difference (dlon) between two points respectively );

4. Calculate the sine and Cosine between two points. The formula is as follows:

A = sin2 (dlat/2) + cos (p1latinrad) * Cos (p2latinrad) * sin2 (dlon/2) (1)

5. Calculate the tangent of two points. The formula is as follows:

C = 2 * Math. atan2 (math. SQRT (A), math. SQRT (1-A) (2)

6. Return the distance between two points. The formula is as follows:

D = earthradiuskm * C (3)

Public class distcnvter {

Private Final Static double Pi = 3.14159265358979323; // circumference Rate

Private Final Static double r = 6371229; // the radius of the earth

Public static double getdistance (double longt1, double LAT1, double longt2, double LAT2 ){

Double X, Y, distance;

X = (longt2-longt1) * pI * R

* Math. Cos (LAT1 + LAT2)/2) * PI/180)/180;

Y = (LAT2-LAT1) * pI * r/180;

Distance = math. hypot (x, y );

Return distance;

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.