简体   繁体   中英

google maps failure to zoom into current location

I am trying to zoom into my current location on android app. The map still defaults to africa. Doesn't zoom into my current location .

Edit code , afther refering to answer. Still no luck with getting GPS values.

public class MainActivity extends Activity {


    private GoogleMap googleMap;

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

        try {
            // Loading map
            initilizeMap();

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

    }


    private void initilizeMap() {
        if (googleMap == null) {
            googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.map)).getMap();
           googleMap.setMyLocationEnabled(true);
           LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);


           Criteria criteria = new Criteria(); 
           String provider = locationManager.getBestProvider(criteria, true);


           // Getting Current Location
           Location location = locationManager.getLastKnownLocation(provider);

           if(location == null){
               LocationListener locationListener = new LocationListener() {

                @Override
                public void onLocationChanged(Location location) {
                    double lat= location.getLatitude();
                    double lng = location.getLongitude();
                    LatLng ll = new LatLng(lat, lng);
                    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 20));                    
                }
                @Override
                public void onProviderDisabled(String provider) {}
                @Override
                public void onProviderEnabled(String provider) {}
                @Override
                public void onStatusChanged(String provider, int status,
                        Bundle extras) {}
                };
             Log.d("APpln", "well hello there >>"+location);
    locationManager.requestLocationUpdates(provider, 20000, 0, locationListener);

           }else{
               double lat= location.getLatitude();
               double lng = location.getLongitude();

               LatLng ll = new LatLng(lat, lng);

               googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 20));
           }


        // Define a listener that responds to location updates
           LocationListener locationListener = new LocationListener() {
               public void onLocationChanged(Location location) {

                 // Called when a new location is found by the network location provider.
                 makeUseOfNewLocation(location);
               }

               private void makeUseOfNewLocation(Location location) {
                   double lat = location.getLatitude();
            double lng = location.getLongitude();
                LatLng ll = new LatLng(lat, lng);
                Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show();

            }

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

               public void onProviderEnabled(String provider) {}

               public void onProviderDisabled(String provider) {}
             };

             locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);      


            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initilizeMap();
    }

}

Manifext.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pcakage"
    android:versionCode="1"
    android:versionName="1.0" >
<permission
        android:name="info.androidhive.googlemapsv2.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-sdk
        android:minSdkVersion="12"
        android:targetSdkVersion="18" />
 <uses-permission 
     android:name="info.androidhive.googlemapsv2.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <!-- Required to show current location -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
 
    <!-- Required OpenGL ES 2.0. for Maps V2 -->
    <uses-feature android:glEsVersion="0x00020000"/>
    <uses-feature android:required="true"/>

    <!-- Goolge Maps API Key -->


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="package.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
     <meta-data
     android:name="com.google.android.maps.v2.API_KEY"
     android:value="some_value" />
    </application>

</manifest>

I am not sure where I am going wrong. WHen I print values on lat and long , i get no values . Which possibly means the Location location = locationManager.getLastKnownLocation(provider) isn't getting the location. Ihas it got to do with access?

Sometime can happen that you can't get a valid location from locationManager.getLastKnownLocation(provider);

Start a location listener and move the camera when you get a location.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();
       googleMap.setMyLocationEnabled(true);
       LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

       Criteria criteria = new Criteria();

       String provider = locationManager.getBestProvider(criteria, true);

       Location location = locationManager.getLastKnownLocation(provider);

       if(location == null){

         LocationListener locationListener = new LocationListener() {
            void onLocationChanged(Location location) {
            double lat= location.getLatitude();
            double lng = location.getLongitude();
            LatLng ll = new LatLng(lat, lng);
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 20));
         }

         LocationManager.requestLocationUpdates(provider, 20000, 0, locationListener);


       }else{
          double lat= location.getLatitude();
          double lng = location.getLongitude();

          LatLng ll = new LatLng(lat, lng);

          googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 20));
      }

    }
    }

Instead to use the standard best provider try get available better provider by hands (sea link )

Location getCurrentLocation()
{
    // Defining current location by the best providers, that availble at runtime on current device;
    Location location = null;
    @Nonnull String[] providers = new String[3];
    providers[0] = LocationManager.GPS_PROVIDER;
    providers[1] = LocationManager.NETWORK_PROVIDER;
    providers[2] = LocationManager.PASSIVE_PROVIDER;

    for (@Nonnull String provider : providers)
    {
        if (!mLocationManager.isProviderEnabled(provider)) continue;
     //            mLocationManager.requestLocationUpdates(provider, MIN_TIME_BW_UPDATES, MIN_DISTANCE_UPDATES, this);
        if (mLocationManager != null)
        {
            location = mLocationManager.getLastKnownLocation(provider);
            if (location != null)
            {
                break;
            }
        }
    }
    return location;
}

and focused on map

private void focusMapOnCurrentLocation()
{
    final int DURATIONMS_CONST = 2000;
    final int ZOOM_ANIM_CAMERA_CONST = 15;
    final int ZOOM_MOVE_CAMERA_CONST = 20;

    // Set focus on current location on google map;

    Location location = getCurrentLocation();
    double lat = location.getLatitude();
    double log = location.getLongitude();
    @Nonnull LatLng latLng = new LatLng(lat, log);
    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, ZOOM_MOVE_CAMERA_CONST));
    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(ZOOM_ANIM_CAMERA_CONST), DURATIONMS_CONST, null);
}

The same you can use mGoogleMap.setMyLocationEnabled(true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM