我正在检查当前坐标是否在目标坐标的10米半径范围内。我试过实现一个方法,但我不确定它有多可靠。它似乎只检查坐标是否在1公里内,这就是我的想法,但我不确定它是否真的创建了给定数字的半径或其他东西。
punchin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
punchout.setVisibility(View.VISIBLE);
punchin.setVisibility(View.INVISIBLE);
curLocation.setText("");
tarLocation.setText("");
String androidID = getIMEINumber();
if (androidID != null) {
getCurrentLocation();
// Execute the Api's
double targetLatitude = 19.2185561;// Specify the latitude of the target location
double targetLongitude = 72.86228096;// Specify the longitude of the target location
float[] distanceResults = new float[1];
Location.distanceBetween(latitude, longitude, targetLatitude, targetLongitude, distanceResults);
float distanceInKm = distanceResults[0] / 1000;
String currentLocationStr = "Current :-" + latitude + " : " + longitude;
String targetLocationStr = "Target :-" + targetLatitude + " : " + targetLongitude;
if (distanceInKm < 1) {
curLocation.setText(currentLocationStr);
tarLocation.setText(targetLocationStr);
Toast.makeText(requireContext(), "You are under office premises ", Toast.LENGTH_LONG).show();
} else {
curLocation.setText(currentLocationStr);
tarLocation.setText(targetLocationStr);
Toast.makeText(requireContext(), "You are not under office premises ", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getContext(), "No Data", Toast.LENGTH_SHORT).show();
}
}
});
private void getCurrentLocation() {
FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireContext());
if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Request location permissions if not already granted
ActivityCompat.requestPermissions((Activity) requireContext(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
} else {
// Permissions already granted, request current location
fusedLocationClient.getLastLocation()
.addOnSuccessListener(location -> {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
// Use the obtained latitude and longitude values for further processing
// You can compare these values with your desired geolocation
}
})
.addOnFailureListener(e -> {
// Handle any errors that occurred while getting the location
});
}
}
1条答案
按热度按时间66bbxpm51#
Android Documentation for Location#distanceBetween声明如下。
如果查看Location#distanceBetween的源代码,您会发现它使用了一个名为computeDistanceAndBearing的私有方法。
其中,前两行是以下开发人员注解。
//基于http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf
//使用“Inverse Formula”(第4节)
这似乎是一个复杂的公式;我认为它返回的是逻辑结果。
话虽如此,你提到了以下几点。
……“好像只检查坐标是否在1公里以内”……
文件上写着,它就在几米之内。
在索引
0
处检查distanceResults
应该会产生一个以米为单位的数字。另外,Android文档还说明了以下内容。
你的
distanceResults
被分配给new float[1]
。您应该将大小增加到
3
,以容纳这些附加值。