使用如何在Google Maps Android API v2中獲取當前位置?
mMap.setMyLocationEnabled(true)
可以設置myLocation層啓用。
但問題是如何獲得myLocation當用戶點擊按鈕? 我想獲取經度和緯度。
使用如何在Google Maps Android API v2中獲取當前位置?
mMap.setMyLocationEnabled(true)
可以設置myLocation層啓用。
但問題是如何獲得myLocation當用戶點擊按鈕? 我想獲取經度和緯度。
的谷歌地圖API的位置,現在的工作,甚至有聽衆,則可以使用,例如做將在地圖第一次找到位置時被調用。
完全不需要LocationService或LocationManager。
OnMyLocationChangeListener
接口已棄用。改爲使用com.google.android.gms.location.FusedLocationProviderApi代替 。 FusedLocationProviderApi提供改進的位置查找和用電量,並由「我的位置」藍點使用。有關示例代碼示例或位置開發人員指南,請參閱示例應用程序文件夾中的MyLocationDemoActivity。
不幸的是不會通知您更新。據說它也壞了。 –
**更新:** https://developers.google.com/maps/documentation/android/location,HTTP 「此方法已 使用com.google.android.gms.location.LocationClient來代替。」:// developer.android.com/google/play-services/location.html – samosaris
嘗試這個
public class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = 「My current location is: 」 +
「Latitud = 」 + loc.getLatitude() +
「Longitud = 」 + loc.getLongitude();
Toast.makeText(getApplicationContext(),Text, Toast.LENGTH_SHORT).show();
tvlat.setText(「」+loc.getLatitude());
tvlong.setText(「」+loc.getLongitude());
this.gpsCurrentLocation();
}
目前GoogleMap.getMyLocation()總是在每一種情況返回null。
目前有兩個谷歌錯誤報告,據我所知,Issue 40932和Issue 4644。
實現前面提到的LocationListener將是不正確的,因爲LocationListener將與您嘗試使用的新API中的LocationOverlay不同步。
接下來由Pramod J George鏈接的Vogella網站教程將爲您提供老Google Maps API的指引。
所以我很抱歉沒有給你一個方法來檢索你的位置的方式。目前,locationListener可能是唯一的手段,但我相信Google正在努力解決新API中的問題。
也抱歉沒有發佈更多的鏈接,StackOverlow認爲我是垃圾郵件,因爲我沒有代表。
---- 2月4日更新,2013 ----
谷歌曾表示,這個問題將通過Issue 4644固定在下次更新的谷歌地圖API。我不確定何時會發生更新,但一旦發生,我將再次編輯此帖子。
---- 4月10日更新,2013 ----
谷歌曾表示該問題已經通過Issue 4644得到修復。它現在應該工作。
試試這個
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, false);
Location location = service.getLastKnownLocation(provider);
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
爲了得到位置,當用戶在按鈕的點擊通話在onClick-
void getCurrentLocation() {
Location myLocation = mMap.getMyLocation();
if(myLocation!=null)
{
double dLatitude = myLocation.getLatitude();
double dLongitude = myLocation.getLongitude();
Log.i("APPLICATION"," : "+dLatitude);
Log.i("APPLICATION"," : "+dLongitude);
mMap.addMarker(new MarkerOptions().position(
new LatLng(dLatitude, dLongitude)).title("My Location").icon(BitmapDescriptorFactory.fromBitmap(Utils.getBitmap("pointer_icon.png"))));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));
}
else
{
Toast.makeText(this, "Unable to fetch the current location", Toast.LENGTH_SHORT).show();
}
}
這種方法也確保了
setMyLocationEnabled
設置爲true。
試試看看它是否可行...
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
if(mMap != null){
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
}
};
,然後設置地圖聽衆:
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
這
Mylocation始終爲空 – Sami
mMap.getMyLocation()已棄用 – sdelvalle57
它會給出當前位置。
mMap.setMyLocationEnabled(true);
Location userLocation = mMap.getMyLocation();
LatLng myLocation = null;
if (userLocation != null) {
myLocation = new LatLng(userLocation.getLatitude(),
userLocation.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation,
mMap.getMaxZoomLevel()-5));
確保您已打開設備上的位置服務。 否則你不會得到任何位置相關的信息。
這對我的作品,
map = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange (Location location) {
LatLng loc = new LatLng (location.getLatitude(), location.getLongitude());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
};
map.setOnMyLocationChangeListener(myLocationChangeListener);
}
我剛剛發現這個代碼片斷簡單而實用, 嘗試:
public class MainActivity extends ActionBarActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
...
@Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}}
這裏的教程鏈接:Getting the Last Known Location
只有一個條件,我測試了我如果你有足夠的時間讓用戶觸摸「獲取我的位置」圖層按鈕,那麼它不會得到空值。
試試這個
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
// Show rationale and request permission.
}
接受的答案工作,但現在一些使用的方法已過時,所以我認爲這是最好的,如果我的回答有更新的方法這個問題。
這個答案是完全從this guide on google developers
所以這裏是一步一步的指導:
在onCreate
實現這一切在你的地圖活動
MapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks
:
private GoogleMap mMap;
private Context context;
private TextView txtStartPoint,txtEndPoint;
private GoogleApiClient mGoogleApiClient;
private Location mLastKnownLocation;
private LatLng mDefaultLocation;
private CameraPosition mCameraPosition;
private boolean mLocationPermissionGranted;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
context = this;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */,
this /* OnConnectionFailedListener */)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
mGoogleApiClient.connect();
}
onConnected
:
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
在onMapReady
:
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Do other setup activities here too, as described elsewhere in this tutorial.
// Turn on the My Location layer and the related control on the map.
updateLocationUI();
// Get the current location of the device and set the position of the map.
getDeviceLocation();
}
而這兩個都是方法onMapReady
:
private void updateLocationUI() {
if (mMap == null) {
return;
}
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
if (mLocationPermissionGranted) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mLastKnownLocation = null;
}
}
private void getDeviceLocation() {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
if (mLocationPermissionGranted) {
mLastKnownLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
}
// Set the map's camera position to the current location of the device.
float DEFAULT_ZOOM = 15;
if (mCameraPosition != null) {
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(mCameraPosition));
} else if (mLastKnownLocation != null) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
} else {
Log.d("pouya", "Current location is null. Using defaults.");
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
這是非常快速,平穩和有效的。希望這有助於
我寧願用FusedLocationApi
因爲OnMyLocationChangeListener
已被棄用。
首先聲明這些3個變量:
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private LocationListener mLocationListener;
定義的方法:
private void initGoogleApiClient(Context context)
{
mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks()
{
@Override
public void onConnected(Bundle bundle)
{
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000);
setLocationListener();
}
@Override
public void onConnectionSuspended(int i)
{
Log.i("LOG_TAG", "onConnectionSuspended");
}
}).build();
if (mGoogleApiClient != null)
mGoogleApiClient.connect();
}
private void setLocationListener()
{
mLocationListener = new LocationListener()
{
@Override
public void onLocationChanged(Location location)
{
String lat = String.valueOf(location.getLatitude());
String lon = String.valueOf(location.getLongitude());
Log.i("LOG_TAG", "Latitude = " + lat + " Longitude = " + lon);
}
};
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener);
}
private void removeLocationListener()
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener);
}
initGoogleApiClient()
用於初始化GoogleApiClient
對象setLocationListener()
用於設置位置改變聽衆removeLocationListener()
是用來刪除偵聽呼叫initGoogleApiClient
方法來啓動代碼工作:)不要忘記在結束時刪除偵聽器(mLocationListener
),以避免內存泄漏問題。
你需要什麼?需要用戶觸摸屏幕時的位置,或當用戶點擊按鈕「獲取我的位置」時需要用戶位置? –