Senza fare clic su alcun pulsante, come ottenere direttamente la posizione corrente e spostare la telecamera su di essa.
Inoltre, ho trovato che c'è un pulsante nella parte superiore destra della mappa. Quando si fa clic su di esso, andrà alla posizione corrente. Come ottenere la posizione in cui ritorna quando si fa clic su quel pulsante?Come spostare direttamente la telecamera nella posizione corrente nell'API di Google Maps per Android v2?
risposta
assicuratevi di avere queste autorizzazioni:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
poi fare qualche attività e registrare un LocationListener
package com.example.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class LocationActivity extends SherlockFragmentActivity implements LocationListener {
private GoogleMap map;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); //You can also use LocationManager.GPS_PROVIDER and LocationManager.PASSIVE_PROVIDER
}
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
@Override
public void onProviderEnabled(String provider) { }
@Override
public void onProviderDisabled(String provider) { }
}
map.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
La risposta di cui sopra non è secondo cosa viene indicato da Google per il rilevamento della posizione in Google API v2.
Ho appena seguito il tutorial ufficiale e ho finito con questa classe che sta recuperando la posizione corrente e centrando la mappa su di essa non appena ho capito.
è possibile estendere questa classe per avere LocationReciever per disporre di un aggiornamento periodico della posizione. Ho appena eseguito questo codice a livello di API 7
http://developer.android.com/training/location/retrieve-current.html
Qui si va.
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener{
private SupportMapFragment mapFragment;
private GoogleMap map;
private LocationClient mLocationClient;
/*
* Define a request code to send to Google Play services
* This code is returned in Activity.onActivityResult
*/
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
// Define a DialogFragment that displays the error dialog
public static class ErrorDialogFragment extends DialogFragment {
// Global field to contain the error dialog
private Dialog mDialog;
// Default constructor. Sets the dialog field to null
public ErrorDialogFragment() {
super();
mDialog = null;
}
// Set the dialog to display
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
// Return a Dialog to the DialogFragment.
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mLocationClient = new LocationClient(this, this, this);
mapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
map = mapFragment.getMap();
map.setMyLocationEnabled(true);
}
/*
* Called when the Activity becomes visible.
*/
@Override
protected void onStart() {
super.onStart();
// Connect the client.
if(isGooglePlayServicesAvailable()){
mLocationClient.connect();
}
}
/*
* Called when the Activity is no longer visible.
*/
@Override
protected void onStop() {
// Disconnecting the client invalidates it.
mLocationClient.disconnect();
super.onStop();
}
/*
* Handle results returned to the FragmentActivity
* by Google Play services
*/
@Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
// Decide what to do based on the original request code
switch (requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST:
/*
* If the result code is Activity.RESULT_OK, try
* to connect again
*/
switch (resultCode) {
case Activity.RESULT_OK:
mLocationClient.connect();
break;
}
}
}
private boolean isGooglePlayServicesAvailable() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
// In debug mode, log the status
Log.d("Location Updates", "Google Play services is available.");
return true;
} else {
// Get the error dialog from Google Play services
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(resultCode,
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment for the error dialog
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
errorFragment.setDialog(errorDialog);
errorFragment.show(getSupportFragmentManager(), "Location Updates");
}
return false;
}
}
/*
* Called by Location Services when the request to connect the
* client finishes successfully. At this point, you can
* request the current location or start periodic updates
*/
@Override
public void onConnected(Bundle dataBundle) {
// Display the connection status
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
Location location = mLocationClient.getLastLocation();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17);
map.animateCamera(cameraUpdate);
}
/*
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
@Override
public void onDisconnected() {
// Display the connection status
Toast.makeText(this, "Disconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
/*
* Called by Location Services if the attempt to
* Location Services fails.
*/
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Sorry. Location services not available to you", Toast.LENGTH_LONG).show();
}
}
}
com.google.android.gms.location.LocationClient non può essere risolto dopo l'aggiornamento del servizio di riproduzione di Google anche .. –
la risposta è di 2 anni ora. Se puoi pubblicare la nuova risposta. Questo sarà utile – Javanator
Ho risposto a questa domanda con l'ultimo documento. Per favore controllalo, –
Sto spiegando come ottenere la posizione corrente e spostare direttamente la telecamera nella posizione corrente presumendo di aver implementato map-v2. Per maggiori dettagli, è possibile consultare official doc.
Aggiungi il servizio di localizzazione in Gradle
implementation "com.google.android.gms:play-services-location:11.0.1"
Aggiungere posizione autorizzazione file manifesto
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
assicuratevi di chiedere per RuntimePermission. Sto usando Ask-Permission per quello. È facile da usare.
Ora fare riferimento al codice seguente per ottenere la posizione corrente e visualizzarla su una mappa.
private FusedLocationProviderClient mFusedLocationProviderClient;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFusedLocationProviderClient = LocationServices
.getFusedLocationProviderClient(getActivity());
}
private void getDeviceLocation() {
try {
if (mLocationPermissionGranted) {
Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
if (task.isSuccessful()) {
// Set the map's camera position to the current location of the device.
Location location = task.getResult();
LatLng currentLatLng = new LatLng(location.getLatitude(),
location.getLongitude());
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(currentLatLng,
DEFAULT_ZOOM);
googleMap.moveCamera(update);
}
}
});
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
Quando l'utente ha concesso il permesso luogo di chiamata sopra getDeviceLocation()
metodo
private void updateLocationUI() {
if (googleMap == null) {
return;
}
try {
if (mLocationPermissionGranted) {
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
getDeviceLocation();
} else {
googleMap.setMyLocationEnabled(false);
googleMap.getUiSettings().setMyLocationButtonEnabled(false);
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
- 1. Come ottenere la posizione corrente nell'API di Google Maps V2
- 2. Android Google Maps V2 cambia icona La mia posizione
- 3. come spostare la camma su un marker specifico in google maps v2 in android
- 4. Android Google Maps V2 Posizione utente
- 5. come mostrare la posizione corrente come freccia nell'API Android di Google Maps V2?
- 6. Come ottenere la posizione corrente nell'API Android di Google Maps v2?
- 7. Google Maps V2 - Android - Ottieni il livello di zoom corrente
- 8. Android Google Maps v2 Animazione fotocamera
- 9. Come animare la videocamera in una posizione specificata in Google Maps v2 per Android?
- 10. Come spostare l'API di Google Maps per Android Compass Position
- 11. Come visualizzare la mia posizione sull'API di Google Maps per Android v2
- 12. Google Maps API Android v2 Overlay
- 13. Indicatori di centro API V2 per Android Google maps
- 14. Personalizza Google Maps punto blu per la posizione corrente
- 15. Bitmap di ridisegno su Google Maps v2 per Android
- 16. Google Maps Android V2 - Schermo vuoto
- 17. Spostare i marcatori in google map v2 android
- 18. Come bloccare la fotocamera nell'API di Google Maps API V2
- 19. API Android di Google Maps v2 creando una nuova LocationSource
- 20. Posizionamento di Google maps v2 comandi di zoom in Android
- 21. Come mostrare la mia posizione corrente in Google Maps Android utilizzando il client API google
- 22. Google maps - posizione della telecamera con marcatore in basso
- 23. Sostituzione per ItemizedOverlay in Google Maps V2 per Android?
- 24. Android Google Maps Api V2, ottenendo le coordinate per il centro mappa corrente
- 25. Come modificare la posizione del pulsante La mia posizione in Google Maps utilizzando Android studio
- 26. L'API di Google Maps per Android v2 è gratuita?
- 27. Android Google Maps v2 - Aggiungi oggetto al marker
- 28. Android di Google Maps API v2 percorso di visualizzazione
- 29. Come abilitare "Google Maps Android API v2" nella console degli sviluppatori
- 30. Android Google Maps v2: ascoltatore su clic che non risponde
Thumbs up per removeUpdates(). – Naskov
cos'è questa SherlockFragmentActivity? Non è menzionato nella tua risposta. –
è una vecchia libreria di supporto per eseguire il porting della barra azioni ... è possibile sostituirla con FragmentActivity http://actionbarsherlock.com/ – tmho