Я не могу правильно определить широту и долготу, он всегда получает одинаковые координаты stati c (штаб-квартира Google) - PullRequest
0 голосов
/ 06 мая 2020

Я пытался включить определение местоположения в свое приложение, но наткнулся на кирпичную стену. Я искал разные методы для его реализации, но пока ничего не работает, и результат всегда один: получайте одну и ту же координату снова и снова с каждой реализацией. Не могли бы вы взглянуть на мой код ниже?

MainActivity. java (его часть)

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //37.8267,-122.4233
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    checkPermission();
    getForcast(latitude,longitude);
    imageView = findViewById(R.id.maps_image_button);
    Log.d(TAG, "Main UI code is running");

}

private void checkPermission() {
    //check permission
    if (ActivityCompat.checkSelfPermission(MainActivity.this,
            Manifest.permission.ACCESS_FINE_LOCATION) ==
                    PackageManager.PERMISSION_GRANTED) {
        //when permission granted
        getLocation();
    }
    else{
        //when permission is not granted
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},PERMISSION_ID);
    }
}

private void getLocation() {
    mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
        @Override
        public void onComplete(@NonNull Task<Location> task) {
            //Initialize location
            Location location = task.getResult();
            if (location != null)
            {

                try {
                    //Initialize GeoCoder
                    Geocoder geocoder = new Geocoder(MainActivity.this,
                            Locale.getDefault());
                    //Initialize address list
                    List <Address> addresses = geocoder.getFromLocation(
                            location.getLatitude(),location.getLongitude(),1);
                    //set latitude and longitude, initialize CurrentUserLocation
                    currentUserLocation = new CurrentUserLocation(addresses.get(0).getLongitude(),
                            addresses.get(0).getLatitude(),
                            addresses.get(0).getLocality());
                    latitude = currentUserLocation.getLatitude();
                    Log.d(TAG, "onComplete: " + addresses.get(0).getLatitude());
                    longitude = currentUserLocation.getLongitude();
                    Log.d(TAG, "onComplete: " + longitude);
                    country = currentUserLocation.getCountry();
                    Log.d(TAG, "onComplete: " + currentUserLocation.getCountry());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });
}

CurrentUserLocation. java

package com.example.stormy.model;

import com.example.stormy.ui.MainActivity;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;

public class CurrentUserLocation {
    double longitude;
    double latitude;
    String country;

    public CurrentUserLocation(double longitude, double latitude, String locality) {
        this.longitude = longitude;
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

    public double getLatitude() {
        return latitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}

Разрешения добавляются в файл манифеста. Зависимости сервисов Google включены в файл gradle. Наконец, позвольте мне предоставить вам результаты журнала:

2020-05-06 21: 42: 27.167 11292-11292 / com.example.stormy D / MainActivity: выполняется основной код пользовательского интерфейса

2020-05-06 21: 42: 27.586 11292-11292 / com.example.stormy D / MainActivity: onComplete: 37.4219982

2020-05-06 21: 42: 27.586 11292-11292 / com.example. бурный D / MainActivity: onComplete: -122.08399980000002

2020-05-06 21: 42: 27.586 11292-11292 / com.example.stormy D / MainActivity: onComplete: null

2020-05 -06 21: 42: 28.151 11292-11469 / com.example.stormy D / MainActivity: Из JSONEtc / GMT

2020-05-06 21: 42: 28.153 11292-11469 / com.example.stormy D / MainActivity: 18:42

Это те же координаты, которые я получаю снова и снова

Он указывает на штаб-квартиру Google, добро пожаловать в проверьте это сами. Может ли кто-нибудь указать мне правильное направление? Что я здесь делаю не так?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...