关于Android高德地图的简单开发实例代码(DEMO)

废话不多说了,直接给大家上干货了。

以下为初次接触时 ,练手的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> listItem; //输入keyword,数据返回的list数据源 
//====================以下为操作数据库================== 
private ArrayList> 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 tipList, int rCode) { 
if (rCode == 1000) {// 正确返回 
//监听反馈回来的数据当做listView数据源 
listItem=new ArrayList>(); 
for (int i = 0; i < tipList.size(); i++) { 
HashMap map = new HashMap(); 
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 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 poiItems = poiResult.getPois();// 取得第一页的poiitem数据,页数从数字0开始 
List 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); 
} 
} 
} 
} 
资源文件如下:
 
 

以上所述是小编给大家介绍的关于Android高德地图的简单开发实例代码(DEMO),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

你可能感兴趣的:(关于Android高德地图的简单开发实例代码(DEMO))