如何获得我的位置变化事件与谷歌地图Android的API V2? [英] How to get My Location changed event with Google Maps android API v2?

查看:206
本文介绍了如何获得我的位置变化事件与谷歌地图Android的API V2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得我的位置改变事件谷歌地图Android的API V2

第一版您可以做下,以手柄位置的改变事件:

 公共类MyLocationOverlay扩展com.google.android.maps.MyLocationOverlay {

    / **
     *监听器
     * /
    公共接口监听{
        无效onLocationChanged(android.location.Location位置);
    }

    私人监听器监听;

    公共MyLocationOverlay(上下文的背景下,图形页面图形页面,监听器监听){
        超(背景下,图形页面);

        this.listener =侦听器;
    }

    @覆盖
    市民同步无效onLocationChanged(位置定位){
        super.onLocationChanged(位置);

        //火监听器
        如果(听众!= NULL)
            listener.onLocationChanged(位置);
    }
}
 

解决方案

更新:谷歌推出新的<一个href="https://developer.android.com/reference/com/google/android/gms/location/LocationClient.html"><$c$c>LocationClient和相关的<一个href="https://developer.android.com/reference/com/google/android/gms/location/LocationListener.html"><$c$c>LocationListener (在 OnMyLocationChangeListener 接口现在是很precated)。


您可以通过创建一个自定义的 LocationSource 为我的定位层做到这一点。下面是自动居中相机上当前的位置,例如(我的位置),类似的是得到 MyLocationOverlay 提供在谷歌地图机器人的API v1的功能。

所以,你可以简单地替换这行的code

  mMap.animateCamera(CameraUpdateFactory.newLatLng(新经纬度(location.getLatitude(),location.getLongitude())));
 

与任何功能,你需要执行时的位置变化。

 公共类PlaceMapFragment扩展SupportMapFragment {

    //注意,这可能为空,如果谷歌Play业务APK不可用。
    私人GoogleMap的MMAP;

    保护PlaceActivity活动;
    私人FollowMeLocationSource followMeLocationSource;
    私人语境mContext;

    / *我们需要为了语境下获得参考位置管理
     *(实例该片段从活动使用的时候:
     * PlaceMapFragment mapFragment =新PlaceMapFragment(本); )* /
    公共PlaceMapFragment(上下文的背景下){
        this.mContext =背景;
    }

    @覆盖
    公共无效onActivityCreated(包savedInstanceState){
        super.onActivityCreated(savedInstanceState);

        活性=(PlaceActivity)getActivity();
    }

    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);

        //创建我们的自定义LocationSource并初始化它的一些成员
        followMeLocationSource =新FollowMeLocationSource();

        / *我们不能保证地图可用,因为谷歌Play业务可能不可用。
         *(在FragmentActivity /活动使用此code时,取消注释以下行
         *尝试得到一个参照地图在这里!)* /
        // setUpMapIfNeeded();
    }

    @覆盖
    公共无效onResume(){
        super.onResume();

        / *我们查询的最佳位置提供者每次出现这一片段
         *以防万一一个更好的供应商可能会变得可用,因为我们最后显示它* /
        followMeLocationSource.getBestAvailableProvider();

        //获取一个参照地图/ GoogleMap的对象
        setUpMapIfNeeded();

        / *启用我的定位层(这将导致我们的LocationSource时自动启动。)
         *当启用时,我的定位层不断吸引用户的指示
         *当前的位置和方位,并显示UI控件允许用户交互
         *与他们的位置(例如,使能或禁止它们的位置和方位的摄像机跟踪)。* /
        mMap.setMyLocationEnabled(真正的);
    }

    @覆盖
    公共无效的onPause(){
        / *禁用我的定位层(这将导致我们的LocationSource被自动关闭。)* /
        mMap.setMyLocationEnabled(假);

        super.onPause();
    }

    / **
     *设定地图,如果有可能的话(即谷歌播放服务APK是正确的
     *安装)和地图尚未实例化。这将确保我们永远只能
     *操作映射,一旦当它{@link #mMap}不为空。
     *所述p为H.;
     *如果没有安装{@link SupportMapFragment}(和{@link com.google.android.gms.maps.MapView
     *图形页面})将显示一个提示用户安装/更新谷歌播放服务APK他们的设备上。
     * /
    私人无效setUpMapIfNeeded(){
        //做一个空检查确认,我们还没有实例化的地图。
        如果(MMAP == NULL){
            MMAP =的GetMap();
            //检查如果我们成功取得地图。
            如果(MMAP!= NULL){
                //地图进行验证。这是现在可以安全地操作图:

                //更换我的定位层(默认)位置源与定制LocationSource
                mMap.setLocationSource(followMeLocationSource);

                //设置默认缩放
                mMap.moveCamera(CameraUpdateFactory.zoomTo(15F));
            }
        }
    }

    / *我们的定制LocationSource。
     *我们注册这个类来接收来自位置管理位置更新
     *出于这个原因,我们还需要实现LocationListener的接口。 * /
    私有类FollowMeLocationSource实现LocationSource,LocationListener的{

        私人OnLocationChangedListener mListener;
        私人LocationManager locationManager;
        私人最终标准标准=新标准();
        私人字符串bestAvailableProvider;
        / *更新被限制为每10秒1,只有当
         *已经检测到超过10米运动。* /
        私人最终诠释minTime = 10000; //最小时间间隔内的位置更新之间,以毫秒为单位
        私人最终诠释minDistance依旧= 10; //最小距离位置更新之间,以米为单位

        私人FollowMeLocationSource(){
            //获取参考位置管理
            locationManager =(LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);

            //指定地点提供标准
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            criteria.setPowerRequirement(Criteria.POWER_LOW);
            criteria.setAltitudeRequired(真正的);
            criteria.setBearingRequired(真正的);
            criteria.setSpeed​​Required(真正的);
            criteria.setCostAllowed(真正的);
        }

        私人无效getBestAvailableProvider(){
            / *指定位置提供的preffered方式(如GPS,网络)使用
             *是要求位置管理的一个最符合我们的标准。
             *通过传递'真'布尔我们要求的最好的(启用)提供商。 * /
            bestAvailableProvider = locationManager.getBestProvider(标准,真正的);
        }

        / *激活此提供商。该供应商将通知提供的侦听器
         *定期,直到调用关闭()。
         *此方法是自动实现我的定位层调用。 * /
        @覆盖
        公共无效启动(OnLocationChangedListener监听器){
            //我们需要不断的引用,我的定位层的听众,所以我们可以推进
            //位置更新,就当我们收到他们的位置管理。
            mListener =侦听器;

            //请求的位置从位置管理器更新
            如果(bestAvailableProvider!= NULL){
                locationManager.requestLocationUpdates(bestAvailableProvider,minTime,minDistance依旧,这一点);
            } 其他 {
                //(显示消息/对话)没有位置提供当前可用。
            }
        }

        / *关闭此提供商。
         *此方法是自动禁用我的定位层调用。 * /
        @覆盖
        公共无效停用(){
            //删除从位置管理位置更新
            locationManager.removeUpdates(本);

            mListener = NULL;
        }

        @覆盖
        公共无效onLocationChanged(位置定位){
            / *推位置更新到注册的侦听器..
             *(这可以保证我的地点层将设置蓝点在新/接收的位置)* /
            如果(mListener!= NULL){
                mListener.onLocationChanged(位置);
            }

            / * ..和动画的相机,以该位置中心!
             *(因为我们的原因创建这​​个自定义位置源!)* /
            mMap.animateCamera(CameraUpdateFactory.newLatLng(新经纬度(location.getLatitude(),location.getLongitude())));
        }

        @覆盖
        公共无效onStatusChanged(字符串S,INT I,束束){

        }

        @覆盖
        公共无效onProviderEnabled(String s)将{

        }

        @覆盖
        公共无效onProviderDisabled(String s)将{

        }
    }

}
 

How to get My Location changed event with Google Maps android API v2?

In v1 you can do the next in order to handle location changed event:

public class MyLocationOverlay extends com.google.android.maps.MyLocationOverlay {

    /**
     * Listener
     */
    public interface Listener {
        void onLocationChanged(android.location.Location location);
    }

    private Listener listener;

    public MyLocationOverlay(Context context, MapView mapView, Listener listener) {
        super(context, mapView);

        this.listener = listener;
    }

    @Override
    public synchronized void onLocationChanged(Location location) {
        super.onLocationChanged(location);

        // fire listener
        if (listener != null)
            listener.onLocationChanged(location);
    }
}

解决方案

UPDATE: Google introduced the new LocationClient and associated LocationListener (the OnMyLocationChangeListener interface is now deprecated).


You can do this by creating a custom LocationSource for the my-location layer. Below is an example that automatically centers the camera on current location ("my location"), similar to the functionality that was offered by MyLocationOverlay in Google Maps Android API v1.

So you can simply replace this line of code

mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));

with whatever functionality you need to be executed when the location changes.

public class PlaceMapFragment extends SupportMapFragment {

    // Note that this may be null if the Google Play services APK is not available.
    private GoogleMap mMap;

    protected PlaceActivity activity;
    private FollowMeLocationSource followMeLocationSource;
    private Context mContext;

    /* We need the Context in order to get a reference to the Location Manager
     * (when instantiating this fragment from your activity use:
     *  PlaceMapFragment mapFragment = new PlaceMapFragment(this); ) */
    public PlaceMapFragment(Context context) {
        this.mContext = context;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        activity = (PlaceActivity)getActivity();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // creates our custom LocationSource and initializes some of its members
        followMeLocationSource = new FollowMeLocationSource();

        /* We can't be guaranteed that the map is available because Google Play services might not be available.
         * (un-comment the following line when using this code in a FragmentActivity / Activity 
         *  to try get a reference to the map here !) */
        //setUpMapIfNeeded();
    }

    @Override
    public void onResume() {
        super.onResume();

        /* We query for the best Location Provider everytime this fragment is displayed
         * just in case a better provider might have become available since we last displayed it */
        followMeLocationSource.getBestAvailableProvider();

        // Get a reference to the map/GoogleMap object
        setUpMapIfNeeded();

        /* Enable the my-location layer (this causes our LocationSource to be automatically activated.)
         * While enabled, the my-location layer continuously draws an indication of a user's
         * current location and bearing, and displays UI controls that allow a user to interact
         * with their location (for example, to enable or disable camera tracking of their location and bearing).*/
        mMap.setMyLocationEnabled(true);
    }

    @Override
    public void onPause() {
        /* Disable the my-location layer (this causes our LocationSource to be automatically deactivated.) */
        mMap.setMyLocationEnabled(false);

        super.onPause();
    }

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated. This will ensure that we only ever
     * manipulate the map once when it {@link #mMap} is not null.
     * <p>
     * If it isn't installed {@link SupportMapFragment} (and {@link com.google.android.gms.maps.MapView
     * MapView}) will show a prompt for the user to install/update the Google Play services APK on their device.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            mMap = getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                // The Map is verified. It is now safe to manipulate the map:

                // Replace the (default) location source of the my-location layer with our custom LocationSource
                mMap.setLocationSource(followMeLocationSource);

                // Set default zoom
                mMap.moveCamera(CameraUpdateFactory.zoomTo(15f));
            }
        }
    }

    /* Our custom LocationSource. 
     * We register this class to receive location updates from the Location Manager
     * and for that reason we need to also implement the LocationListener interface. */
    private class FollowMeLocationSource implements LocationSource, LocationListener {

        private OnLocationChangedListener mListener;
        private LocationManager locationManager;
        private final Criteria criteria = new Criteria();
        private String bestAvailableProvider;
        /* Updates are restricted to one every 10 seconds, and only when
         * movement of more than 10 meters has been detected.*/
        private final int minTime = 10000;     // minimum time interval between location updates, in milliseconds
        private final int minDistance = 10;    // minimum distance between location updates, in meters

        private FollowMeLocationSource() {
            // Get reference to Location Manager
            locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);

            // Specify Location Provider criteria
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            criteria.setPowerRequirement(Criteria.POWER_LOW);
            criteria.setAltitudeRequired(true);
            criteria.setBearingRequired(true);
            criteria.setSpeedRequired(true);
            criteria.setCostAllowed(true);
        }

        private void getBestAvailableProvider() {
            /* The preffered way of specifying the location provider (e.g. GPS, NETWORK) to use 
             * is to ask the Location Manager for the one that best satisfies our criteria.
             * By passing the 'true' boolean we ask for the best available (enabled) provider. */
            bestAvailableProvider = locationManager.getBestProvider(criteria, true);
        }

        /* Activates this provider. This provider will notify the supplied listener
         * periodically, until you call deactivate().
         * This method is automatically invoked by enabling my-location layer. */
        @Override
        public void activate(OnLocationChangedListener listener) {
            // We need to keep a reference to my-location layer's listener so we can push forward
            // location updates to it when we receive them from Location Manager.
            mListener = listener;

            // Request location updates from Location Manager
            if (bestAvailableProvider != null) {
                locationManager.requestLocationUpdates(bestAvailableProvider, minTime, minDistance, this);
            } else {
                // (Display a message/dialog) No Location Providers currently available.
            }
        }

        /* Deactivates this provider.
         * This method is automatically invoked by disabling my-location layer. */
        @Override
        public void deactivate() {
            // Remove location updates from Location Manager
            locationManager.removeUpdates(this);

            mListener = null;
        }

        @Override
        public void onLocationChanged(Location location) {
            /* Push location updates to the registered listener..
             * (this ensures that my-location layer will set the blue dot at the new/received location) */
            if (mListener != null) {
                mListener.onLocationChanged(location);
            }

            /* ..and Animate camera to center on that location !
             * (the reason for we created this custom Location Source !) */
            mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    }

}

这篇关于如何获得我的位置变化事件与谷歌地图Android的API V2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆