BÀI 91 - TÍNH KHOẢNG CÁCH TỪ 2 THÀNH PHỐ TRONG ANDROID
Bài này mình sẽ chỉ cách tính khoảng cách từ tên của 2 local.
Nguyên tắc là chúng ta phải tìm ra lat và long của 2 local này. Từ đó sẽ tính khoảng cách dựa vào các lat và long.
Để tìm được lat và long từ tên địa điểm bạn code như này !
@SuppressLint("SetTextI18n")
public void getLocationFromAddress(String strAddress)
{
//Create coder with Activity context - this
Geocoder coder = new Geocoder(this);
List <Address> address;
try {
address = coder.getFromLocationName(strAddress,5);
if (address == null) {
return;
}
//Lets take first possibility from the all possibilities.
Address location = address.get(0);
tvTypeWarranty.setText(distance(location.getLatitude(), location.getLongitude())+"");
} catch (IOException e) {
e.printStackTrace();
}
}
Sau đó chúng ta sẽ tính khoảng cách như sau:
public static double distance(double la2, double lo2) {
double R = 6371;
double la1 = 10.037114;
double lo1 = 105.775997;
double dLat = (la2 - la1) * (Math.PI / 180);
double dLon = (lo2 - lo1) * (Math.PI / 180);
double la1ToRad = la1 * (Math.PI / 180);
double la2ToRad = la2 * (Math.PI / 180);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(la1ToRad)
* Math.cos(la2ToRad) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
Ở ví dụ trên la1 và lo1 là local mà mình gán cố định tại 1 điểm trên bản đồ
Và mình đã tìm la2 và lo2 theo tên của địa phương cần tính khoảng cách.