更新谷歌地图上的位置

时间:2017-03-09 10:12:18

标签: java android multithreading google-maps

我想知道在地图上更新我的位置的最佳/建议方式是什么。我试图更改我的位置一旦它改变并在地图上绘制一条线路,我走过的路线。我正在考虑使用一个每5秒调用一次定位方法的线程(?),但我怀疑这是建议的方法。

问题:在地图上更新我的位置的最佳方法,以及如何为我拍摄的路径绘制路线。

如果有人能指出我正确的方向,我会非常感激。

1 个答案:

答案 0 :(得分:0)

您可以使用this库。它非常实用且可定制。您可以设置获取位置的频率。只需保留以前位置的参考。定义LocationTracker的全局实例,然后将其设置为这样。

private void setupLocationTracker() {
    TrackerSettings settings = new TrackerSettings()
            .setUseGPS(true)
            .setUseNetwork(true)
            .setUsePassive(true)
            .setTimeBetweenUpdates(1000 * 5)    //You can set it according to your needs
            .setMetersBetweenUpdates(10);    //Or you can set this too.
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, 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;
    }
    locationTracker = new LocationTracker(this, settings) {
        @Override
        public void onLocationFound(@NonNull Location location) {
            LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
            //if(latLngList.size() == 0) {
            mMap.addMarker(new MarkerOptions().position(currentLocation).title("Current Location"));
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 15.0f), 3000, null);
            //Write your function to draw line
            drawLine(previousLocation, currentLocation);
            previousLocation = currentLocation;
        }

        @Override
        public void onTimeout() {
            Log.d("MESSAGE", "Time out");
        }
    };
}

然后随时随地致电locationTraker.startListening()locationTracker.stopListening()。别忘了在stopListening()内拨打onPause()