关于Android高德地图的简单开发实例代码(DEMO)
程序员文章站
2024-03-01 20:11:58
废话不多说了,直接给大家上干货了。
以下为初次接触时 ,练手的demo
import android.app.activity;
import androi...
废话不多说了,直接给大家上干货了。
以下为初次接触时 ,练手的demo
import android.app.activity; import android.app.progressdialog; import android.content.contentvalues; import android.database.cursor; import android.database.sqlexception; import android.database.sqlite.sqlitedatabase; import android.graphics.color; import android.os.bundle; import android.os.handler; import android.os.message; import android.text.editable; import android.text.textwatcher; import android.util.log; import android.view.gravity; import android.view.keyevent; import android.view.view; import android.widget.adapterview; import android.widget.autocompletetextview; import android.widget.button; import android.widget.linearlayout; import android.widget.listview; import android.widget.simpleadapter; import android.widget.textview; import android.widget.toast; import com.amap.api.location.amaplocation; import com.amap.api.location.amaplocationclient; import com.amap.api.location.amaplocationclientoption; import com.amap.api.location.amaplocationlistener; import com.amap.api.maps.amap; import com.amap.api.maps.cameraupdatefactory; import com.amap.api.maps.locationsource; import com.amap.api.maps.mapview; import com.amap.api.maps.uisettings; import com.amap.api.maps.model.bitmapdescriptorfactory; import com.amap.api.maps.model.latlng; import com.amap.api.maps.model.marker; import com.amap.api.maps.model.markeroptions; import com.amap.api.maps.model.poi; import com.amap.api.maps.overlay.poioverlay; import com.amap.api.services.core.latlonpoint; import com.amap.api.services.core.poiitem; import com.amap.api.services.core.suggestioncity; import com.amap.api.services.geocoder.geocodequery; import com.amap.api.services.geocoder.geocoderesult; import com.amap.api.services.geocoder.geocodesearch; import com.amap.api.services.geocoder.regeocodequery; import com.amap.api.services.geocoder.regeocoderesult; import com.amap.api.services.help.inputtips; import com.amap.api.services.help.inputtipsquery; import com.amap.api.services.help.tip; import com.amap.api.services.poisearch.poiresult; import com.amap.api.services.poisearch.poisearch; import java.util.arraylist; import java.util.hashmap; import java.util.list; import java.util.map; public class basemapactivity extends activity implements view.onclicklistener,locationsource,amaplocationlistener,textwatcher,inputtips.inputtipsli stener,amap.onmarkerclicklistener,poisearch.onpoisearchlistener,amap.onpoiclicklistener,ge ocodesearch.ongeocodesearchlistener{ private mapview mapview; private amap amap; private linearlayout ly_1; private button bt_map; private autocompletetextview search_keyword; //输入要搜索的keyword private listview listview; //keyword 监听数据形成的列表 private progressdialog progdialog = null;// 进度条显示 private linearlayout ly_2; //ly_1 所包含的布局之一 private button bt_back1; private listview history_listview; private textview history_item_tv; list<map<string, object>> listitem; //输入keyword,数据返回的list数据源 //====================以下为操作数据库================== private arraylist<hashmap<string, object>> maphistorylist; //=============地图定位控件============== private onlocationchangedlistener mlistener; private amaplocationclient mlocationclient; private amaplocationclientoption mlocationoption; //=============地图自身ui定义============ private uisettings muisettings; //=============通用地图控件============== private latlonpoint mlatlonpoint;//初始定位经纬度 private double ms,me; //经纬度double值 private string locationadressname; //=============地图poi关键字搜索========== private poiresult poiresult; // poi返回的结果 private poisearch.query query;// poi查询条件类 private poisearch poisearch;// poi搜索 private static string keyword = "";// 要输入的poi搜索关键字 private int currentpage = 0;// 当前页面,从0开始计数 private button bt_search; //搜索poi private markeroptions options; //========================以下为地理编码================= private geocodesearch geocodersearch; private static string addresscitydistric; //得到逆地理编码的 市区 @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.base_map_activity); mapview = (mapview) findviewbyid(r.id.map); mapview.oncreate(savedinstancestate);// 此方法必须重写 init(); initui(); inithistorylist(); } /** * 初始化amap对象 */ private void init() { if (amap == null) { amap = mapview.getmap(); setupmap(); } } /** * 设置一些amap的属性 */ private void setupmap() { amap.setlocationsource(this);// 设置定位监听 amap.getuisettings().setmylocationbuttonenabled(true);// 设置默认定位按钮是否显示 amap.setmylocationenabled(true);// 设置为true表示显示定位层并可触发定位,false表示 隐藏定位层并不可触发定位,默认是false // 设置定位的类型为定位模式 ,可以由定位、跟随或地图根据面向方向旋转几种 amap.setmylocationtype(amap.location_type_locate); amap.movecamera(cameraupdatefactory.newlatlngzoom(new latlng(me,ms), 14)); //当前 地图镜头界面 (让地图在刚进入时就是这个的话,需要先得到latlng值即可,待后续修正) muisettings= amap.getuisettings(); //实例化地图ui设置 muisettings.setscalecontrolsenabled(true); //比例尺显示 muisettings.setcompassenabled(false); //指南针不显示 mlocationoption.setgpsfirst(true); //优先返回gps定位信息 amap.setonpoiclicklistener(this); //poi 点击事件监听 amap.setonmarkerclicklistener(this); geocodersearch = new geocodesearch(this); geocodersearch.setongeocodesearchlistener(this); // 注册地理编码监听 } private void initui(){ ly_1=(linearlayout)findviewbyid(r.id.map_2); //地图隐藏掉显示的界面 bt_map=(button)findviewbyid(r.id.map_bt); //首页 按钮 bt_map.setonclicklistener(this); //返回键 bt_back1=(button)findviewbyid(r.id.bt_back_1); bt_back1.setonclicklistener(this); //keyword search_keyword=(autocompletetextview)findviewbyid(r.id.keyword); search_keyword.addtextchangedlistener(this); //keyword输入list listview=(listview)findviewbyid(r.id.map_list); //第二页显示 ly_2=(linearlayout)findviewbyid(r.id.history_record); //poi 搜索 按钮 bt_search=(button)findviewbyid(r.id.bt_search); bt_search.setonclicklistener(this); //历史记录 list history_listview=(listview)findviewbyid(r.id.lv_history); history_item_tv=(textview)findviewbyid(r.id.history_item_addressname); } @override public void onclick(view v) { switch (v.getid()){ case r.id.map_bt: bt_map.setvisibility(view.gone); mapview.setvisibility(view.gone); ly_1.setvisibility(view.visible); break; case r.id.bt_search: // mlocationclient.stoplocation(); searchbutton(); bt_map.setvisibility(view.gone); mapview.setvisibility(view.visible); ly_1.setvisibility(view.visible); listview.setvisibility(view.gone); ly_2.setvisibility(view.gone); break; case r.id.bt_back_1: amap.clear(); bt_map.setvisibility(view.visible); mapview.setvisibility(view.visible); ly_1.setvisibility(view.gone); break; } } /** * 方法必须重写 */ @override protected void onresume() { super.onresume(); mapview.onresume(); } /** * 方法必须重写 */ @override protected void onpause() { super.onpause(); mapview.onpause(); } /** * 方法必须重写 */ @override protected void onsaveinstancestate(bundle outstate) { super.onsaveinstancestate(outstate); mapview.onsaveinstancestate(outstate); } /** * 方法必须重写 */ @override protected void ondestroy() { super.ondestroy(); mapview.ondestroy(); } /** * back设置 * @param keycode * @param event * @return */ @override public boolean onkeydown(int keycode, keyevent event) { if (keycode == keyevent.keycode_back ) { amap.clear(); bt_map.setvisibility(view.visible); mapview.setvisibility(view.visible); ly_1.setvisibility(view.gone); } return false; } //========================================================以下为定位 =============================================== /** * 激活定位 */ @override public void activate(onlocationchangedlistener listener) { mlistener = listener; if (mlocationclient == null) { mlocationclient = new amaplocationclient(this); mlocationoption = new amaplocationclientoption(); //设置定位监听 mlocationclient.setlocationlistener(this); //设置为高精度定位模式 mlocationoption.setlocationmode (amaplocationclientoption.amaplocationmode.hight_accuracy); //设置定位参数 mlocationclient.setlocationoption(mlocationoption); // 此方法为每隔固定时间会发起一次定位请求,为了减少电量消耗或网络流量消耗, // 注意设置合适的定位时间的间隔(最小间隔支持为2000ms),并且在合适时间调用 stoplocation()方法来取消定位请求 // 在定位结束后,在合适的生命周期调用ondestroy()方法 // 在单次定位情况下,定位无论成功与否,都无需调用stoplocation()方法移除请求, 定位sdk内部会移除 mlocationclient.startlocation(); } } /** * 停止定位 */ @override public void deactivate() { mlistener = null; if (mlocationclient != null) { mlocationclient.stoplocation(); mlocationclient.ondestroy(); } mlocationclient = null; } /** * 定位成功后回调函数 */ @override public void onlocationchanged(amaplocation amaplocation) { if (mlistener != null && amaplocation != null) { if (amaplocation != null && amaplocation.geterrorcode() == 0) { mlistener.onlocationchanged(amaplocation);// 显示系统小蓝点 message msg = mhandler.obtainmessage(); //定位成功后,开始hangler更新经纬 度 msg.obj = amaplocation; msg.what = utils.msg_location_finish; mhandler.sendmessage(msg); //当前定位后的详细位置(省、市、区、街道信息) locationadressname=amaplocation.getprovider()+amaplocation.getcity ()+amaplocation.getdistrict()+amaplocation.getaddress(); } else { string errtext = "定位失败," + amaplocation.geterrorcode()+ ": " + amaplocation.geterrorinfo(); toast.maketext(getapplicationcontext(),errtext,toast.length_short).show(); } } } handler mhandler = new handler() { public void dispatchmessage(android.os.message msg) { switch (msg.what) { //开始定位 case utils.msg_location_start: //("正在定位..."); break; // 定位完成 case utils.msg_location_finish: amaplocation loc = (amaplocation) msg.obj; string result = utils.getlocationstr(loc); // (result); ms=utils.jingdu; me=utils.weidu; mlatlonpoint=new latlonpoint(me,ms); break; //停止定位 case utils.msg_location_stop: // ("定位停止"); break; default: break; } }; }; //=========================================以下为keyword 改变监听 =================================== @override public void beforetextchanged(charsequence charsequence, int i, int i1, int i2) { } @override public void ontextchanged(charsequence s, int start, int stop, int count) { string newtext = s.tostring().trim(); //在这里判断 是否有输入 if(s.length()<1){ ly_2.setvisibility(view.visible); listview.setvisibility(view.gone); }else { ly_2.setvisibility(view.gone); mapview.setvisibility(view.gone); listview.setvisibility(view.visible); } if (!amaputil.isemptyornullstring(newtext)) { inputtipsquery inputquery = new inputtipsquery(newtext, utils.city); inputtips inputtips = new inputtips(basemapactivity.this, inputquery); inputtips.setinputtipslistener(this); //设置=======得到数据监听======= inputtips.requestinputtipsasyn(); } } @override public void aftertextchanged(editable editable) { } //=======得到数据监听======= @override public void ongetinputtips(list<tip> tiplist, int rcode) { if (rcode == 1000) {// 正确返回 //监听反馈回来的数据当做listview数据源 listitem=new arraylist<map<string,object>>(); for (int i = 0; i < tiplist.size(); i++) { hashmap<string, object> map = new hashmap<string, object>(); map.put("mapname",tiplist.get(i).getname()); map.put("mapaddress",tiplist.get(i).getdistrict()); map.put("mapposition",tiplist.get(i).getpoint()); listitem.add(map); } listview.setadapter(new maplistadapter(this,listitem)); //输入时keyword 产生的列表的 item点击事件 listview.setonitemclicklistener(new adapterview.onitemclicklistener() { @override public void onitemclick(adapterview<?> adapterview, view view, int i, long l) { amap.clear(); mlocationclient.stoplocation(); latlonpoint latlonpoint=(latlonpoint)(listitem.get(i).get ("mapposition")); double dd=latlonpoint.getlatitude(); double ee=latlonpoint.getlongitude(); options=new markeroptions(); marker marker=amap.addmarker(options.position(new latlng(dd,ee))); // 做marker标记 marker.setvisible(true); amap.movecamera(cameraupdatefactory.newlatlngzoom(new latlng(dd,ee), 14));//移动视图 bt_map.setvisibility(view.gone); mapview.setvisibility(view.visible); ly_1.setvisibility(view.visible); listview.setvisibility(view.gone); ly_2.setvisibility(view.gone); toast.maketext(getapplicationcontext(),""+listitem.get(i).get ("mapposition"),toast.length_short).show(); } }); } else { toastutil.showerror(this, rcode); } } //==========================================以下为poi关键字搜索 ===================================================== /** * 显示进度框 */ private void showprogressdialog() { if (progdialog == null) progdialog = new progressdialog(this); progdialog.setprogressstyle(progressdialog.style_spinner); progdialog.setindeterminate(false); progdialog.setcancelable(false); progdialog.setmessage("正在搜索:\n" + keyword); progdialog.show(); } /** * 隐藏进度框 */ private void dissmissprogressdialog() { if (progdialog != null) { progdialog.dismiss(); } } /** * 点击搜索按钮 */ public void searchbutton() { keyword = amaputil.checkedittext(search_keyword); if ("".equals(keyword)) { toastutil.show(basemapactivity.this, "请输入搜索关键字"); return; } else { dosearchquery(); if (maphistorylist.size()>0){ for (int i=0;i<maphistorylist.size();i++){ if (keyword.equals(maphistorylist.get(i).get("maphistoryname").tostring ())){ return; } }} map_addtohistory(); //增加数据到数据库 } } /** * 开始进行poi搜索 */ protected void dosearchquery() { showprogressdialog();// 显示进度框 mlocationclient.stoplocation(); //停止定位 20160812 query = new poisearch.query(keyword, "", utils.city);// 第一个参数表示搜索字符串第二个参数表示poi搜索类型,第三个参数表示poi搜索区域(空字符串代表全国) query.setpagesize(20);// 设置每页最多返回多少条poiitem query.setpagenum(currentpage);// 设置查第一页 poisearch = new poisearch(this, query); poisearch.setonpoisearchlistener(this); poisearch.searchpoiasyn(); } /** * poi没有搜索到数据,返回一些推荐城市的信息 */ private void showsuggestcity(list<suggestioncity> cities) { string infomation = "推荐城市\n"; for (int i = 0; i < cities.size(); i++) { infomation += "城市名称:" + cities.get(i).getcityname() + "城市区号:" + cities.get(i).getcitycode() + "城市编码:" + cities.get(i).getadcode() + "\n"; } toastutil.show(basemapactivity.this, infomation); } /** * poi信息查询回调方法 */ @override public void onpoisearched(poiresult result, int rcode) { dissmissprogressdialog();// 隐藏对话框 if (rcode == 1000) { if (result != null && result.getquery() != null) {// 搜索poi的结果 if (result.getquery().equals(query)) {// 是否是同一条 poiresult = result; // 取得搜索到的poiitems有多少页 list<poiitem> poiitems = poiresult.getpois();// 取得第一页的poiitem数据,页数从数字0开始 list<suggestioncity> suggestioncities = poiresult .getsearchsuggestioncitys();// 当搜索不到poiitem数据时,会返回含有搜索关键字的城市信息 if (poiitems != null && poiitems.size() > 0) { amap.clear();// 清理之前的图标 poioverlay poioverlay = new poioverlay(amap, poiitems); poioverlay.removefrommap(); poioverlay.addtomap(); poioverlay.zoomtospan(); } else if (suggestioncities != null && suggestioncities.size() > 0) { showsuggestcity(suggestioncities); } else { toastutil.show(basemapactivity.this, "无返回结果"); } } } else { toastutil.show(basemapactivity.this, "无返回结果"); } } else { toastutil.showerror(this, rcode); } } @override public void onpoiitemsearched(poiitem poiitem, int i) { } //===================以下为poi 点击事件================ @override public void onpoiclick(poi poi) { // amap.clear(); //暂时去掉 markeroptions markoptiopns = new markeroptions(); markoptiopns.position(poi.getcoordinate()); textview textview = new textview(getapplicationcontext()); textview.settext("到"+poi.getname()+"去"); textview.setgravity(gravity.center); textview.settextcolor(color.black); textview.setbackgroundresource(r.drawable.dir1); markoptiopns.icon(bitmapdescriptorfactory.fromview(textview)); markoptiopns.icon(bitmapdescriptorfactory.defaultmarker()); amap.addmarker(markoptiopns); latlng newlatlng=poi.getcoordinate(); double ss=newlatlng.latitude; double se=newlatlng.longitude; // latlonpoint newlatlonpoint=new latlonpoint(ss,se); getaddress(new latlonpoint(ss,se)); // toast.maketext(getapplicationcontext (),"marker"+addresscitydistric,toast.length_short).show(); } //==================以下为 marker 点击事件反馈=================== @override public boolean onmarkerclick(marker marker) { toast.maketext(getapplicationcontext(),"marker点击"+marker.getposition ()+"--"+marker.gettitle()+"--"+marker.getsnippet(),toast.length_short).show(); marker.getposition(); return false; } //========================以下为地理编码以及你地理编码================================ /** * 响应地理编码 */ public void getlatlon(final string name) { // showdialog(); geocodequery query = new geocodequery(name, utils.city);// 第一个参数表示地址,第 二个参数表示查询城市,中文或者中文全拼,citycode、adcode, geocodersearch.getfromlocationnameasyn(query);// 设置同步地理编码请求 } /** * 响应逆地理编码 */ public void getaddress(final latlonpoint latlonpoint) { // showdialog(); regeocodequery query = new regeocodequery(latlonpoint, 200, geocodesearch.amap);// 第一个参数表示一个latlng,第二参数表示范围多少米, 第三个参数表示是火系坐标系还是gps原生坐标系 geocodersearch.getfromlocationasyn(query);// 设置同步逆地理编码请求 } /** * 地理编码查询回调 */ @override public void ongeocodesearched(geocoderesult result, int rcode) { // dismissdialog(); if (rcode == 1000) { if (result != null && result.getgeocodeaddresslist() != null && result.getgeocodeaddresslist().size() > 0) { // geocodeaddress address = result.getgeocodeaddresslist().get(0); // amap.animatecamera(cameraupdatefactory.newlatlngzoom( // amaputil.converttolatlng(address.getlatlonpoint()), 15)); // geomarker.setposition(amaputil.converttolatlng(address // .getlatlonpoint())); // addressname = "经纬度值:" + address.getlatlonpoint() + "\n位置描 述:" // + address.getformataddress(); } } else { toastutil.showerror(this, rcode); } } /** * 逆地理编码回调 */ @override public void onregeocodesearched(regeocoderesult result, int rcode) { // dismissdialog(); if (rcode == 1000) { if (result != null && result.getregeocodeaddress() != null) { addresscitydistric = result.getregeocodeaddress().getformataddress(); textview tv=(textview)findviewbyid(r.id.address_name); tv.settext(addresscitydistric); log.e("fans",""+addresscitydistric); } else { toastutil.showerror(this, rcode); } } } } 资源文件如下: <?xml version="1.0" encoding="utf-8"?> <relativelayout 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" tools:context="com.gaodemap.basemapactivity"> <button android:id="@+id/map_bt" android:layout_width="260dp" android:layout_height="40dp" android:text="|查地点、搜路线" android:layout_marginleft="10dp" android:layout_margintop="7dp" android:background="@android:color/white" /> <com.amap.api.maps.mapview android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" > </com.amap.api.maps.mapview> <linearlayout android:id="@+id/ly_address_route" android:layout_width="350dp" android:layout_height="70dp" android:orientation="vertical" android:layout_centerhorizontal="true" android:layout_margintop="450dp" android:background="@android:color/darker_gray" > <linearlayout android:layout_width="match_parent" android:layout_height="40dp" android:orientation="horizontal" > <textview android:id="@+id/address_name" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center"/> <textview android:id="@+id/xiangqing" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="3" android:text="详情" android:gravity="center" /> </linearlayout> <framelayout android:layout_width="match_parent" android:layout_height="1dp" android:background="@android:color/black"></framelayout> <textview android:id="@+id/route_tv" android:layout_width="match_parent" android:layout_height="29dp" android:text="路径规划" android:gravity="center"/> </linearlayout> <linearlayout android:id="@+id/map_2" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:visibility="gone"> <linearlayout android:layout_width="match_parent" android:layout_height="60dp" android:orientation="horizontal"> <button android:id="@+id/bt_back_1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="返回"/> <autocompletetextview android:id="@+id/keyword" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="请输入关键字" android:textsize="14dp" android:imeoptions="actiondone" android:inputtype="text|textautocomplete" android:maxlength="20" android:layout_weight="2"/> <button android:id="@+id/bt_search" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="搜索"/> </linearlayout> <listview android:id="@+id/map_list" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone"></listview> <linearlayout android:id="@+id/history_record" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="@android:color/darker_gray" > <textview android:id="@+id/history_tv" android:layout_width="match_parent" android:layout_height="50dp" android:text="历史记录" android:textsize="16dp" android:gravity="center" /> <listview android:id="@+id/lv_history" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margintop="10dp"></listview> <textview android:id="@+id/zero_history_tv" android:layout_width="match_parent" android:layout_height="50dp" android:text="清空历史记录" android:textsize="16dp" android:gravity="center" /> </linearlayout> </linearlayout> </relativelayout> 代码中相关的工具类,即官方demo 中提供的工具类,并没什么改变。。 好了,初步的使用就是这样。 清单文件中相关权限 <!--地图相关权限--> <uses-permission android:name="android.permission.internet" /> <uses-permission android:name="android.permission.write_external_storage" /> <uses-permission android:name="android.permission.access_coarse_location" /> <uses-permission android:name="android.permission.access_network_state" /> <uses-permission android:name="android.permission.access_fine_location" /> <uses-permission android:name="android.permission.read_phone_state" /> <uses-permission android:name="android.permission.change_wifi_state" /> <uses-permission android:name="android.permission.access_wifi_state" /> <uses-permission android:name="android.permission.change_configuration" /> <uses-permission android:name="android.permission.wake_lock" /> <uses-permission android:name="android.permission.write_settings" /> <!-- 定位需要的服务 使用2.0的定位需要加上这个 --> <service android:name="com.amap.api.location.apsservice" ></service> 申请官方相关key ,根据自己androdi studio 上的sha1值和包名来获取 <meta-data android:name="com.amap.api.v2.apikey" android:value="xxxxxxxxxxxxxxxxxxxxxxx" />
以上所述是小编给大家介绍的关于android高德地图的简单开发实例代码(demo),希望对大家有所帮助