Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

android - How can I get the distance between two point by latlng?

I want to get the distance from A to B by latlng.When i run my app with the following code,it return a wrong result. Fx i tryed A( 31.172740,115.0081630) ,then B(30.6055980,114.3603140),the result is about 3111km.but the right distance is about 134km. My code is:

    class btnListener implements OnClickListener{

    public void onClick(View v) {
         lat_a=lat_A.getText().toString();
         lng_a=lng_A.getText().toString();
         lat_b=lat_B.getText().toString();
         lng_b=lng_B.getText().toString();
         double a1,n1,a2,n2;
         a1=30.6055980;
         a2=Double.parseDouble(lat_b);
         n2=Double.parseDouble(lng_b);
         double R=6371;
         double D=Math.acos(Math.sin(a1)*Math.sin(a2)+Math.cos(a1)*Math.cos(a2)*Math.cos(n2-n1));
         Toast.makeText(getApplication(), "the distance is"+String.valueOf(D*R)+"km from A to B", Toast.LENGTH_SHORT).show();
    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is an api provided by android itself to get distance between two points. Use:

Location.distanceBetween(
    startLatitude,
    startLongitude,
    endLatitude,
    endLongitude,
    results);

which returns distance in meters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...