Я разрабатываю приложение с помощью Android Studio в Java. У меня проблема. Я работаю с Google Map. Я создал круг, но я не знаю, как я могу определить, находится ли местоположение человека в круге. Я нашел что-то, чтобы проверить это, но это не работает, мое приложение мгновенно создает sh. Спасибо за вашу помощь.
Код, который я нашел:
float[] distance = new float[2];
Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), circle.getCenter().latitude,circle.getCenter().longitude,distance);
if ( distance[0] <= circle.getRadius())
{
// Inside The Circle
}
else
{
// Outside The Circle
}
И это весь мой код (без строк импорта):
public class MainActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
Location currentLocation;
FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101;
private Handler mHandler = new Handler();
private TextView mTextViewResult;
private GoogleMap mMap;
private Marker markertest;
double lat;
double longi;
boolean zoom;
float[] distance = new float[2];
Circle circle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
zoom = true;
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
mTextViewResult = findViewById(R.id.text_view_result);
//openActivite();
fetchLastLocation();
Check();
runnabletest.run();
}
public void Check(){
currentLocation.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), circle.getCenter().latitude,circle.getCenter().longitude,distance);
if ( distance[0] <= circle.getRadius())
{
System.exit(0);
}
else
{
// Outside The Circle
}
}
private Runnable runnabletest = new Runnable(){
@Override
public void run() {
fetchLastLocation();
mHandler.postDelayed(runnabletest, 10000);
}
};
private void fetchLastLocation(){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
return;
}
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if(location != null){
currentLocation = location;
Toast.makeText(getApplicationContext(), currentLocation.getLatitude()
+""+currentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.google_map);
supportMapFragment.getMapAsync(MainActivity.this);
lat = currentLocation.getLatitude();
longi = currentLocation.getLongitude();
}
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(lat, longi);
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("Vous");
googleMap.addMarker(markerOptions);
LatLng latLng2 = new LatLng(48.8534, 2.3488);
MarkerOptions markerOptions2 = new MarkerOptions().position(latLng2).title("Point d'arrivée").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
googleMap.addMarker(markerOptions2);
circle = googleMap.addCircle(new CircleOptions().center(latLng2).radius(500.0).strokeWidth(3f).strokeColor(Color.BLUE).fillColor(Color.argb(70, 150, 50, 50)));
if(zoom == true){
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 5));
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng2));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng2, 5));
}
zoom = false;
}
@Override
public void onLocationChanged(Location currentLocation){
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch(requestCode){
case REQUEST_CODE:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
fetchLastLocation();;
}
break;
}
}
}
И ошибки в логах:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.okiep, PID: 21205
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.okiep/com.example.okiep.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.example.okiep.MainActivity.Check(MainActivity.java:81)
at com.example.okiep.MainActivity.onCreate(MainActivity.java:76)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)