不點擊任何按鈕,如何直接獲取當前位置並將相機移動到該位置。
此外,我發現地圖右上方有一個按鈕。點擊它時,它會轉到當前位置。如何獲取點擊該按鈕時返回的位置?如何直接將相機移至Google Maps Android API v2中的當前位置?
回答
請確保您擁有這些權限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
然後做一些活動和註冊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"/>
以上回答沒有根據Google Doc推薦Google API a v2中的位置跟蹤功能。
我只是跟着官方的教程,並結束了與這個類是獲取當前位置,並儘快圍繞它的地圖,因爲我明白了。
你可以擴展這個類有LocationReciever有周期性位置更新。 我只是在執行API級驗證碼7
http://developer.android.com/training/location/retrieve-current.html
在這裏不言而喻。
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無法解析後更新谷歌播放服務.. –
現在的答案是2歲。如果你可以發佈新的答案。這將有所幫助 – Javanator
我已經用最新的文檔回答了這個問題。請檢查一下, –
我解釋瞭如何獲取當前位置,並假設您已經實現了map-v2,直接移動到相機到當前位置。欲瞭解更多詳情,您可以參考official doc。
添加位置服務的Gradle中
implementation "com.google.android.gms:play-services-location:11.0.1"
添加位置的權限清單文件
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
確保你問的RuntimePermission。我正在使用Ask-Permission。它易於使用。
現在參考下面的代碼來獲取當前位置,並在地圖上顯示出來。
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());
}
}
當用戶授予上述getDeviceLocation()
方法
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. Google Maps Android API v2和當前位置
- 2. Android Google Maps Api v2當前位置Null
- 3. 如何在Google Maps Android API v2中獲取當前位置?
- 4. 如何在android google maps api V2中獲取當前位置?
- 5. 如何在Google Maps Android API V2中將當前位置顯示爲箭頭
- 6. Android獲取當前位置作爲Google Maps Android API的起點V2
- 7. 使用Google Maps API v2獲取當前位置爲TEXT
- 8. 如何在Android中使用Google Maps Api獲取手機的當前位置?
- 9. Android Google Maps API V2:如何更改我的位置圖標?
- 10. 如何創建當前位置的鏈接(google map v2,android)
- 11. Android Maps API v2:放大當前位置和標記
- 12. Google Maps API JavaScript當前位置
- 13. Android Google Maps Api V2,獲取當前地圖中心的座標
- 14. 如何在Google Maps API V2中鎖定相機
- 15. Android Studio Google Maps API v2
- 16. 使用Google Maps Android API v2
- 17. 如何將Google Maps Android API v2標記鏈接到對象
- 18. Google maps api v2如何找到最近的位置
- 19. 在Android Google Maps API v2中標記用戶位置
- 20. 繪製2個位置之間的路線Google Maps API Android V2
- 21. 如何從Android Google Maps API V2獲取MapView的位圖
- 22. Google Maps API v2 vs Google Maps API v3?
- 23. Google Maps API v2上的隨機NullPointerException
- 24. Android:Google Maps API v1至v2
- 25. GOOGLE MAPS V2 - 獲取當前用戶位置
- 26. Google Maps API v2中的setBounds如何?
- 27. 如何使用Android中的MarkerOptions顯示/繪製位置Google Maps API v2
- 28. 如何在Google Maps v2中順利地保持移動當前位置標記android
- 29. Android google maps v2 error
- 30. 如何移動Android Google Maps API指南針位置
大拇指爲removeUpdates位置的權限()調用。 – Naskov
這是什麼SherlockFragmentActivity?它在你的答案中沒有提到。 –
它是一箇舊的支持庫來支持操作欄...你可以用FragmentActivity替換它 http://actionbarsherlock.com/ – tmho