定期获取位置并在地图上绘制标记

2024-04-08

我正在寻找在 android 中创建一个应用程序,它基本上跟踪手机位置并定期向谷歌地图 api 添加标记,以便可以显示路线,我遇到的问题是我不知道如何获取位置定期和在后台。

这是我的代码:

public class MapsActivity extends FragmentActivity implements LocationListener {

private GoogleMap mMap; // Might be null if Google Play services APK is not available.
Button btnCurrent, btnPrevious;
ArrayList<Double> latitude = new ArrayList<>();
ArrayList<Double> longitude = new ArrayList<>();
LocationManager lm;
LocationListener ll;
Location networkLocation;
Location gpsLocation;
double LONG;
double LAT;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    networkLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);


    lm.requestLocationUpdates(lm.GPS_PROVIDER, 10, 0, new android.location.LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            LONG = networkLocation.getLongitude();
            LAT = networkLocation.getLatitude();

            latitude.add(LAT);
            longitude.add(LONG);

            Log.d("COORDS", LAT+" , "+LONG);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    });


    setUpMapIfNeeded();




    btnCurrent = (Button)findViewById(R.id.btn_currentLoc);
    btnPrevious = (Button) findViewById(R.id.btn_prevLoc);

    btnCurrent.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            mMap.clear();
            double curLong, curLat;
            String test = lm.getAllProviders().toString();
            LatLng CurrentLoc;

            Log.d("PROVIDERS ", test);

            if((lm.isProviderEnabled("gps"))==true)
            {
                curLong = gpsLocation.getLongitude();
                curLat = gpsLocation.getLatitude();
                CurrentLoc = new LatLng(curLat,curLong);
                Log.d("GPS", "true");
            }else
            {
                curLong = networkLocation.getLongitude();
                curLat = networkLocation.getLatitude();
                CurrentLoc = new LatLng(curLat,curLong);
                Log.d("GPS", "false");
            }


            mMap.addMarker(new MarkerOptions().position(new LatLng(curLat,curLong)).title("LOCATION "+ curLat + ", " + curLong));
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(CurrentLoc,15));
            Log.d("LOCATION", curLat + "," + curLong);




        }
    });

    btnPrevious.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            for(int i = 0;i<latitude.size();i++)
            {
                mMap.addMarker(new MarkerOptions().position(new LatLng(latitude.get(i),longitude.get(i))).title("LOCATION "+ latitude.get(i) + ", " + longitude.get(i)));

                Log.d("LOCATION", latitude.get(i)+ "," + longitude.get(i));


            }


        }
    });

}

@Override
protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();
}


private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}


private void setUpMap() {


}

private void getCurrentLocation(){




}

private void seeAllLocations(){




}


@Override
public void onLocationChanged(Location location) {

}
}

任何帮助,将不胜感激。


检查下面的代码,它可以帮助您在单击按钮时获取当前位置以及@some timeInterval。

public class MainActivity extends Activity implements ConnectionCallbacks,
        OnConnectionFailedListener, LocationListener {

    // LogCat tag
    private static final String TAG = MainActivity.class.getSimpleName();

    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

    private Location mLastLocation;

    // Google client to interact with Google API
    private GoogleApiClient mGoogleApiClient;

    // boolean flag to toggle periodic location updates
    private boolean mRequestingLocationUpdates = false;

    private LocationRequest mLocationRequest;

    // Location updates intervals in sec
    private static int UPDATE_INTERVAL = 10000; // 10 sec
    private static int FATEST_INTERVAL = 5000; // 5 sec
    private static int DISPLACEMENT = 10; // 10 meters

    // UI elements
    private TextView lblLocation;
    private Button btnShowLocation, btnStartLocationUpdates;

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

        lblLocation = (TextView) findViewById(R.id.lblLocation);
        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
        btnStartLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates);

        // First we need to check availability of play services
        if (checkPlayServices()) {

            // Building the GoogleApi client
            buildGoogleApiClient();

            createLocationRequest();
        }

        // Show location button click listener
        btnShowLocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                displayLocation();
            }
        });

        // Toggling the periodic location updates
        btnStartLocationUpdates.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                togglePeriodicLocationUpdates();
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

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

        checkPlayServices();

        // Resuming the periodic location updates
        if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopLocationUpdates();
    }

    /**
     * Method to display the location on UI
     * */
    private void displayLocation() {

        mLastLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);

        if (mLastLocation != null) {
            double latitude = mLastLocation.getLatitude();
            double longitude = mLastLocation.getLongitude();

            lblLocation.setText(latitude + ", " + longitude);

        } else {

            lblLocation
                    .setText("(Couldn't get the location. Make sure location is enabled on the device)");
        }
    }

    /**
     * Method to toggle periodic location updates
     * */
    private void togglePeriodicLocationUpdates() {
        if (!mRequestingLocationUpdates) {
            // Changing the button text
            btnStartLocationUpdates
                    .setText(getString(R.string.btn_stop_location_updates));

            mRequestingLocationUpdates = true;

            // Starting the location updates
            startLocationUpdates();

            Log.d(TAG, "Periodic location updates started!");

        } else {
            // Changing the button text
            btnStartLocationUpdates
                    .setText(getString(R.string.btn_start_location_updates));

            mRequestingLocationUpdates = false;

            // Stopping the location updates
            stopLocationUpdates();

            Log.d(TAG, "Periodic location updates stopped!");
        }
    }

    /**
     * Creating google api client object
     * */
    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
    }

    /**
     * Creating location request object
     * */
    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FATEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
    }

    /**
     * Method to verify google play services on the device
     * */
    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Toast.makeText(getApplicationContext(),
                        "This device is not supported.", Toast.LENGTH_LONG)
                        .show();
                finish();
            }
            return false;
        }
        return true;
    }

    /**
     * Starting the location updates
     * */
    protected void startLocationUpdates() {

        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);

    }

    /**
     * Stopping location updates
     */
    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
    }

    /**
     * Google api callback methods
     */
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
                + result.getErrorCode());
    }

    @Override
    public void onConnected(Bundle arg0) {

        // Once connected with google api, get the location
        displayLocation();

        if (mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }

    @Override
    public void onConnectionSuspended(int arg0) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        // Assign the new location
        mLastLocation = location;

        Toast.makeText(getApplicationContext(), "Location changed!",
                Toast.LENGTH_SHORT).show();

        // Displaying the new location on UI
        displayLocation();
    }

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

定期获取位置并在地图上绘制标记 的相关文章

  • fitBounds() 显示整个地球(如果地图先隐藏然后显示)

    I have a bunch or markers and I want to show only the area containing them I found a long list of similar questions see
  • “android.enableUnitTestBinaryResources”已弃用[重复]

    这个问题在这里已经有答案了 我刚刚更新了我的 Android Studio 现在当我构建我的项目时 我收到此错误 选项 android enableUnitTestBinaryResources 已弃用 这 当前默认值为 假 已从当前版本中
  • 如何在 Android Studio 中使用 git 分支

    我是 git 新手 我有一个非常简单的使用 git 的场景 我的第一个版本是用 Android Studio 编写的 现在我想使用一些新功能 到目前为止我做了什么 在我的 Android Studio 中启用 VCS 从 Android S
  • Android 在连接 Socket 时出现错误

    在阅读了一些express io文档并成功连接到之后 我尝试使用nodejs和express io编写简单的应用程序http chat socket io在命令行中运行下面的代码并打开后 我找到了使用 nodejs 和express io
  • 如何生成带logo的二维码?

    我正在为 Android 设备开发应用程序 我想生成带有徽标的二维码 With ZXing I know how to generate simple QR codes like this one But I want to generat
  • 为什么 LocationSettingsResult startResolutionForResult 不调用 onActivityResult?

    我看过这个问答LocationSettingsRequest 对话框 跳过 onActivityResult https stackoverflow com questions 31235564 locationsettingsreques
  • 模拟器的窗口比手机屏幕太大

    我做了一个小例子来测试我的Android环境 当我在AVD上启动执行时 它看起来太大了 就好像它是平板电脑屏幕一样 如何调整大小使其看起来像手机屏幕 Android Studio 2 2更新后就没有了Emulator Tab in Edit
  • Android 自定义对话框中的图标

    有没有一种方法可以在不使用 AlertDialog 方法的情况下在自定义对话框上设置图标 对话框有标题 但缺少漂亮的分隔线和设置图标的功能 但肯定有一种方法可以在不使用 AlertDialog 的情况下获得两者 您可以使用以下代码添加图标
  • 如何将数据从 SQLITE 数据库获取到 Android 中的数组?

    很确定这是一个简单的问题 但我对所有将从游标返回的数据适应不同视图的示例感到困惑 我只想运行原始查询并将返回的每一项数据放入浮点数组中 以便我稍后可以将它们添加起来 我需要为此使用什么 Thanks 当您查询数据库时 您仍然会有一个游标 但
  • 使用 GestureDetector 时出现 NullPointerException

    下面是在发生不同事件时加载两个不同图像的帧动画的代码 第一个事件是在活动开始时 其他的是onTouch 我在哪里利用GestureDetector为了onDown and onScroll 问题是我得到NullPointerExceptio
  • 应用程序在 JSON jparser 发出 http 请求时崩溃

    您好 我使用本教程连接到网络或本地的 mySQL 数据库 here http www androidhive info 2012 05 how to connect android with php mysql 虽然所有服务器端 php 文
  • Android NDK __android_log_print函数和LogCat

    我有一个类似的功能 android log print ANDROID LOG INFO HelloNDK 在我的 C 代码上 我在 LogCat 上找不到该输出 我需要设置什么样的过滤器 按日志标签 按日志消息 按应用程序名称 按日志级别
  • 应用程序被终止时无法处理 FCM 消息

    我一直在阅读各种教程 其他 SO 线程以及官方 Android 开发人员和 Firebase 文档 但无济于事 我已经尝试了几乎所有的方法 但我已经耗尽了精力和时间 因为我正在修复以前可以工作但现在不再工作的通知系统 我正在使用 Azure
  • Android 2.3 或更低版本上通知中的可点击自定义视图

    我创建了一个自定义通知布局 其中有一个可单击的按钮 到目前为止 在 Android 3 API 级别 11 或更高版本上可以正常工作 但在 Android 2 3 即ContentIntent来自Notification总是覆盖我的布局并且
  • 在主表单之前显示登录表单

    我在表单之间导航时遇到问题 我使用 Delphi XE5 创建了一个 Android Firemonkey 移动应用程序 我目前有一个登录表单和主表单 现在我想要有关如何处理登录表单以显示在主表单之前的建议 在 项目选项 中的表单下 选择要
  • 用 ruby​​ 解决旅行商问题(50 多个位置)

    我在一家快递公司工作 目前 我们 手动 解决了 50 多个地点的路线 我一直在考虑使用 Google Maps API 来解决这个问题 但我读到有 24 点的限制 目前我们在服务器中使用 Rails 因此我正在考虑使用 ruby 脚本来获取
  • Android 多用户支持(4.2 中的新功能)对服务器端数据模型(例如 android_id)的影响

    Google 刚刚发布了 Android 4 2 其中支持单个设备上的多个用户配置文件 http developer android com about versions android 4 2 html MultipleUsers htt
  • 始终启动没有历史记录的新活动实例

    有没有办法将活动作为没有历史记录的新实例启动 在清单文件中尝试了以下内容 android launchmode singleinstance android noHistory true 我能够实现我所需要的 但是一旦屏幕锁定 就会显示之前
  • Pinterest 喜欢自定义 GridView

    我是 Android 新手 我正在寻找网格视图的逻辑 例如为 iPhone 构建的 pinterest homescreen 应用程序 一个大号 图像来自服务器 我需要以以下形式显示并具有分页效果 即在滚动上加载图像 如果可以的话请回复 我
  • 需要在 Android 应用程序卸载期间执行一些活动

    我正在开发一个应用程序 如果用户卸载该应用程序 我需要登录该应用程序 所以我正在遵循这种方法应用程序如何检测到它将被卸载 https stackoverflow com questions 18692571 how it works war

随机推荐

  • Linux/C下判断两个文件路径是否指向同一个文件?

    在Linux下 我有两个文件路径A和B const char A const char B 我现在想确定 我是否应该open 2 他们俩 int fda open A int fdb open B 我会在文件系统中打开同一个文件的两个文件句
  • Asp.Net Mvc 3 客户端验证、属性生成

    Asp net Mvc3 在输入元素上添加了一些自定义属性 例如 data val required 以执行验证 我知道这背后的所有理论 以及它是如何运作的 我想知道的是 当我在 using Html BeginForm 中创建表单时 它会
  • 如何使用seaborn为我的DataFrame创建堆积条形图[重复]

    这个问题在这里已经有答案了 我有一个数据框df df pd DataFrame columns App Feature1 Feature2 Feature3 Feature4 Feature5 Feature6 Feature7 Featu
  • 如何解析非结构化表状数据?

    我有一个text file保存操作的一些结果 数据显示在human readable format 就像一张桌子 我如何解析这些数据 以便形成一个数据结构 例如dictionaries有了这个数据 的一个例子unstructured dat
  • 获取所有不到一个月的物品

    有没有办法在 Django 中获取日期小于一个月前的所有对象 就像是 items Item objects filter less than a month old order by 你对 月 的定义是什么 30天 31天 除此之外 这应该
  • 如何将参数值传递给 a4j:jsFunction

    在我的页面上有一个按钮 可以在弹出窗口中打开项目列表 当我在列表中选择一个项目时 我想将该项目的 id 传递给我的第一页的 backingbean 是否可以 它尝试这样做a4j jsFunction and a4j param但它不起作用
  • 如何在 php 中创建可编辑的 Pdf 表单

    我有一个简单的表单 我想使用 php 使其可以在 pdf 中编辑 但是 pdf 正在创建表单 但我无法编辑和提交它 有什么原因或者我无法使用 php 编辑 pdf 我的代码是
  • 从 Firebase 数据库检索特定数据

    我正在使用 Firebase 数据库和 Java 在 Android 上创建一个聊天应用程序 每当用户首次注册时 它会将其用户名存储到节点下的数据库中user UserID profile username 用户名使用 User 类存储 这
  • 包含 iframe 中的 iframe 的目标父 div

    所以基本上我有这样的东西 div class iframe holder span span div gt div class iframe holder span span div gt div class iframe holder s
  • 为加权图生成邻接矩阵

    我正在尝试实施弗洛伊德 沃歇尔算法 http en wikipedia org wiki Floyd E2 80 93Warshall algorithm 为此 我需要设置一个adjacency matrix的加权图 我该怎么做呢 我知道这
  • 如何在没有 DOTALL 的情况下匹配任何内容 (DOTALL)?

    我的正则表达式需要默认的非换行符匹配点和re DOTALL dot 匹配换行符 我需要前几个 只是one后者在单个正则表达式中 尽管如此 因为我需要一个点来匹配换行符 所以我必须使用DOTALL 并使用 n 多次以获得默认的 除换行符之外的
  • 以编程方式隐藏和显示 WKInterfaceGroup

    我正在使用 xCode 6 2 beta 2 并尝试以编程方式隐藏和显示组 但没有显示我可以编写的方法group hidden YES or group hidden NO还有其他方法可以做到同样的事情吗 是的 WKInterfaceGro
  • 如何减慢从BVH文件读取opengl动画的速度?

    使用 GLFW3 我目前制作了一个 bvh 文件解析器 它读取文件并将其转换为我在 opengl 中制作的人体模型 然而 每当我启动它时 移动速度太快 以至于眼睛看不到动画 所以我想把动画速度调低一点 这是我的渲染循环 while glfw
  • efcore 3.1 不支持字符串连接查询?

    有没有办法通过使用 String Format 或 将多个字段连接在一起或只是传统的 来使用 EFCore 3 1 进行查询 我有这个代码 await this Db ACoolDbSet Where y gt y Plums y Pear
  • 如何使用 JSON 从 Java 服务器将图像发送到 Javascript 客户端

    我正在研究 Google Contacts API 我收到了所有数据并以字符串形式发送到 JSON javascript 但是当我从联系人获取图像时 我可以接收图像 我怎样才能将它发送到 JSON 如何将图像文件发送到 URL 可以使用路标
  • 是否可以通过内置应用程序将文件保存在沙箱之外?

    如果我有一个UIWebView其中包含文件链接 那么是否可以将这些文件保存到应用程序沙箱之外的磁盘上 是的 我知道应用程序无法访问其沙箱之外的文件系统 但是保存过程可以由任何可以处理文件类型的应用程序来完成吗 例如 如果它是音频文件 我的应
  • 在 bash 中重定向 stdout 和 stderr 的正确方法是什么? [复制]

    这个问题在这里已经有答案了 这是我想要完成的具体任务 zsh 的行为方式是我喜欢的 zsh which clang gt dev null 2 gt 1 echo clang echo gcc clang which doesntexist
  • 如何制作模态 JFrame 或另一个 JComponent?

    我有一个主 JFrame 和一个附加 JFrame 用于输入许多附加参数 所以 我需要我的第二个 jframe 将数据返回到主 jframe 使用 ActionListener 作为 保存 按钮 但我不知道如何做到这一点 请告诉我 我希望你
  • 谷歌字体@import + @font-face?

    我正在尝试在 CSS 中使用 import 和 font face 导入 Google Fonts 字体 我以前只使用 font face下载字体 但由于加载需要时间 我更喜欢使用Google Fonts方法 我不希望 Roboto 的 粗
  • 定期获取位置并在地图上绘制标记

    我正在寻找在 android 中创建一个应用程序 它基本上跟踪手机位置并定期向谷歌地图 api 添加标记 以便可以显示路线 我遇到的问题是我不知道如何获取位置定期和在后台 这是我的代码 public class MapsActivity e