我使用谷歌api创建一个地图活动,但当我启动我的应用程序时,它显示默认位置不是最新的

时间:2016-07-20 12:31:41

标签: android

我使用google api创建一个地图活动 但是当我启动我的应用程序时,它会显示默认位置,但在启用gps

后当前显示的位置不显示该位置

MapsActivity

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
        com.google.android.gms.location.LocationListener{

    private GoogleMap mMap;
    private GoogleApiClient googleApiClient;
    public static final String TAG = MapsActivity.class.getName();
    private LocationRequest locationRequest;
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // 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);
        initClient();
    }

    private void initClient() {
        googleApiClient = new GoogleApiClient.Builder(this, this, this).addApi(LocationServices.API).build();
        locationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(10 * 1000).setFastestInterval(1 * 1000);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

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

    @Override
    protected void onPause() {
        super.onPause();
        if (googleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
            googleApiClient.disconnect();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


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

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }


    @Override
    public void onConnected(Bundle bundle) {
        Log.i(TAG, "Location service is connected");
        Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

        if (location == null) {
            Log.d(TAG, "No location found,Requesting for location update");
            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;
            }
            LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
        }
        else
        {


            handleLocation(location);
        }
    }


    private void handleLocation(Location location) {
        Log.d(TAG, location.toString());
        double latitude=location.getLatitude();
        double longitude=location.getLongitude();

        LatLng currentLatLng=new LatLng(latitude,longitude);


        MarkerOptions options = new MarkerOptions().position(currentLatLng).title("I am Here.").snippet("Consider U R Located");
        mMap.addMarker(options);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLatLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(16));
    }
    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Google Api Client is Suspended,Please Connect It");

    }



    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (connectionResult.hasResolution()) {
            try {
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        } else {
            Log.i(TAG, "Connection has failed with code" + connectionResult.getErrorCode());
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        handleLocation(location);


    }


}

menifest

 <uses-permission android:name="com.javapapers.currentlocationinmap.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

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

                <!--<category android:name="android.intent.category.LAUNCHER" />-->
            <!--</intent-filter>-->
        </activity>
        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/. 
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>



        </activity>
    </application>

</manifest>

我已经在google_maps_api.xml中添加了api密钥

4 个答案:

答案 0 :(得分:1)

在这里你可以这样做,见http://developer.android.com/reference/android/location/LocationManager.html#PASSIVE_PROVIDER

 LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
myLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
double longitude = myLocation.getLongitude();
double latitude = myLocation.getLatitude();

private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        longitude = location.getLongitude();
        latitude = location.getLatitude();
    }
}

答案 1 :(得分:0)

在onCreate()

中调用此方法
 private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        mMap.setMyLocationEnabled(true);
        // Check if we were successful in obtaining the map.
        if (mMap != null) {


         mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

       @Override
       public void onMyLocationChange(Location arg0) {
        // TODO Auto-generated method stub

         mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
       }
      });

        }
    }
}

请参阅此处https://developers.google.com/maps/documentation/android-api/intro#sample_code

如果上述方法无效,请尝试使用LocationManager。

LocationManager locationManager = LocationManager)getSystemService(Context.LOCATION_SERVICE);

// Creating an empty criteria object
 Criteria criteria = new Criteria(); 
// Getting the name of the provider that meets the criteria 
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
long c = location.getLatitude();
long d = location.getLongitude();

使用onLocationChangedListener中的纬度和经度值!

答案 2 :(得分:0)

这是因为您在此默认悉尼位置添加了标记,请获取当前的latlng并在当前位置添加标记。

&#13;
&#13;
 LatLng sydney = new LatLng(-34, 151);
&#13;
&#13;
&#13;

使用此 LocationService.class 获取您当前的位置

&#13;
&#13;
public class LocationService extends Service {

    private static final int LOCATION_UPDATE_INTERVAL = 2 * 1000;
    private static final int LOCATION_UPDATE_DISTANCE = 5;
    private LocationManager mLocationManager;
    private LocationUpdatesListener mLocationUpdatesListener;
    private Context mContext;
    public static double mLatitude = 0.0;
    public static double mLongitude = 0.0;
    public static boolean socketConnected=false;


    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mLocationUpdatesListener = new LocationUpdatesListener();

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

            if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
                        0, mLocationUpdatesListener);
            }
            if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
                        0, mLocationUpdatesListener);
            }

        }
        mCountDowntimer.start();
        return START_STICKY;
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mLocationManager.removeUpdates(mLocationUpdatesListener);
        }

    }

    public class LocationUpdatesListener implements LocationListener {

        public void onLocationChanged(final Location location) {

            if (null != location) {
           
            mLatitude=location.getLatitude();
                mLongitude=location.getLongitude();
            }

        public void onProviderDisabled(String provider) {
            Toast.makeText(getApplicationContext(), "Gps not working",
                    Toast.LENGTH_SHORT).show();
        }

        public void onProviderEnabled(String provider) {
        }

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

        }
    }


}
&#13;
&#13;
&#13;

而不是在刚开始服务之后添加

&#13;
&#13;
LatLng sydney = new LatLng(LocationService.mLatitude, LocationService.mLongitude);
&#13;
&#13;
&#13;

还将此权限添加到清单

&#13;
&#13;
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
      
&#13;
&#13;
&#13;

和此服务标签

&#13;
&#13;
<service
            android:name=".LocationService"
            android:enabled="true" />
&#13;
&#13;
&#13;

答案 3 :(得分:0)

当您导入任何谷歌地图样本时,您将获得他们自己的位置lat和long。

您需要添加自己的位置lat和long,以便在那里看到标记。

如果您要添加mMap.setMyLocationEnabled(true); 然后你可以在地图屏幕上看到当前位置符号(图标),然后点击你将用蓝色标记移动到当前位置(谷歌默认)。

仅供参考:https://developers.google.com/maps/documentation/android-api/location