简体   繁体   English

如何获取Google Maps Android API v2中的当前位置?

[英]How to get the current location in Google Maps Android API v2?

Using 运用

mMap.setMyLocationEnabled(true)

can set the myLocation layer enable. 可以设置myLocation层启用。
But the problem is how to get the myLocation when the user clicks on the button? 但问题是当用户点击按钮时如何获取myLocation? I want to get the longitude and latitude. 我想得到经度和纬度。

The Google Maps API location now works, even has listeners, you can do it using that, for example: Google Maps API位置现在可以使用,即使有听众也可以使用它,例如:

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

and then set the listener for the map: 然后为地图设置监听器:

mMap.setOnMyLocationChangeListener(myLocationChangeListener);

This will get called when the map first finds the location. 当地图首次找到该位置时,将调用此方法。

No need for LocationService or LocationManager at all. 根本不需要LocationService或LocationManager。

OnMyLocationChangeListener interface is deprecated. 不推荐使用OnMyLocationChangeListener接口。 use com.google.android.gms.location.FusedLocationProviderApi instead. 请改用com.google.android.gms.location.FusedLocationProviderApi。 FusedLocationProviderApi provides improved location finding and power usage and is used by the "My Location" blue dot. FusedLocationProviderApi提供改进的定位和功率使用,并由“我的位置”蓝点使用。 See the MyLocationDemoActivity in the sample applications folder for example example code, or the Location Developer Guide. 有关示例代码示例或位置开发人员指南,请参阅示例应用程序文件夹中的MyLocationDemoActivity。

At the moment GoogleMap.getMyLocation() always returns null under every circumstance. 目前,GoogleMap.getMyLocation()始终在每种情况下都返回null。

There are currently two bug reports towards Google, that I know of, Issue 40932 and Issue 4644 . 目前有两个针对Google的错误报告,我知道, 问题40932问题4644

Implementing a LocationListener as brought up earlier would be incorrect because the LocationListener would be out of sync with the LocationOverlay within the new API that you are trying to use. 实现之前提到的LocationListener是不正确的,因为LocationListener将与您尝试使用的新API中的LocationOverlay不同步。

Following the tutorial on Vogella's Site, linked earlier by Pramod J George, would give you directions for the Older Google Maps API. 按照早期由Pramod J George链接的Vogella网站教程,将为您提供旧版Google Maps API的说明。

So I apologize for not giving you a method to retrieve your location by that means. 所以我很抱歉没有给你一个通过这种方式检索你的位置的方法。 For now the locationListener may be the only means to do it, but I'm sure Google is working on fixing the issue within the new API. 目前,locationListener可能是唯一的方法,但我确信谷歌正在努力解决新API中的问题。

Also sorry for not posting more links, StackOverlow thinks I'm spam because I have no rep. 也很抱歉没有发布更多链接,StackOverlow认为我是垃圾邮件,因为我没有代表。

---- Update on February 4th, 2013 ---- ---- 2013年2月4日更新----

Google has stated that the issue will be fixed in the next update to the Google Maps API via Issue 4644 . Google已声明该问题将通过问题4644在Google Maps API的下一次更新中修复。 I am not sure when the update will occur, but once it does I will edit this post again. 我不确定何时会发生更新,但一旦完成,我将再次编辑此帖子。

---- Update on April 10th, 2013 ---- ---- 2013年4月10日更新----

Google has stated the issue has been fixed via Issue 4644 . 谷歌已经表示该问题已通过问题4644修复。 It should work now. 它现在应该工作。

try this 试试这个

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

Ensure that you have turned ON the location services on the device. 确保已打开设备上的位置服务。 Else you won't get any location related info. 否则,您将无法获得任何位置相关信息。

This works for me, 这对我有用,

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

} }

To get the location when the user clicks on a button call this method in the onClick- 要在用户点击按钮时获取位置,请在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();
    }

}

Also make sure that the 还要确保

setMyLocationEnabled setMyLocationEnabled

is set to true . 设置为true

Try and see if this works... 试试看看这是否有效......

你试过GoogleMap.getMyLocation()吗?

I just found this code snippet simple and functional, try : 我刚刚发现这段代码片段简单实用,请尝试:

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

here's the link of the tutorial : Getting the Last Known Location 这是教程的链接: 获取最后一个已知位置

try this 试试这个

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
    mMap.setMyLocationEnabled(true);
} else {
    // Show rationale and request permission.
}

Try This 试试这个

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

}

It will give the current location. 它将给出当前位置。

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

只有一个条件,我测试它不是null,如果你有足够的时间用户触摸“获取我的位置”图层按钮,那么它将不会获得null值。

the accepted answer works but some of the used methods are now deprecated so I think it is best if I answer this question with updated methods. 接受的答案有效,但现在已经弃用了一些使用过的方法,所以我认为最好用更新的方法回答这个问题。

this is answer is completely from this guide on google developers 这个答案完全来自谷歌开发者的这个指南

so here is step by step guide: 所以这里是一步一步的指南:

  1. implement all this in your map activity 在地图活动中实现所有这些

    MapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks

  2. in your onCreate : 在你的onCreate

     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(); } 
  3. in your onConnected : 在您的onConnected

     SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(map); mapFragment.getMapAsync(this); 
  4. in your onMapReady : 在你的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(); } 
  5. and these two are methods in onMapReady : 这两个是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); } } 

this is very fast , smooth and effective. 这是非常快速,顺畅和有效的。 hope this helps 希望这可以帮助

I would rather use FusedLocationApi since OnMyLocationChangeListener is deprecated. 我宁愿用FusedLocationApi因为OnMyLocationChangeListener已被弃用。

First declare these 3 variables: 首先声明这3个变量:

private LocationRequest  mLocationRequest;
private GoogleApiClient  mGoogleApiClient;
private LocationListener mLocationListener;

Define methods: 定义方法:

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() is used to initialize GoogleApiClient object initGoogleApiClient()用于初始化GoogleApiClient对象
  • setLocationListener() is used to setup location change listener setLocationListener()用于设置位置更改侦听器
  • removeLocationListener() is used to remove the listener removeLocationListener()用于删除侦听器

Call initGoogleApiClient method to start the code working :) Don't forget to remove the listener ( mLocationListener ) at the end to avoid memory leak issues. 调用initGoogleApiClient方法启动代码工作:)不要忘记在最后删除监听器( mLocationListener )以避免内存泄漏问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM