Android 谷歌地图每秒更新当前位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21403181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:31:10  来源:igfitidea点击:

Google map update current location every second

androidgoogle-mapsgoogle-maps-api-3locationgeometry

提问by Christ Samuel

Hello stackoferflow users.

你好 stackoferflow 用户。

I am developing android App and this app implement Google Play Service

我正在开发 android 应用程序和这个应用程序实现 Google Play Service

I already get my location and set a pin and also a circle on my maps.

我已经获得了我的位置并在我的地图上设置了一个图钉和一个圆圈。

What i want to achieve is whenever i move to someplace, the circle will also move and put my position as the centerlocation.

我想要实现的是每当我移动到某个地方时,圆圈也会移动并将我的位置作为中心位置。

My question is :

我的问题是:

  1. How to update my current location every 2-5 second and the circle will also move to my new current location

  2. How to set my circle area as an area where the marker will place, so if the marker not in the area of my circle, it will not shown on the map.

  1. 如何每 2-5 秒更新我的当前位置,圆圈也会移动到我的新当前位置

  2. 如何将我的圆圈区域设置为标记将放置的区域,因此如果标记不在我的圆圈区域内,它将不会显示在地图上。

Thank you

谢谢

This is my code that i use for maps:

这是我用于地图的代码:

    mMap.setMyLocationEnabled(true);
    mMap.getUiSettings().setCompassEnabled(true);
    mMap.getUiSettings().setMyLocationButtonEnabled(true);
    mMap.getUiSettings().setRotateGesturesEnabled(true);

    locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
    // Creating a criteria object to retrieve provider
    Criteria criteria = new Criteria();

    // Getting the name of the best provider
    String provider = locationManager.getBestProvider(criteria, true);

    // Getting Current Location
    Location location = locationManager.getLastKnownLocation(provider);

    mMap.setInfoWindowAdapter(new InfoWindowAdapter() {

        @Override
        public View getInfoWindow(Marker arg0) {
            return null;
        }

        @Override
        public View getInfoContents(Marker marker) {
            View v = getLayoutInflater().inflate(R.layout.marker, null);
            TextView title= (TextView) v.findViewById(R.id.title);
            TextView info= (TextView) v.findViewById(R.id.info);
            title.setText(marker.getTitle().toString());
            info.setText(marker.getSnippet().toString());
            return v;
        }
    });

    if(location != null){
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        myPosition = new LatLng(latitude, longitude);   

        CameraUpdate center = CameraUpdateFactory.newLatLngZoom(myPosition, 15);
        mMap.moveCamera(center);
        mMap.addMarker(new MarkerOptions()
            .position(myPosition)
            .alpha(0.8f)
            .anchor(0.0f, 1.0f)
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.blue_pin))
            .title("Your position :\n ")
            .snippet(latitude + " and " + longitude));

        CircleOptions circleOptions = new CircleOptions()
          .center(myPosition)   //set center
          .radius(rad)   //set radius in meters
          .fillColor(0x402092fd)  //default
          .strokeColor(Color.LTGRAY)
          .strokeWidth(5);
          circle = mMap.addCircle(circleOptions);   

          CameraPosition cameraPosition = CameraPosition.builder()
                  .target(myPosition)
                  .zoom(15)
                  .bearing(90)
                  .build();

         mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition),2000, null);
    }

Thank you =)

谢谢你=)

回答by Sachin Suthar

Hello for updating your location every second you have to use broadcasting.using this your service start so can put your map code in thread where you put delay 1 second so you get location every second.you also put this method in broadcast receiver class.

您好,您必须每秒更新您的位置,您必须使用广播。使用此服务启动您可以将地图代码放入线程中,您将延迟 1 秒,以便每秒获取位置。您还将此方法放入广播接收器类中。

    public void onReceive(final Context context, Intent intent) {
        this.context = context;
        Log.i(TAG, "onReceive");

        locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            listener = new LocationListener() {

                @Override
                public void onLocationChanged(Location location) {
                    // double valueLatitude = location.getLatitude();
                    // double valueLongitude= location.getLongitude();
                    double precision = Math.pow(10, 6);
                    double valueLatitude = ((int) (precision * location
                            .getLatitude())) / precision;
                    double valueLongitude = ((int) (precision * location
                            .getLongitude())) / precision;
                    Log.i(TAG, "onLocationChanged");
                    Log.v(TAG, "LAT: " + valueLatitude + " & LONG: "
                            + valueLongitude);
                    String lat = String.valueOf(valueLatitude);
                    String lng = String.valueOf(valueLongitude);
                    SessionManager.saveLocation(valueLatitude, valueLongitude, context);
                    Log.v(TAG, "LAT: SESSION" + SessionManager.getlattitude(context));
                    try {
                        if (!SessionManager.getlattitude(context).equals(
                                valueLatitude)
                                || !SessionManager.getlongitude(context)
                                .equals(valueLongitude)) {

                            SessionManager.saveLocation(valueLatitude,
                                    valueLongitude, context);
//                            if (Utils.progrsDia.isShowing()) {
//                                Utils.progrsDia.dismiss();
//                            }
//                            CategoryNearbyFragment.callGetNearByFlyerListListner
//                                    .callGetNearByFlyer(lat, lng);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onProviderDisabled(String arg0) {
                }

                @Override
                public void onProviderEnabled(String arg0) {
                }

                @Override
                public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
                }

            };
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            locationManager.requestSingleUpdate(
                    LocationManager.NETWORK_PROVIDER, listener, null);
        } else {
            // GlobalData.showSettingsAlert(context);
        }
    }

回答by Shylendra Madda

For your first question How to update my current location every 2-5 second and the circle will also move to my new current location

对于你的第一个问题 How to update my current location every 2-5 second and the circle will also move to my new current location

I suggest you take a look at the excellent and complete sample at Googles Receiving Location Updatesguide.

我建议您查看 Googles Receiving Location Updates指南中出色且完整的示例。

It includes sample code and an Android project you can import in ADT straight away.

它包括示例代码和一个 Android 项目,您可以直接在 ADT 中导入。

The callback method that Location Services invokes to send a location update to your app is specified in the LocationListener interface, in the method onLocationChanged().

位置服务调用以向您的应用程序发送位置更新的回调方法在 LocationListener 接口的 onLocationChanged() 方法中指定。

There you can put your camera update.

在那里你可以把你的相机更新。

For your query How to set my circle area as an area where the marker will placefollow thislink

对于您的查询,请How to set my circle area as an area where the marker will place点击链接

回答by Naaz

I'll suggest using the onLocationChange() method to load refreshed coords into the lat long variables and then use a handler timed for like 5 seconds or 10seconds to update the map object using the moveCamera() functions ,this way you will get steady updates that are not too frequently annoying!

我建议使用 onLocationChange() 方法将刷新的坐标加载到 lat long 变量中,然后使用定时 5 秒或 10 秒的处理程序使用 moveCamera() 函数更新地图对象,这样您将获得稳定的更新这不是太频繁烦人!