【Android】3.21 示例21—兴趣点收藏功能

分类:C#、Android、VS2015、百度地图应用; 创建日期:2016-02-04

简介:介绍如何创建、管理本地收藏的兴趣点数据

详述:

(1)新建本地点收藏;

(2)查看已收藏本地点;

(3)删除已收藏本地点;

一、运行截图

长按选择的兴趣点,就会自动显示该点的经纬度,输入名称,单击【保存】按钮就保存了该兴趣点。可多次重复此过程保存多个兴趣点。

单击【查看全部】按钮,就会显示如下图所示的兴趣点标注。单击标注,会弹出对话框编辑或删除该标注。

单击【删除全部】,将删除所有兴趣点。

image

二、设计步骤

1、添加xml文件

在layout文件夹下添加下面的3个文件(代码不再列出):

demo21_favorite.xml

demo21_favorite_alert.xml

demo21_favorite_infowindow.xml

2、添加Demo21Favorite.cs文件

在SrcSdkDemos文件夹下添加该文件,然后将代码改为下面的内容:

using Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Views;
using Android.Widget;
using Com.Baidu.Mapapi.Favorite;
using Com.Baidu.Mapapi.Map;
using Com.Baidu.Mapapi.Model;
using System.Collections.Generic;

namespace BdMapV371Demos.SrcSdkDemos
{
    /// <summary>
    /// 演示如何使用本地点收藏功能
    /// </summary>
    [Activity(Label = "@string/demo_name_favorite",
        ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.KeyboardHidden,
        ScreenOrientation = ScreenOrientation.Sensor)]
    public class Demo21Favorite : Activity
    {
        //地图相关
        private TextureMapView mMapView;
        private BaiduMap mBaiduMap;

        //界面控件相关
        private EditText locationText;
        private EditText nameText;
        private View mPop;
        private View mModify;
        EditText mdifyName;
        //保存点中的点id
        private string currentID;
        //显示marker用的图标
        BitmapDescriptor bdA = BitmapDescriptorFactory.FromResource(Resource.Drawable.icon_marka);
        IList<Marker> markers = new List<Marker>();
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.demo21_favorite);
            //初始化地图
            mMapView = FindViewById<TextureMapView>(Resource.Id.bmapView);
            mBaiduMap = mMapView.Map;
            mBaiduMap.MapClick += (s, e) =>
            {
                mBaiduMap.HideInfoWindow();
            };
            mBaiduMap.MapLongClick += (s, e) =>
            {
                var point = e.P0;
                locationText.Text = string.Format("{0},{1}", point.Latitude, point.Longitude);
            };
            mBaiduMap.MarkerClick += (s, e) =>
            {
                var marker = e.P0;
                mBaiduMap.HideInfoWindow();
                if (marker == null)
                {
                    return;
                }
                else
                {
                    InfoWindow mInfoWindow = new InfoWindow(mPop, marker.Position, -47);
                    mBaiduMap.ShowInfoWindow(mInfoWindow);
                    MapStatusUpdate update = MapStatusUpdateFactory.NewLatLng(marker.Position);
                    mBaiduMap.SetMapStatus(update);
                    currentID = marker.ExtraInfo.GetString("id");
                }
            };

            //【保存】按钮--添加收藏点
            Button btnSave = FindViewById<Button>(Resource.Id.save);
            btnSave.Click += delegate
            {
                if (string.IsNullOrEmpty(nameText.Text))
                {
                    Toast.MakeText(this, "名称必填", ToastLength.Long).Show();
                    return;
                }
                if (string.IsNullOrEmpty(locationText.Text))
                {
                    Toast.MakeText(this, "坐标点必填", ToastLength.Long).Show();
                    return;
                }
                FavoritePoiInfo info = new FavoritePoiInfo();
                info.InvokePoiName(nameText.Text);

                LatLng pt;
                try
                {
                    string strPt = locationText.Text;
                    string lat = strPt.Substring(0, strPt.IndexOf(","));
                    string lng = strPt.Substring(strPt.IndexOf(",") + 1);
                    pt = new LatLng(double.Parse(lat), double.Parse(lng));
                    info.InvokePt(pt);
                    if (FavoriteManager.Instance.Add(info) == 1)
                    {
                        Toast.MakeText(this, "添加成功", ToastLength.Long).Show();
                    }
                    else
                    {
                        Toast.MakeText(this, "添加失败", ToastLength.Long).Show();
                    }
                }
                catch
                {
                    Toast.MakeText(this, "坐标解析错误", ToastLength.Long).Show();
                }
            };

            //【查看全部】按钮--获取全部收藏点
            Button btnSearchAll = FindViewById<Button>(Resource.Id.searchall);
            btnSearchAll.Click += delegate
            {
                mBaiduMap.Clear();
                IList<FavoritePoiInfo> list = FavoriteManager.Instance.AllFavPois;
                if (list == null || list.Count == 0)
                {
                    Toast.MakeText(this, "没有收藏点", ToastLength.Long).Show();
                    return;
                }
                //将marker绘制在地图上
                markers.Clear();
                for (int i = 0; i < list.Count; i++)
                {
                    MarkerOptions option = new MarkerOptions()
                    .InvokeIcon(bdA)
                    .InvokePosition(list[i].Pt);
                    Bundle b = new Bundle();
                    b.PutString("id", list[i].ID);
                    option.InvokeExtraInfo(b);
                    markers.Add((Marker)mBaiduMap.AddOverlay(option));
                }
            };

            //【删除全部】按钮--删除全部点
            Button btnDeleteAll = FindViewById<Button>(Resource.Id.deleteall);
            btnDeleteAll.Click += delegate
            {
                if (FavoriteManager.Instance.ClearAllFavPois())
                {
                    Toast.MakeText(this, "全部删除成功", ToastLength.Long).Show();
                    mBaiduMap.Clear();
                    mBaiduMap.HideInfoWindow();
                }
                else
                {
                    Toast.MakeText(this, "全部删除失败", ToastLength.Long).Show();
                }
            };

            //初始化收藏夹
            FavoriteManager.Instance.Init();
            //初始化UI
            InitUI();
        }
        public void InitUI()
        {
            locationText = FindViewById<EditText>(Resource.Id.pt);
            nameText = FindViewById<EditText>(Resource.Id.name);

            //获取弹框
            mPop = LayoutInflater.Inflate(Resource.Layout.demo21_favorite_infowindow, null, false);
            //弹框中的【修改】按钮--修改收藏点
            Button btnSearchOne = mPop.FindViewById<Button>(Resource.Id.searchone);
            btnSearchOne.Click += delegate
            {
                mBaiduMap.HideInfoWindow();
                //弹框修改
                mModify = LayoutInflater.Inflate(Resource.Layout.demo21_favorite_alert, null);
                mdifyName = mModify.FindViewById<EditText>(Resource.Id.modifyedittext);
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.SetView(mModify);
                string oldName = FavoriteManager.Instance.GetFavPoi(currentID).PoiName;
                mdifyName.Text = oldName;
                builder.SetPositiveButton("确认", (sender, args) =>
                 {
                     string newName = mdifyName.Text;
                     if (string.IsNullOrEmpty(newName) == false)
                     {
                         //modify
                         FavoritePoiInfo info = FavoriteManager.Instance.GetFavPoi(currentID);
                         info.InvokePoiName(newName);
                         if (FavoriteManager.Instance.UpdateFavPoi(currentID, info))
                         {
                             Toast.MakeText(this, "修改成功", ToastLength.Long).Show();
                         }
                     }
                     else
                     {
                         Toast.MakeText(this, "名称不能为空,修改失败", ToastLength.Long).Show();
                     }
                     (sender as AlertDialog).Dismiss();
                 });
                builder.SetNegativeButton("取消", (sender, args) =>
                {
                    (sender as AlertDialog).Dismiss();
                });
                builder.Create().Show();
            };
            //弹框中的【删除】按钮--删除一个指定点
            Button btnDeleteOne = mPop.FindViewById<Button>(Resource.Id.deleteone);
            btnDeleteOne.Click += delegate
            {
                if (FavoriteManager.Instance.DeleteFavPoi(currentID))
                {
                    Toast.MakeText(this, "删除点成功", ToastLength.Long).Show();
                    if (markers != null)
                    {
                        for (int i = 0; i < markers.Count; i++)
                        {
                            if (markers[i].ExtraInfo.GetString("id") == currentID)
                            {
                                markers[i].Remove();
                                markers.RemoveAt(i);
                                mBaiduMap.HideInfoWindow();
                                break;
                            }
                        }
                    }
                }
                else
                {
                    Toast.MakeText(this, "删除点失败", ToastLength.Long).Show();
                }
            };
        }

        protected override void OnPause()
        {
            mMapView.OnPause();
            base.OnPause();
        }

        protected override void OnResume()
        {
            mMapView.OnResume();
            base.OnResume();
        }

        protected override void OnDestroy()
        {
            //释放收藏夹功能资源
            FavoriteManager.Instance.Destroy();
            bdA.Recycle();
            // MapView的生命周期与Activity同步,当activity销毁时需调用MapView.destroy()
            mMapView.OnDestroy();
            mBaiduMap = null;
            base.OnDestroy();
        }
    }
}

3、修改MainActivity.cs文件

在MainActivity.cs文件的demos字段定义中,去掉【示例21】下面的注释。

运行观察效果。

posted @ 2016-02-04 16:10  rainmj  阅读(1057)  评论(1编辑  收藏  举报