【Android】3.17 示例17--周边雷达功能
分类:C#、Android、VS2015、百度地图应用; 创建日期:2016-02-04
一、简介
周边雷达功能同步支持Android和iOS端。它本质是一个连接百度LBS开放平台前端SDK产品和后端LBS云的中间服务。开发者利用周边雷达功能,可以便捷的在自己的应用内,帮助用户实现查找周边跟“我”使用同样一款App的人这样一个功能。或者说,利用周边雷达功能,开发者可在App内低成本、快速实现查找周边使用相同App的用户位置。
1、周边雷达功能的典型使用场景
(1)查看周边都有谁跟“我”使用同一个App,分布在哪里?
(2)查看周边用户在听什么歌、看什么文章、有什么新动态?
(3)查看周边有什么最新发生的新闻、资讯?
2、使用周边雷达功能的流程
使用周边雷达功能的流程如下:
第一步、注册周边雷达
在使用周边雷达功能之前,需要对应用的密钥(Key)做相应的注册操作。周边雷达支持应用位置信息上传,及一个或多个应用之间实现相互的位置信息查看功能。
第二步、集成SDK
周边雷达是地图SDK产品的一个功能模块,需要使用周边雷达功能的开发者,需在官网下载包含周边雷达功能的地图SDK,并将其集成到自己的开发环境中即可。
具体SDK集成方式请参考《开发指南 – 配置环境及发布》章节的介绍。
第三步、开发
完成周边雷达注册和SDK集成后,即可开始具体功能的开发工作。
具体使用方法请参考后文的详细介绍及官方Demo示例。
二、运行截图
简介:介绍如果使用周边雷达功能上传位置、检索周边的人
详述:
(1)获取位置信息并单次上传服务端;
(2)获取位置信息连续上传服务端;
(3)检索周边用户的位置;
(4)用列表的形式及地图的形式展示周边用户的位置等信息;
注意:需要把应用的key在官网的雷达注册页面进行相关的注册才能使用!
注册网址:http://developer.baidu.com/map/index.php?title=radar
本示例运行截图如下:
三、设计步骤
1、在雷达注册页面中注册key
进入官网的雷达注册页面,用原来申请的key注册雷达定位服务。
2、添加demo17_radarlist.xml文件
在layout文件夹下添加该文件,然后将代码改为下面的内容:
(略)
3、添加demo17_radarmap.xml文件
在layout文件夹下添加该文件,然后将代码改为下面的内容:
(略)
4、添加demo17_radartablayout.xml文件
在layout文件夹下添加该文件,然后将代码改为下面的内容:
(略)
5、添加Demo17CustomViewPager.cs文件
在SrcSdkDemos文件夹下添加该文件,然后将代码改为下面的内容:
using Android.App; using Android.Content; using Android.Support.V4.View; using Android.Util; using Android.Views; namespace BdMapV371Demos.SrcSdkDemos { [Activity(Label = "@string/demo_name_share")] public class Demo17CustomViewPager : ViewPager { private bool isCanScroll = false; public Demo17CustomViewPager(Context context) : base(context) { } public Demo17CustomViewPager(Context context, IAttributeSet attrs) : base(context, attrs) { } public void SetScanScroll(bool isCanScroll) { this.isCanScroll = isCanScroll; } public override void ScrollTo(int x, int y) { base.ScrollTo(x, y); } public override void SetCurrentItem(int item, bool smoothScroll) { base.SetCurrentItem(item, smoothScroll); } public override bool OnTouchEvent(MotionEvent e) { if (isCanScroll) { return base.OnTouchEvent(e); } else { return false; } } public override bool OnInterceptTouchEvent(MotionEvent ev) { if (isCanScroll) { return base.OnInterceptTouchEvent(ev); } else { return false; } } } }
6、添加Demo17Radar.cs文件
在SrcSdkDemos文件夹下添加该文件,然后将代码改为下面的内容:
using Android.App; using Android.Content.PM; using Android.OS; using Android.Util; using Android.Text; using Android.Views; using Android.Widget; using Android.Graphics; using Com.Baidu.Location; using Com.Baidu.Mapapi.Map; using Com.Baidu.Mapapi.Model; using Com.Baidu.Mapapi.Radar; using Android.Support.V4.View; using System.Collections.Generic; namespace BdMapV371Demos.SrcSdkDemos { /// <summary> /// 演示周边雷达的业务场景使用 /// </summary> [Activity(Label = "@string/demo_name_radar", ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.KeyboardHidden, ScreenOrientation = ScreenOrientation.Sensor)] public class Demo17Radar : Activity, IRadarUploadInfoCallback, IRadarSearchListener, IBDLocationListener { #region 界面空间相关 private Demo17CustomViewPager mPager;//自定义viewPager,目的是禁用手势滑动 private List<View> listViews; private TabHost mTabHost; private EditText userId; private EditText userDes; private Button uploadOnece; private Button uploadContinue; private Button stopUpload; private Button switchBtn; private Button searchNearbyBtn; private Button clearRstBtn; private Button clearInfoBtn; private int index = 0; private Button listPreBtn; private Button listNextBtn; private TextView listCurPage; private Button mapPreBtn; private Button mapNextBtn; private TextView mapCurPage; #endregion #region 定位相关 LocationClient mLocClient; private int pageIndex = 0; private int curPage = 0; private int totalPage = 0; private LatLng pt = null; #endregion #region 周边雷达相关 RadarNearbyResult listResult = null; ListView mResultListView = null; RadarResultListAdapter mResultListAdapter = null; private string userID = ""; private string userComment = ""; private bool uploadAuto = false; #endregion #region 地图相关 private TextureMapView mMapView; private BaiduMap mBaiduMap; private TextView popupText = null;//泡泡view BitmapDescriptor ff3 = BitmapDescriptorFactory.FromResource(Resource.Drawable.icon_marka); #endregion protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.demo17_radartablayout); //初始化UI和地图 InitUI(); //周边雷达设置监听 RadarSearchManager.Instance.AddNearbyInfoListener(this); //周边雷达设置用户,id为空默认是设备标识 RadarSearchManager.Instance.SetUserID(userID); // 定位初始化 mLocClient = new LocationClient(this); mLocClient.RegisterLocationListener(this); LocationClientOption option = new LocationClientOption(); option.OpenGps = false; // 是否打开gps option.CoorType = "bd09ll"; // 设置坐标类型 option.ScanSpan = 1000; mLocClient.LocOption = option; mLocClient.Start(); } private void InitUI() { mTabHost = FindViewById<TabHost>(Resource.Id.tabhost); mTabHost.Setup(); mTabHost.AddTab(mTabHost.NewTabSpec("tabUpload") .SetIndicator(ComposeLayout("上传位置", 0)) .SetContent(Resource.Id.tabUpload)); mTabHost.AddTab(mTabHost.NewTabSpec("tabGet") .SetIndicator(ComposeLayout("检索周边", 0)) .SetContent(Resource.Id.tabGet)); mTabHost.CurrentTab = 0; mTabHost.TabChanged += (s, e) => { mTabHost.TabWidget.GetChildAt(mTabHost.CurrentTab).SetBackgroundColor(Color.ParseColor("#B0E2FF")); }; mPager = FindViewById<Demo17CustomViewPager>(Resource.Id.viewpager); listViews = new List<View>(); View layout = LayoutInflater.Inflate(Resource.Layout.demo17_radarlist, null); View mapLayout = LayoutInflater.Inflate(Resource.Layout.demo17_radarmap, null); //地图初始化 mMapView = mapLayout.FindViewById<TextureMapView>(Resource.Id.map); mBaiduMap = mMapView.Map; mBaiduMap.MarkerClick += (s, e) => { var marker = e.P0; mBaiduMap.HideInfoWindow(); if (marker != null) { popupText = new TextView(this); popupText.SetBackgroundResource(Resource.Drawable.popup); popupText.SetTextColor(Color.ParseColor("0xFF000000")); popupText.Text = marker.ExtraInfo.GetString("des"); mBaiduMap.ShowInfoWindow(new InfoWindow(popupText, marker.Position, -47)); MapStatusUpdate update = MapStatusUpdateFactory.NewLatLng(marker.Position); mBaiduMap.SetMapStatus(update); } }; mBaiduMap.MapClick += (s, e) => { mBaiduMap.HideInfoWindow(); }; mBaiduMap.MyLocationEnabled = true; listViews.Add(layout); listViews.Add(mapLayout); mPager.Adapter = new MyPagerAdapter(listViews); mPager.CurrentItem = 0; mPager.PageSelected += (s, e) => { if (e.Position == 0) //切换为列表 { index = 0; switchBtn.Text = "地图"; } else //切换为地图 { index = 1; switchBtn.Text = "列表"; } }; userId = FindViewById<EditText>(Resource.Id.id); userDes = FindViewById<EditText>(Resource.Id.des); //用户ID和用户描述文本框变化时引发的事件 userId.TextChanged += User_TextChanged; userDes.TextChanged += User_TextChanged; //【检索周边】按钮 searchNearbyBtn = FindViewById<Button>(Resource.Id.searchNearByButton); searchNearbyBtn.Click += delegate { //查找周边的人 if (pt == null) { Toast.MakeText(this, "未获取到位置", ToastLength.Long).Show(); return; } pageIndex = 0; SearchRequest(pageIndex); }; //【清除结果】按钮 clearRstBtn = FindViewById<Button>(Resource.Id.clearResultButton); clearRstBtn.Click += delegate { //清除查找结果 ParseResultToList(null); ParseResultToMap(null); clearRstBtn.Enabled = false; listPreBtn.Visibility = ViewStates.Invisible; listNextBtn.Visibility = ViewStates.Invisible; mapPreBtn.Visibility = ViewStates.Invisible; mapNextBtn.Visibility = ViewStates.Invisible; listCurPage.Visibility = ViewStates.Invisible; mapCurPage.Visibility = ViewStates.Invisible; mBaiduMap.HideInfoWindow(); }; //【地图】按钮 switchBtn = FindViewById<Button>(Resource.Id.switchButton); switchBtn.Click += delegate { //viewPager切换 if (index == 0) { //切换为地图 index = 1; switchBtn.Text = "列表"; } else { //切换为列表 index = 0; switchBtn.Text = "地图"; } mPager.CurrentItem = index; }; //【获取当前位置并上传】按钮 uploadOnece = FindViewById<Button>(Resource.Id.uploadonece); uploadOnece.Click += delegate { //上传一次位置 if (pt == null) { Toast.MakeText(this, "未获取到位置", ToastLength.Long).Show(); return; } RadarUploadInfo info = new RadarUploadInfo(); info.Comments = userComment; info.Pt = pt; RadarSearchManager.Instance.UploadInfoRequest(info); clearInfoBtn.Enabled = true; }; //【连续获取位置并上传】按钮 uploadContinue = FindViewById<Button>(Resource.Id.uploadcontinue); uploadContinue.Click += delegate { //开始自动上传 if (pt == null) { Toast.MakeText(this, "未获取到位置", ToastLength.Long).Show(); return; } uploadAuto = true; RadarSearchManager.Instance.StartUploadAuto(this, 5000); uploadContinue.Enabled = false; stopUpload.Enabled = true; clearInfoBtn.Enabled = true; }; //【停止上传】按钮 stopUpload = FindViewById<Button>(Resource.Id.stopupload); stopUpload.Click += delegate { //停止自动上传 uploadAuto = false; RadarSearchManager.Instance.StopUploadAuto(); stopUpload.Enabled = false; uploadContinue.Enabled = true; }; //【清除当前信息】按钮 clearInfoBtn = FindViewById<Button>(Resource.Id.clearInfoButton); clearInfoBtn.Click += delegate { //清除自己当前的信息 RadarSearchManager.Instance.ClearUserInfo(); }; //--------layout--demo17_radarlist.xml---------------- //【上一页】按钮 listPreBtn = layout.FindViewById<Button>(Resource.Id.radarlistpre); listPreBtn.Click += delegate { if (pageIndex < 1) return; pageIndex--; SearchRequest(pageIndex); }; //【下一页】按钮 listNextBtn = layout.FindViewById<Button>(Resource.Id.radarlistnext); listNextBtn.Click += delegate { if (pageIndex >= totalPage - 1) return; pageIndex++; SearchRequest(pageIndex); }; listCurPage = layout.FindViewById<TextView>(Resource.Id.radarListPage); mapPreBtn = mapLayout.FindViewById<Button>(Resource.Id.radarmappre); mapNextBtn = mapLayout.FindViewById<Button>(Resource.Id.radarmapnext); mapCurPage = mapLayout.FindViewById<TextView>(Resource.Id.radarMapPage); uploadContinue.Enabled = true; stopUpload.Enabled = false; clearRstBtn.Enabled = false; clearInfoBtn.Enabled = false; listPreBtn.Visibility = ViewStates.Invisible; listNextBtn.Visibility = ViewStates.Invisible; mapPreBtn.Visibility = ViewStates.Invisible; mapNextBtn.Visibility = ViewStates.Invisible; listCurPage.Visibility = ViewStates.Invisible; mapCurPage.Visibility = ViewStates.Invisible; mTabHost.TabWidget.GetChildAt(0).SetBackgroundColor(Color.DarkGray); List<RadarNearbyInfo> infos = new List<RadarNearbyInfo>(); mResultListAdapter = new RadarResultListAdapter(this, infos); mResultListView = layout.FindViewById<ListView>(Resource.Id.radar_list); mResultListView.Adapter = mResultListAdapter; mResultListAdapter.NotifyDataSetChanged(); } private void User_TextChanged(object sender, TextChangedEventArgs e) { userID = userId.Text; userComment = userDes.Text; RadarSearchManager.Instance.SetUserID(userID); } private void SearchRequest(int index) { curPage = 0; totalPage = 0; RadarNearbySearchOption option = new RadarNearbySearchOption() .CenterPt(pt).PageNum(pageIndex).Radius(2000); RadarSearchManager.Instance.NearbyInfoRequest(option); listPreBtn.Visibility = ViewStates.Invisible; listNextBtn.Visibility = ViewStates.Invisible; mapPreBtn.Visibility = ViewStates.Invisible; mapNextBtn.Visibility = ViewStates.Invisible; listCurPage.Text = "0/0"; mapCurPage.Text = "0/0"; mBaiduMap.HideInfoWindow(); } /// <summary> /// 更新结果列表 /// </summary> /// <param name="res"></param> public void ParseResultToList(RadarNearbyResult res) { if (res == null) { if (mResultListAdapter.list != null) { mResultListAdapter.list.Clear(); mResultListAdapter.NotifyDataSetChanged(); } } else { mResultListAdapter.list.Clear(); foreach (RadarNearbyInfo v in res.InfoList) { mResultListAdapter.list.Add(v); } mResultListAdapter.NotifyDataSetChanged(); if (curPage > 0) { listPreBtn.Visibility = ViewStates.Visible; } if (totalPage - 1 > curPage) { listNextBtn.Visibility = ViewStates.Visible; } if (totalPage > 0) { listCurPage.Visibility = ViewStates.Visible; listCurPage.Text = string.Format("{0}/{1}", curPage + 1, totalPage); } } } /// <summary> ///更新结果地图 /// </summary> /// <param name="res"></param> public void ParseResultToMap(RadarNearbyResult res) { mBaiduMap.Clear(); if (res != null && res.InfoList != null && res.InfoList.Count > 0) { List<RadarNearbyInfo> v = new List<RadarNearbyInfo>(); foreach (RadarNearbyInfo item in res.InfoList) { v.Add(item); } for (int i = 0; i < v.Count; i++) { MarkerOptions option = new MarkerOptions() .InvokeIcon(ff3) .InvokePosition(v[i].Pt); Bundle des = new Bundle(); if (v[i].Comments == null || v[i].Comments == "") { des.PutString("des", "没有备注"); } else { des.PutString("des", v[i].Comments); } option.InvokeExtraInfo(des); mBaiduMap.AddOverlay(option); } } if (curPage > 0) { mapPreBtn.Visibility = ViewStates.Visible; } if (totalPage - 1 > curPage) { mapNextBtn.Visibility = ViewStates.Visible; } if (totalPage > 0) { mapCurPage.Visibility = ViewStates.Visible; mapCurPage.Text = string.Format("{0}/{1}", curPage + 1, totalPage); } } /// <summary> /// IRadarUploadInfoCallback要求实现的接口 /// 实现上传callback,自动上传 /// </summary> /// <returns></returns> public RadarUploadInfo OnUploadInfoCallback() { RadarUploadInfo info = new RadarUploadInfo(); info.Comments = userComment; info.Pt = pt; Log.Debug("hjtest", "OnUploadInfoCallback"); return info; } #region 实现IRadarSearchListener接口 public void OnGetClearInfoState(RadarSearchError p0) { var error = p0; if (error == RadarSearchError.RadarNoError) { Toast.MakeText(this, "清除位置成功", ToastLength.Long).Show(); } else { Toast.MakeText(this, "清除位置失败", ToastLength.Long).Show(); } } public void OnGetNearbyInfoList(RadarNearbyResult p0, RadarSearchError p1) { RadarNearbyResult result = p0; RadarSearchError error = p1; if (error == RadarSearchError.RadarNoError) { Toast.MakeText(this, "查询周边成功", ToastLength.Long).Show(); //获取成功 listResult = result; curPage = result.PageIndex; totalPage = result.PageNum; //处理数据 ParseResultToList(listResult); ParseResultToMap(listResult); clearRstBtn.Enabled = true; } else { //获取失败 curPage = 0; totalPage = 0; Toast.MakeText(this, "查询周边失败", ToastLength.Long).Show(); } } public void OnGetUploadState(RadarSearchError p0) { RadarSearchError error = p0; if (error == RadarSearchError.RadarNoError) { //上传成功 if (!uploadAuto) { Toast.MakeText(this, "单次上传位置成功", ToastLength.Long).Show(); } } else { //上传失败 if (!uploadAuto) { Toast.MakeText(this, "单次上传位置失败", ToastLength.Long).Show(); } } } #endregion protected override void OnPause() { mMapView.OnPause(); base.OnPause(); } protected override void OnResume() { mMapView.OnResume(); base.OnResume(); mTabHost.TabWidget.GetChildAt(0).SetBackgroundColor(Color.ParseColor("#B0E2FF")); } protected override void OnDestroy() { // 退出时销毁定位 mLocClient.Stop(); //释放周边雷达相关 RadarSearchManager.Instance.RemoveNearbyInfoListener(this); RadarSearchManager.Instance.ClearUserInfo(); RadarSearchManager.Instance.Destroy(); //释放地图 ff3.Recycle(); mMapView.OnDestroy(); mBaiduMap = null; base.OnDestroy(); } //定位SDK回调 public void OnReceiveLocation(BDLocation arg0) { if (arg0 == null || mBaiduMap == null) return; pt = new LatLng(arg0.Latitude, arg0.Longitude); MyLocationData locData = new MyLocationData.Builder() .Accuracy(arg0.Radius) // 此处设置开发者获取到的方向信息,顺时针0-360 .Direction(100).Latitude(arg0.Latitude) .Longitude(arg0.Longitude).Build(); if (mBaiduMap != null) { mBaiduMap.SetMyLocationData(locData); } } /// <summary> /// ViewPager适配器 /// </summary> public class MyPagerAdapter : PagerAdapter { public IList<View> mListViews; public MyPagerAdapter(IList<View> mListViews) { this.mListViews = mListViews; } public override int Count { get { return mListViews.Count; } } public override void DestroyItem(View container, int position, Java.Lang.Object objectValue) { ((ViewPager)container).RemoveView(mListViews[position]); base.DestroyItem(container, position, objectValue); } public override Java.Lang.Object InstantiateItem(View container, int position) { ((ViewPager)container).AddView(mListViews[position], 0); return mListViews[position]; } public override bool IsViewFromObject(View view, Java.Lang.Object objectValue) { return view == objectValue; } public override IParcelable SaveState() { return null; } } /// <summary> /// 结果列表listview适配器 /// </summary> private class RadarResultListAdapter : BaseAdapter { private Demo17Radar demo17Radar; public List<RadarNearbyInfo> list; public RadarResultListAdapter(Demo17Radar radar, List<RadarNearbyInfo> res) : base() { demo17Radar = radar; list = res; } public override int Count { get { if (list == null || (list != null && list.Count < 10)) { return 10; } else { return list.Count; } } } public override View GetView(int position, View convertView, ViewGroup parent) { convertView = View.Inflate(demo17Radar, Resource.Layout.demo_info_item, null); TextView title = convertView.FindViewById<TextView>(Resource.Id.title); TextView desc = convertView.FindViewById<TextView>(Resource.Id.desc); title.SetTextColor(Color.ParseColor("#0000FF")); desc.SetTextColor(Color.ParseColor("#0000FF")); if (list == null || list.Count == 0 || position >= list.Count) { desc.Text = ""; title.Text = ""; } else { if (list[position].Comments == null || list[position].Comments == "") { desc.Text = string.Format("{0}米_没有备注", list[position].Distance); } else { desc.Text = string.Format("{0}米_{1}", list[position].Distance, list[position].Comments); } title.Text = list[position].UserID; } return convertView; } public override Java.Lang.Object GetItem(int index) { if (list == null) { return new RadarNearbyInfo(); } else { return list[index]; } } public override long GetItemId(int id) { return id; } } public View ComposeLayout(string s, int i) { LinearLayout layout = new LinearLayout(this); layout.Orientation = Orientation.Vertical; ImageView iv = new ImageView(this); iv.SetImageResource(i); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); lp.SetMargins(0, 5, 0, 0); layout.AddView(iv, lp); TextView tv = new TextView(this); tv.Gravity = GravityFlags.Center; tv.SetSingleLine(true); tv.Text = s; tv.SetTextColor(Color.ParseColor("#0000FF")); tv.TextSize = 20; layout.AddView(tv, new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent)); return layout; } } }
7、修改MainActivity.cs
在MainActivity.cs文件的demos字段定义中,去掉【示例17】下面的注释。
运行观察结果。