简体   繁体   English

Android Google Maps API位置

[英]Android Google Maps API Location

I've googled around a bit, and still can't find a definite answer to this. 我已经在Google上搜索了一下,但仍然找不到确切的答案。

What is the current "best" or "recommended" way of using Google Maps in Android? 目前在Android中使用Google Maps的“最佳”或“推荐”方式是什么?

I want my application to use the blue dot that automatically keeps track of the user's location, much like the Maps app does when you click on the "my location" button. 我希望我的应用程序使用自动跟踪用户位置的蓝点,就像单击“我的位置”按钮时的“地图”应用程序一样。 Some of this functionality seems to come built in just by using the map, however, I'm unsure how to extract the Location from this, as I've read .getMyLocation() is deprecated? 其中一些功能似乎只是通过使用地图内置的,但是,我不确定如何从中提取位置,因为我已经阅读过.getMyLocation()?

What is the best way to do this? 做这个的最好方式是什么?

I am using this code: 我正在使用此代码:

//get locationManager object from System Service LOCATION_SERVICE
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);


            Criteria criteria = new Criteria();

            String provider = locationManager.getBestProvider(criteria, true);

            Location myLocation = locationManager.getLastKnownLocation(provider);

            map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

            double latitude = myLocation.getLatitude();
            double longitude = myLocation.getLongitude();

            LatLng latLng = new LatLng(latitude, longitude);


            map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10));

You can show the user's current location with the blue dot by enabling the My Location layer. 通过启用“我的位置”图层,可以用蓝点显示用户的当前位置。 Simply call the following method and the blue dot showing the user's current location will be displayed on the map: 只需调用以下方法,就会在地图上显示显示用户当前位置的蓝点:

mMap.setMyLocationEnabled(true);

To get location updates you should setup a LocationListener using a LocationClient . 为了让您应该设置一个位置更新LocationListener使用LocationClient When you implement the LocationListener interface you will override the onLocationChanged method which will provide you with location updates. 在实现LocationListener接口时,您将覆盖onLocationChanged方法,该方法将为您提供位置更新。 When you request location updates using a LocationClient you create a LocationRequest to specify how frequently you want location updates. 当您使用LocationClient请求位置更新时,您将创建一个LocationRequest以指定您希望位置更新的频率。

There is an excellent tutorial at the Android Developers site for making you app location aware. Android Developers网站上有一个出色的教程,可让您了解应用的位置。

You have to work with Location Listener. 您必须使用位置监听器。 It will solve all you want. 它将解决您想要的所有问题。 Use this code. 使用此代码。 I tried to explain all things in comments. 我试图用评论解释所有事情。

import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
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.CameraPosition;
import com.google.android.gms.maps.model.LatLng;

public class YourActivity extends FragmentActivity implements 
LocationListener, ConnectionCallbacks, OnConnectionFailedListener{

    private GoogleMap mMap;
    private LocationClient mLocationClient;
    private static final LocationRequest REQUEST = LocationRequest.create()
            .setInterval(1000)         // 1 second - interval between requests
            .setFastestInterval(16)    // 60fps
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_map);

    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        setUpLocationClientIfNeeded();
        //.. and connect to client
        mLocationClient.connect();

    }

    @Override
    public void onPause() {
        super.onPause();
        // if you was connected to client you have to disconnect
        if (mLocationClient != null) {
            mLocationClient.disconnect();
        }
    }

    private void setUpMapIfNeeded() {
        // if map did not install yet
        if (mMap == null) {
            // install it from fragment
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // if installation success
            if (mMap != null) {
                // init all settings of map
                init();
            }
        }
    }

    //if client was not created - create it
    private void setUpLocationClientIfNeeded() {
        if (mLocationClient == null) {
            mLocationClient = new LocationClient(
                    getApplicationContext(),
                    this, 
                    this);
        }
    }

    private void init() {
        // settings of your map
        mMap.setBuildingsEnabled(true);
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setCompassEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);

    }

    // when you get your current location - set it on center of screen
    @Override
    public void onLocationChanged(Location location) {

        CameraPosition cameraPosition = new CameraPosition.Builder()
        .target(new LatLng(location.getLatitude(), location.getLongitude())).zoom(9).bearing(0).tilt(0).build();
        CameraUpdate cameraUpdate = CameraUpdateFactory
        .newCameraPosition(cameraPosition);
        mMap.animateCamera(cameraUpdate);

        //Be careful, if want to show current location only once(after starting map) use this line
        //but you don't need it in your task!
        mLocationClient.removeLocationUpdates(this);
    }

    // after connection to client we will get new location from LocationListener 
    //with settings of LocationRequest
    @Override
    public void onConnected(Bundle arg0) {
        mLocationClient.requestLocationUpdates(
                REQUEST, //settings for this request described in "LocationRequest REQUEST" at the beginning
                this);
    }

    @Override
    public void onDisconnected() {

    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {

    }
}

I was looking for it last 2 days. 我最近两天一直在寻找它。
Answering your question: 回答您的问题:

What is the current "best" or "recommended" way of using Google Maps in Android? 目前在Android中使用Google Maps的“最佳”或“推荐”方式是什么?

Today you have 2 options: 今天,您有2个选择:

  1. Use new/latest Location Service API (like google recommend). 使用新的/最新的位置服务API(例如Google推荐)。 But there is a "little" problem: The official guide Location APIs is outdate. 但是存在一个“小”问题:官方指南Location API已过时。 I mean, if you follow their tutorial Making Your App Location-Aware you will find that they are using LocationClient which is deprecated. 我的意思是,如果您遵循他们的教程“ 使您的应用程序具有位置感知能力”,您会发现他们正在使用不建议使用的LocationClient After 2 days looking for the "new" way to do it I found this nice answer Android LocationClient class is deprecated but used in documentation . 寻找“新”方法2天后,我发现这个不错的答案Android LocationClient类已被弃用,但已在文档中使用

  2. Use LocationManager . 使用LocationManager This second one is the most used. 第二个是最常用的。 You can find how to use it here and here . 您可以在这里这里找到如何使用它。

As far as I have seen both works fine but if you ask to me which one I will use, I will choose the one Google recommend: #1. 据我所知,两种方法都可以正常工作,但是如果您问我将使用哪一种,我会选择一种Google推荐的方法:#1。

Here is what they say about it: 他们是这样说的:

The Google Location Services API, part of Google Play Services, provides a more powerful, high-level framework that automatically handles location providers, user movement, and location accuracy. 作为Google Play服务的一部分的Google Location Services API提供了更强大的高级框架,该框架可自动处理位置提供者,用户移动和位置准确性。 It also handles location update scheduling based on power consumption parameters you provide. 它还根据您提供的功耗参数处理位置更新计划。 In most cases, you'll get better battery performance, as well as more appropriate accuracy, by using the Location Services API. 在大多数情况下,通过使用Location Services API,您将获得更好的电池性能以及更合适的精度。

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

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