0

Я могу получить текущее местоположение вручную, но я хочу получить его программно в приложении Android. Я использую LocationListener и LocationManager, но я не получаю текущее местоположение на карте. Мой код приведен ниже, любой может мне помочь, как я могу это сделать?Показать текущее местоположение на карте google программно андроид

package com.example.nabia.myapplication; 

import android.content.Context; 
import android.content.pm.PackageManager; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.support.v4.app.ActivityCompat; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 

import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.MapView; 
import com.google.android.gms.maps.MapsInitializer; 
import com.google.android.gms.maps.OnMapReadyCallback; 
import com.google.android.gms.maps.model.LatLng; 

public class FindNearbyMosque extends AppCompatActivity implements LocationListener, OnMapReadyCallback { 
    MapView gMapView; 
    GoogleMap gMap = null; 
    double latitude; 
    double longitude; 


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

     LocationManager myManager; 
     myManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); 
     if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      // TODO: Consider calling 
      // ActivityCompat#requestPermissions 
      // here to request the missing permissions, and then overriding 
      // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
      //           int[] grantResults) 
      // to handle the case where the user grants the permission. See the documentation 
      // for ActivityCompat#requestPermissions for more details. 
      return; 
     } 
     myManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); 


     gMapView = (MapView)findViewById(R.id.map); 
     gMapView.getMapAsync(this); 
     gMapView.onCreate(savedInstanceState); 
     gMapView.onResume(); // needed to get the map to display immediately 
     try { 
      MapsInitializer.initialize(this.getApplicationContext()); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    @Override 
    public void onMapReady(GoogleMap map) { 

     gMap = map; 
     gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 

    } 

    @Override 
    public void onLocationChanged(Location location) { 

     latitude = location.getLatitude(); 
     longitude = location.getLongitude(); 
     gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude) , 14.0f)); 
    } 

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

    } 

    @Override 
    public void onProviderEnabled(String provider) { 

    } 

    @Override 
    public void onProviderDisabled(String provider) { 

    } 
} 

ответ

1

я решил мою проблему, подключив LocationServices через GoogleApiClient(), как вы можете видеть ниже кода.

public class FindNearbyMosque extends FragmentActivity implements OnMapReadyCallback, 
     GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener { 
    private static final int GPS_ERRORDIALOG_REQUEST = 9001; 

    GoogleApiClient mGoogleApiClient; 
    Location mLastLocation; 
    GoogleMap mMap; 
    double lat; 
    double lng; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     if (servicesOK()) { 
      setContentView(R.layout.activity_map); 

      if (initMap()) { 
       Toast.makeText(this, "Ready to map!", Toast.LENGTH_SHORT).show(); 
      } else { 
       Toast.makeText(this, "Map not available!", Toast.LENGTH_SHORT).show(); 
      } 
     } else { 
      setContentView(R.layout.activity_find_nearby_mosque); 
     } 
    } 

    private boolean servicesOK() { 
     GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance(); 
     int isAvailable = googleAPI.isGooglePlayServicesAvailable(this); 
     if (isAvailable == ConnectionResult.SUCCESS) { 
      return true; 
     } else if (googleAPI.isUserResolvableError(isAvailable)) { 
      Dialog dialog = googleAPI.getErrorDialog(this, isAvailable, GPS_ERRORDIALOG_REQUEST); 
      dialog.show(); 
     } else { 
      Toast.makeText(this, "Can't connect to google play services", Toast.LENGTH_SHORT).show(); 
     } 
     return false; 
    } 

    private boolean initMap() { 

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

     return (true); 
    } 

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

    protected synchronized void buildGoogleApiClient() { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
     mGoogleApiClient.connect(); 
    } 

    @Override 
    public void onConnected(@Nullable Bundle bundle) { 

     if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      // TODO: Consider calling 
      // ActivityCompat#requestPermissions 
      // here to request the missing permissions, and then overriding 
      // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
      //           int[] grantResults) 
      // to handle the case where the user grants the permission. See the documentation 
      // for ActivityCompat#requestPermissions for more details. 
      return; 
     } 
     mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
       mGoogleApiClient); 
     if (mLastLocation != null) { 
      lat = mLastLocation.getLatitude(); 
      lng = mLastLocation.getLongitude(); 

      LatLng loc = new LatLng(lat, lng); 

      CameraUpdate center= 
        CameraUpdateFactory.newLatLng(loc); 
      CameraUpdate zoom=CameraUpdateFactory.newLatLngZoom(loc,14); 
      mMap.moveCamera(center); 
      mMap.animateCamera(zoom); 
      mMap.addMarker(new MarkerOptions().position(loc).title("New Marker")); 
     } 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

    } 
} 
Смежные вопросы