Отображать текущее местоположение с помощью Google Maps API - PullRequest
0 голосов
/ 25 декабря 2018

Я пытаюсь отобразить свое текущее местоположение на Картах Google с помощью API Карт Google в Android Studio.Код ниже помещает маркер в неправильном месте (где-то в Атлантическом океане).Что я делаю не так и как я могу решить эту проблему?PS Я запускал код на виртуальных устройствах Pixel 2 и Nexus 5 API 28

Заранее спасибо.

public class MapsActivity extends FragmentActivity implements 
OnMapReadyCallback {

private GoogleMap mMap;
private double userLat, userLong;
private Location lastKnownLocation;
private LatLng userLocation;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    String locationProvider = LocationManager.GPS_PROVIDER;

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
    }
    lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
    userLat = lastKnownLocation.getLatitude();
    userLong = lastKnownLocation.getLongitude();

}


@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    userLocation = new LatLng (userLat, userLong);
    mMap.addMarker(new MarkerOptions().position(userLocation).title("My Location"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));

  }
}

1 Ответ

0 голосов
/ 28 декабря 2018

Попробуйте мой код, он работает на меня очень хорошо

    public class mapTracking extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    boolean isGpsEnable = false;
    boolean isNetworkEnable = false;
    Location location;
    LocationManager locationManager;
    Context mcontext;
    DatabaseHelper db = new DatabaseHelper(this);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_tracking);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(),
                android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);

        }


        mcontext = this;


        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        isGpsEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnable = locationManager.isProviderEnabled(NETWORK_PROVIDER);

        if (isGpsEnable) {
            if (location == null) {
                if (ActivityCompat.checkSelfPermission(mapTracking.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5, myLocationListener);
                if (locationManager != null) {
                    locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                }
            }

        }

        if (isNetworkEnable) {
            if (location == null) {
                locationManager.requestLocationUpdates(NETWORK_PROVIDER, 1000, 5, myLocationListener);
                if (locationManager != null) {
                    locationManager.getLastKnownLocation(NETWORK_PROVIDER);
                }
            }

        }
        if (location != null) {
            locationManager.requestLocationUpdates(NETWORK_PROVIDER, 1000, 5, myLocationListener);
            if (locationManager != null) {
                locationManager.getLastKnownLocation(NETWORK_PROVIDER);
            }

        }


    }



    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        try {
            db.getWritableDatabase();
            List<MyLocation>myLocationList = db.getAllMark();

            if (myLocationList.size() == 0) {
                Toast.makeText(this, "No Data Found", Toast.LENGTH_SHORT).show();
            }

            for (MyLocation l : myLocationList) {
                LatLng latlng = new LatLng(l.getLatitude(), l.getLongitude());

                mMap.addMarker(new MarkerOptions().position(latlng).snippet("Coordinates: " + l.getLatitude() + " " + l.getLongitude()));
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 16.2f));


            }
            db.close();
        } catch (NumberFormatException e){
            e.printStackTrace();
            Toast.makeText(this, "No data Found" , Toast.LENGTH_SHORT).show();
        }

    }

    final LocationListener myLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(final Location location) {

            final double lat = location.getLatitude();
            final double lon = location.getLongitude();
            db.insertMyLocation(lat,lon);
            System.out.println("LOCATIONNNN::::::::::::::::::::::::::" + lat + "," + lon + "\n" + location.getProvider());
            System.out.println(":::::::::::::::::::::::::::::::::::::::::::::::::"+db.getlocation().getCount());
            final LatLng latLng = new LatLng(lat, lon);
            Toast.makeText(mcontext, "" + latLng + "\n" + location.getProvider(), Toast.LENGTH_SHORT).show();
            mMap.addMarker(new MarkerOptions().position(latLng).snippet("Coordinates: " + lat + " " + lon));
            // mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16.2f));
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 20.2f));
            mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                @Override
                public boolean onMarkerClick(Marker marker) {
//                    Toast.makeText(mapTracking.this, ""+latLng, Toast.LENGTH_SHORT).show();
                    LatLng loc = marker.getPosition();
                    double lat1 = loc.latitude;
                    double lng1 = loc.longitude;
                    Geocoder geocoder = new Geocoder(mapTracking.this, Locale.getDefault());
                    try {
                        List<Address> addresses = geocoder.getFromLocation(lat1,lng1,1);
                        Address address = addresses.get(0);
                        System.out.println(":::::::::::::::::123" + address);
                        Toast.makeText(mapTracking.this, "Address:" + address.getAddressLine(0), Toast.LENGTH_LONG).show();

                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    return false;
                }
            });

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

}
...