谷歌地图无法放大到当前位置

时间:2013-10-24 04:14:07

标签: android google-maps

我想在Android应用上放大我当前的位置。地图仍然默认为非洲。不会放大我当前的位置。

编辑代码,请参阅答案。获得GPS值仍然没有运气。

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>

我不确定我哪里出错了。当我在lat和long上打印值时,我没有得到任何值。这可能意味着Location location = locationManager.getLastKnownLocation(provider)没有获得该位置。我是否与访问有关?

2 个答案:

答案 0 :(得分:3)

有时您可能无法从locationManager.getLastKnownLocation(provider);

获取有效位置

启动位置监听器并在到达位置时移动摄像机。

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));
      }

    }
    }

答案 1 :(得分:1)

相反,要使用标准的最佳提供商,请尝试手动获取更好的提供者(海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;
}

专注于地图

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);
}

同样可以使用mGoogleMap.setMyLocationEnabled(true);