简单实现安卓里百度地图持续定位
作者:周大胆 发布时间:2023-07-29 07:59:22
这几天自己研究了关于地手机上面开发安卓地图的问题,发现百度官方示例demo讲解百度持续定位方面还是讲解的有些不清楚,本人研究了几次之后将其弄得更详细以便于让各位方便学习,有不足之处请在评论区指出,官方示例的网址是:http://lbsyun.baidu.com/index.php?title=android-locsdk/guide/v5-0
上面的网址已经将安卓简单配置百度地图环境讲解的很详细了,再次不做赘述了,此外,可能会有人发现
package com.example.andoridloca;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.BDNotifyListener;//假如用到位置提醒功能,需要import该类
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.location.Poi;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.MapView;
public class MainActivity extends Activity implements OnClickListener{
MapView mMapView = null;
public static final String TAG="mian";
StringBuffer sb = new StringBuffer(256);
public StringBuilder builder=new StringBuilder();
private Button bt1;
private TextView tv1;
private DBtools DBhelper;
boolean isOpenLocation=false;
public LocationClient mLocationClient = null;
public BDLocationListener myListener = new MyLocationListener();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
DBhelper = new DBtools(this);
tv1=(TextView) findViewById(R.id.textView1);
tv1.setMovementMethod(new ScrollingMovementMethod());
bt1=(Button) findViewById(R.id.button1);
bt1.setOnClickListener(this);
mMapView = (MapView) findViewById(R.id.bmapView);
mLocationClient = new LocationClient(getApplicationContext()); //声明LocationClient类
mLocationClient.registerLocationListener( myListener ); //注册监听函数
initLocation();
}
private void initLocation(){
LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationMode.Hight_Accuracy
);//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备
option.setCoorType("bd09ll");//可选,默认gcj02,设置返回的定位结果坐标系
int span=0;
option.setScanSpan(span);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的
option.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要
option.setOpenGps(true);//可选,默认false,设置是否使用gps
option.setLocationNotify(true);//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果
option.setIsNeedLocationDescribe(true);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近”
option.setIsNeedLocationPoiList(true);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到
option.setIgnoreKillProcess(false);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死
option.SetIgnoreCacheException(false);//可选,默认false,设置是否收集CRASH信息,默认收集
option.setEnableSimulateGps(false);//可选,默认false,设置是否需要过滤gps仿真结果,默认需要
mLocationClient.setLocOption(option);
}
@Override
protected void onDestroy() {
super.onDestroy();
//在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理
mMapView.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
//在activity执行onResume时执行mMapView. onResume (),实现地图生命周期管理
mMapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
//在activity执行onPause时执行mMapView. onPause (),实现地图生命周期管理
mMapView.onPause();
}
public class MyLocationListener implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
//Receive Location
StringBuffer sb = new StringBuffer(256);
sb.append("time : ");
sb.append(location.getTime());
sb.append("\nerror code : ");
sb.append(location.getLocType());
sb.append("\nlatitude : ");
sb.append(location.getLatitude());
sb.append("\nlontitude : ");
sb.append(location.getLongitude());
sb.append("\nradius : ");
sb.append(location.getRadius());
if (location.getLocType() == BDLocation.TypeGpsLocation){// GPS定位结果
sb.append("\nspeed : ");
sb.append(location.getSpeed());// 单位:公里每小时
sb.append("\nsatellite : ");
sb.append(location.getSatelliteNumber());
sb.append("\nheight : ");
sb.append(location.getAltitude());// 单位:米
sb.append("\ndirection : ");
sb.append(location.getDirection());// 单位度
sb.append("\naddr : ");
sb.append(location.getAddrStr());
sb.append("\ndescribe : ");
sb.append("gps定位成功");
} else if (location.getLocType() == BDLocation.TypeNetWorkLocation){// 网络定位结果
sb.append("\naddr : ");
sb.append(location.getAddrStr());
//运营商信息
sb.append("\noperationers : ");
sb.append(location.getOperators());
sb.append("\ndescribe : ");
sb.append("网络定位成功");
} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
sb.append("\ndescribe : ");
sb.append("离线定位成功,离线定位结果也是有效的");
} else if (location.getLocType() == BDLocation.TypeServerError) {
sb.append("\ndescribe : ");
sb.append("服务端网络定位失败,可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com,会有人追查原因");
} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
sb.append("\ndescribe : ");
sb.append("网络不同导致定位失败,请检查网络是否通畅");
} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
sb.append("\ndescribe : ");
sb.append("无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机");
}
sb.append("\nlocationdescribe : ");
sb.append(location.getLocationDescribe());// 位置语义化信息
List<Poi> list = location.getPoiList();// POI数据
if (list != null) {
sb.append("\npoilist size = : ");
sb.append(list.size());
for (Poi p : list) {
sb.append("\npoi= : ");
sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
}
}
Log.i("BaiduLocationApiDem", sb.toString());
DBtools dbhelper=new DBtools(getApplicationContext());
ContentValues initialValues = new ContentValues();
initialValues.put("shijian",location.getTime());
initialValues.put("didian",location.getLatitude()+"--"+location.getLongitude());
dbhelper.open();
dbhelper.insert("path",initialValues);
dbhelper.close();
tv1.setText(sb.toString());
}
}
@Override
public void onClick(View arg0) {
Thread mytime=new Thread(new ThreadShow());
if(isOpenLocation){
mLocationClient.stop();
isOpenLocation=false;
}
else{
Toast.makeText(getApplicationContext(), "开启", Toast.LENGTH_SHORT).show();
isOpenLocation=true;
//mLocationClient.start();
mytime.start();
}
}
// handler类接收数据
Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 1) {
Log.i("BaiduLocationApiDem", "加以");
mLocationClient.start();
mLocationClient.requestLocation();
}
};
};
// 线程类
class ThreadShow implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
while (isOpenLocation) {
try {
mLocationClient.stop();
Thread.sleep(2000);
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
// System.out.println("send...");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("thread error...");
}
}
}
}
}
这里面关于mLocationClient.stop();mLocationClient.start(); mLocationClient.requestLocation(); 这三个函数我有必要讲解一下,因为持续定位时这三个函数的配合使用很重要,官方文档里面解释说mLocationClient.start()函数用于开启定位,mLocationClient.requestLocation()函数用于主动触发定位SDK内部定位逻辑,个人感觉差不多,两个都会执行我的mLocationClient的所属类里面的逻辑代码,可能是我的项目就这样吧,然后是mLocationClient.stop(),此函数用于停止定位,如果持续定位的话,是需要和mLocationClient.start()函数配合使用的,具体在上面的代码里面有展示。
切记不要将mLocationClient.start()和mLocationClient.stop()一起使用,我在网上查询时好像是说一部原因,具体举一个例子吧:
//某段代码如果是这样的话按照逻辑韩式会将mLocationClient所属类的里面逻辑代码执行一遍,具体见MainAvtivity里面的MyLocationListener类内容,但是实际上是不会执行的
mLocationClient.start();
mLocationClient.stop();
所以在我的MainActivity里面我使用线程来一遍遍的执行start和stop函数,这样就会消除刚刚说的这种效果,最后就能够实现持续定位了。
在此给出我的布局文件配合看看
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.newloca.MainActivity" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="300dp">
<com.baidu.mapapi.map.MapView
android:id="@+id/bmapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true" />
</RelativeLayout>
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="150dp"
android:scrollbars="vertical"
android:background="#f00"
android:text="位置信息" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:text="获取位置" />
</RelativeLayout>
</LinearLayout>
其他像权限什么的配置,用最开始给的官方地址里面的就行了
顺便说一下,本人是使用的安卓4.2版本开发的,手机真机调试和虚拟机调试在定位的时间间隔上面会有点误差,也不知道什么原因
来源:http://www.cnblogs.com/ztjloveshanshan/p/6250461.html
猜你喜欢
- Echarts图表数据一般都是从后台数据库实时取数据的 传输数据大多采用JSON数据格式 本文通过springmvc来拦截数据请求 完成数据
- 目录Emit异常处理流程 显示Exception对象的Message属性 返回目录 Emit异常处理流程来看这种C#异常处理代码: 
- 本文实例讲述了Java Spring开发环境搭建及简单入门示例。分享给大家供大家参考,具体如下:前言虽然之前用过Spring,但是今天试着去
- 编辑 项目目录/.idea/workspace.xml添加标签后,保存。重启idea即可。<component name="
- 当我们打开app的时候是不是会有一瞬间的白屏然后再进入主活动,虽然这并不会造成什么不好的后果,但是感觉用户体验就不是很好。像网易云音乐等等
- Spring发布了一个新工具Spring Native Beta,用于将现有的Spring Boot应用程序(用Java或Kotlin编写)
- Java BigDecimal的坑采坑处 BigDecimal bd =new BigDecimal(0.1);
- Gradle和Maven都是当前热门的自动化构建工具。使用Gradle去构建项目,由于没有办法像Maven一样配置Setting文件来修改本
- 像javascript中有eval()来执行动态代码,c#中是没有的,于是自己动手丰衣足食,先来代码using System;using S
- 这篇文章介绍了Java+Nginx实现POP、IMAP、SMTP邮箱代理服务,我们本次使用的环境为Centos7下,java程序我们通过ec
- import java.text.ParseException;import java.text.SimpleDateFormat;impo
- 本文实例讲述了Android中SeekBar和RatingBar用法。分享给大家供大家参考,具体如下:什么是SeekBar?可以拖动的进度条
- Android多媒体 MediaPlayer我们可以通过这个API来播放音频和视频该类是Androd多媒体框架中的一个重要组件,通过该类,我
- 一、银行存取款1.前言毕竟谁不喜欢钱呢!(不是😅)我看谁不喜欢在知识的海洋中遨游😤!2.描述银行存取款的流程是人们非常熟悉的事情,用户可以在
- 资源服务器就是业务服务 如用户服务,订单服务等 第三方需要到资源服务器调用接口获取资源ResourceServerConfigResourc
- Tinker是什么Tinker是微信官方的Android热补丁解决方案,它支持动态下发代码、So库以及资源,让应用能够在不需要重新安装的情况
- 本篇文章介绍:如何使用Toolbar;自定义Toolbar;先来看一看效果,了解一下toolbar;布局文件:<android.sup
- 我们已经有文章向你描述如何使用<include />标签来重用和共享你的布局代码。这篇文章将向你阐述<merge />
- 概述:App几乎都离不开与服务器的交互,本文主要讲解了flutter网络请求三种方式 flutter自带的HttpClient、 第三方库h
- 本文实例为大家分享了C#基于Socket实现多人聊天功能的具体代码,供大家参考,具体内容如下服务器服务器负责接受所有客户端发来的消息,和将接