項目中集成百度、高德、騰訊地圖已是司空見慣的事情,今天我總結了一下項目中用到的高德地圖常用的功能:
1.展示高德地圖並定位顯示定位圖標;
2.添加實時大頭針;
3.反地理編碼獲取周圍興趣點
效果如下:

現在開始展示集成流程
一.顯示地圖
1.申請key
至於如何申請高德地圖開發者賬號,請自行百度。在高德開放平台->控制台->創建新應用 ->添加新Key
需提前獲取 SHA1: keytool -v -list -keystore keystore 文件絕對路徑或者先定位到keystore 文件所在路徑后,后面只寫keystone文件名
2.配置AndroidManifest.xml
1)添加權限
//地圖SDK(包含其搜索功能)需要的基礎權限
1 <!--允許程序打開網絡套接字--> 2 <uses-permission android:name="android.permission.INTERNET" /> 3 <!--允許程序設置內置sd卡的寫權限--> 4 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 5 <!--允許程序獲取網絡狀態--> 6 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 7 <!--允許程序訪問WiFi網絡信息--> 8 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 9 <!--允許程序讀寫手機狀態和身份--> 10 <uses-permission android:name="android.permission.READ_PHONE_STATE" /> 11 <!--允許程序訪問CellID或WiFi熱點來獲取粗略的位置--> 12 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
2)配置key
1 <meta-data android:name="com.amap.api.v2.apikey" android:value="開發者申請的key "/>
3.下載jar包(若選擇3D地圖包,還需要下載so文件)
地圖SDK:http://lbs.amap.com/api/android-sdk/download
定位sdk:http://lbs.amap.com/api/android-location-sdk/download
4.將jar包放入libs目錄下
對於每個jar文件,右鍵-選擇Add As Library,導入到工程中。
或者使用菜單欄 選擇 File ->Project Structure->Modules-> Dependencies。點擊綠色的加號選擇File dependency. 然后選擇要添加的jar包即可,此時build.gradle中會自動生成如下信息(以地圖、定位為例)
5.初始化地圖容器
布局xml文件中添加地圖控件(以地圖2D):
1 <com.amap.api.maps2d.MapView 2 android:id="@+id/map" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent"/>
管理地圖生命周期
1 @Override 2 protected void onCreate(Bundle savedInstanceState) { 3 super.onCreate(savedInstanceState); 4 。。。。 5 //獲取地圖控件引用 6 mMapView = (MapView) findViewById(R.id.map); 7 //在activity創建地圖 8 aMapView.onCreate(savedInstanceState); 9 //初始化地圖控制器對象 10 if (aMap == null) { 11 aMap = mapView.getMap(); 12 } 13 } 14 @Override 15 protected void onDestroy() { 16 super.onDestroy(); 17 //在activity銷毀地圖 18 aMapView.onDestroy(); 19 //銷毀定位對象 20 if (null != mlocationClient) { 21 mlocationClient.onDestroy();//銷毀定位客戶端,同時銷毀本地定位服務。 22 } 23 } 24 @Override 25 protected void onResume() { 26 super.onResume(); 27 //在activity重新繪制加載地圖 28 aMapView.onResume(); 29 } 30 @Override 31 protected void onPause() { 32 super.onPause(); 33 //在activity暫停地圖的繪制 34 mMapView.onPause(); 35 } 36 @Override 37 protected void onSaveInstanceState(Bundle outState) { 38 super.onSaveInstanceState(outState); 39 //在activity保存地圖當前的狀態 40 mMapView.onSaveInstanceState(outState); 41 }
二.顯示定位小藍點及反地理編碼檢索
地圖 SDK 5.0.0版本之前
1.配置AndroidManifest.xml
請在application標簽中聲明service組件
1 <service android:name="com.amap.api.location.APSService"></service>
聲明權限
1 <!--用於獲取wifi的獲取權限,wifi信息會用來進行網絡定位--> 2 <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission> 3 <!--用於訪問GPS定位--> 4 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 5 <!--用於申請調用A-GPS模塊--> 6 <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/>
設置一些amap的屬性
1 private void setUpMap() { 2 // 自定義系統定位小藍點 3 MyLocationStyle myLocationStyle = new MyLocationStyle(); 4 myLocationStyle.myLocationIcon(BitmapDescriptorFactory 5 .fromResource(R.drawable.location_marker));// 設置小藍點的圖標 6 myLocationStyle.strokeColor(Color.BLACK);// 設置圓形的邊框顏色 7 myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 設置圓形的填充顏色 8 // myLocationStyle.anchor(int,int)//設置小藍點的錨點 9 myLocationStyle.strokeWidth(1.0f);// 設置圓形的邊框粗細 10 aMap.setMyLocationStyle(myLocationStyle); 11 aMap.setLocationSource(this);// 設置定位監聽 12 aMap.getUiSettings().setMyLocationButtonEnabled(true);// 設置默認定位按鈕是否顯示 13 aMap.setMyLocationEnabled(true);// 設置為true表示啟動顯示定位藍點,false表示隱藏定位藍點並不進行定位,默認是false。 14 // 觸摸監聽 15 aMap.setOnCameraChangeListener(cameraChangeListener); 16 }
2.初始化定位
在aMap.setLocationSource(this)中包含兩個回調:在activate()中設置定位初始化及啟動定位,在deactivate()中寫停止定位的相關調用。
1 /** 2 * 激活定位 3 */ 4 @Override 5 public void activate(OnLocationChangedListener listener) { 6 mListener = listener; 7 if (mlocationClient == null) { 8 //初始化定位 需要傳Context類型的參數。推薦用getApplicationConext()方法 9 mlocationClient = new AMapLocationClient(this); 10 //初始化定位參數 11 mLocationOption = new AMapLocationClientOption(); 12 //設置定位回調監聽 13 mlocationClient.setLocationListener(this); 14 //設置單次定位 該方法默認為false。 15 mLocationOption.setOnceLocation(true); 16 //選擇定位模式 SDK默認選擇使用高精度定位模式。 17 // 高精度定位模式:Hight_Accuracy 同時使用網絡定位和GPS定位 18 //低功耗定位模式:Battery_Saving 不會使用GPS和其他傳感器,只會使用網絡定位(Wi-Fi和基站定位) 19 //僅用設備定位模式:Device_Sensors 不需要連接網絡,只使用GPS進行定位,這種模式下不支持室內環境的定位,自 v2.9.0 版本支持返回地址描述信息 mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy); 20 //設置定位間隔,單位毫秒,默認為2000ms 最低1000ms 21 mLocationOption.setInterval(5000); 22 //設置是否返回地址信息(默認返回地址信息) 23 mLocationOption.setNeedAddress(true); 24 //設置是否強制刷新WIFI,默認為true,強制刷新,會增加電量消耗。 25 mLocationOption.setWifiActiveScan(true); 26 // 設置定位請求超時時間,單位是毫秒,默認30000毫秒,建議超時時間不要低於8000毫秒。 27 mLocationOption.setHttpTimeOut(30000); 28 //設置是否開啟定位緩存機制 緩存機制默認開啟true 網絡定位結果均會生成本地緩存, 29 // 不區分單次定位還是連續定位。GPS定位結果不會被緩存 30 mLocationOption.setLocationCacheEnable(true); 31 //設置定位參數 32 mlocationClient.setLocationOption(mLocationOption); 33 // 此方法為每隔固定時間會發起一次定位請求,為了減少電量消耗或網絡流量消耗, 34 // 注意設置合適的定位時間的間隔(最小間隔支持為2000ms),並且在合適時間調用stopLocation()方法來取消定位請求 35 // 在定位結束后,在合適的生命周期調用onDestroy()方法 36 // 在單次定位情況下,定位無論成功與否,都無需調用stopLocation()方法移除請求,定位sdk內部會移除 37 mlocationClient.startLocation();//啟動定位 38 } 39 } 40 /** 41 * 停止定位 42 */ 43 @Override 44 public void deactivate() { 45 mListener = null; 46 if (mlocationClient != null) { 47 mlocationClient.stopLocation();//停止定位后,本地定位服務並不會被銷毀 48 } 49 mlocationClient = null; 50 }
3.定位回調中設置顯示大頭針
mlocationClient.setLocationListener(this);后,重寫onLocationChanged回調
1 /** 2 * 定位成功后回調函數 3 */ 4 @Override 5 public void onLocationChanged(AMapLocation amapLocation) { 6 if (mListener != null&&amapLocation != null) { 7 if (amapLocation.getErrorCode() == 0) { 8 mListener.onLocationChanged(amapLocation);// 顯示系統小藍點 9 //定位成功回調信息,設置相關消息 10 amapLocation.getLocationType();//獲取當前定位結果來源,如網絡定位結果,詳見定位類型表 11 amapLocation.getLatitude();//獲取緯度 12 amapLocation.getLongitude();//獲取經度 13 amapLocation.getAccuracy();//獲取精度信息 14 amapLocation.getAddress();//地址,如果option中設置isNeedAddress為false,則沒有此結果,網絡定位結果中會有地址信息,GPS定位不返回地址信息。 15 amapLocation.getCountry();//國家信息 16 amapLocation.getProvince();//省信息 17 amapLocation.getCity();//城市信息 18 amapLocation.getDistrict();//城區信息 19 amapLocation.getStreet();//街道信息 20 amapLocation.getStreetNum();//街道門牌號信息 21 amapLocation.getCityCode();//城市編碼 22 amapLocation.getAdCode();//地區編碼 23 amapLocation.getAoiName();//獲取當前定位點的AOI信息 24 amapLocation.getBuildingId();//獲取當前室內定位的建築物Id 25 amapLocation.getFloor();//獲取當前室內定位的樓層 26 amapLocation.getGpsAccuracyStatus();//獲取GPS的當前狀態 27 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 28 Date date = new Date(amapLocation.getTime()); 29 df.format(date);//定位時間 30 addMarker(locationLatLng, desc);//添加大頭針 desc可為null 31 //根據locationLatLng地圖移至中心位置
aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(locationLatLng, 15)); 32 //反地理編碼搜索 33 regeocodeSearch(latitude, longitude, 3000); 34 } else { 35 String errText = "定位失敗," + amapLocation.getErrorCode()+ ": " + amapLocation.getErrorInfo(); 36 Log.e("AmapErr",errText); 37 } 38 } 39 } 40 /** 41 * 定位成功后往地圖上添加marker 42 * 此處設置兩個marker,來實現大頭針下添加小原點 43 * @param latLng 44 */ 45 private void addMarker(LatLng latLng, String desc) { 46 MarkerOptions markerOptions = new MarkerOptions(); 47 markerOptions.position(latLng); markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_fixed_location));//大頭針圖標 48 MarkerOptions options = new MarkerOptions(); 49 options.position(latLng); options.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_location));//大頭針下原點 50 options.anchor(0.5f,0.5f);//保證小藍點的中心對應經緯度位置 51 //markerOptions.icon(BitmapDescriptorFactory.defaultMarker()); 52 marker = aMap.addMarker(options);//先添加的在底層 53 locationMarker = aMap.addMarker(markerOptions); 54 } 55 注意:需要在系統 onDestroy() 方法中銷毀定位對象 56 @Override 57 protected void onDestroy() { 58 super.onDestroy(); 59 //在activity執行onDestroy時執行mMapView.onDestroy(),銷毀地圖 60 mMapView.onDestroy(); 61 // 銷毀定位對象 62 if(null != mlocationClient){ 63 mlocationClient.onDestroy();//銷毀定位客戶端,同時銷毀本地定位服務。 64 } 65 }
4.滑動地圖事件或調用aMap.moveCamera后回調
1 AMap.OnCameraChangeListener cameraChangeListener = new AMap.OnCameraChangeListener() { 2 /*設置定位圖標位置*/ 3 @Override 4 public void onCameraChange(CameraPosition cameraPosition) { 5 LatLng latLng = cameraPosition.target; 6 if (locationMarker != null) { 7 locationMarker.setPosition(latLng); 8 } 9 if (null != marker) 10 marker.setPosition(latLng); 11 } 12 /*更新地址列表*/ 13 @Override 14 public void onCameraChangeFinish(CameraPosition position) { 15 final LatLng latLng = position.target; 16 if (null != marker && !marker.isVisible()) 17 marker.setVisible(true);//設置可見性 18 //marker.setVisible(false); 19 adapter.index = 0; 20 regeocodeSearch(latLng.latitude, latLng.longitude, 3000); 21 } 22 };
5.反地理編碼設置
1 private void regeocodeSearch(double lat, double lng, float radius) { 2 LatLonPoint point = new LatLonPoint(lat, lng); 3 GeocodeSearch geocodeSearch = new GeocodeSearch(this); 4 geocodeSearch.setOnGeocodeSearchListener(this); 5 // 第一個參數表示一個Latlng,第二參數表示范圍多少米,第三個參數表示是火系坐標系還是GPS原生坐標系 6 RegeocodeQuery regeocodeQuery = new RegeocodeQuery(point, radius, GeocodeSearch.AMAP); 7 geocodeSearch.getFromLocationAsyn(regeocodeQuery); 8 } 9 @Override 10 public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int rCode) { 11 String preAdd = "";//地址前綴 12 if (1000 == rCode) { 13 RegeocodeAddress address = regeocodeResult.getRegeocodeAddress(); 14 StringBuffer stringBuffer = new StringBuffer(); 15 String area = address.getProvince();//省或直轄市 16 String loc = address.getCity();//地級市或直轄市 17 String subLoc = address.getDistrict();//區或縣或縣級市 18 String ts = address.getTownship();//鄉鎮 19 String thf = null;//道路 20 List<RegeocodeRoad> regeocodeRoads = address.getRoads();//道路列表 21 if (regeocodeRoads != null && regeocodeRoads.size() > 0) { 22 RegeocodeRoad regeocodeRoad = regeocodeRoads.get(0); 23 if (regeocodeRoad != null) { 24 thf = regeocodeRoad.getName(); 25 } 26 } 27 String subthf = null;//門牌號 28 StreetNumber streetNumber = address.getStreetNumber(); 29 if (streetNumber != null) { 30 subthf = streetNumber.getNumber(); 31 } 32 String fn = address.getBuilding();//標志性建築,當道路為null時顯示 33 if (area != null) { 34 stringBuffer.append(area); 35 preAdd += area; 36 } 37 if (loc != null && !area.equals(loc)) { 38 stringBuffer.append(loc); 39 preAdd += loc; 40 } 41 if (subLoc != null) { 42 stringBuffer.append(subLoc); 43 preAdd += subLoc; 44 } 45 if (ts != null) 46 stringBuffer.append(ts); 47 if (thf != null) 48 stringBuffer.append(thf); 49 if (subthf != null) 50 stringBuffer.append(subthf); 51 if ((thf == null && subthf == null) && fn != null && !subLoc.equals(fn)) 52 stringBuffer.append(fn + "附近"); 53 String ps = "poi"; 54 List<PoiItem> pois = address.getPois();//獲取周圍興趣點 55 if (pois != null && pois.size() > 0) { 56 for (int i = 0; i < pois.size(); i++) { 57 String title = pois.get(i).getTitle(); 58 String adName = pois.get(i).getAdName(); 59 String snippet = pois.get(i).getSnippet(); 60 LatLonPoint latLonPoint = pois.get(i).getLatLonPoint(); 61 double latitude = latLonPoint.getLatitude(); 62 double longitude = latLonPoint.getLongitude(); 63 ps = ps + ",title=" + title + ",adName=" + adName + ",snippet=" + snippet; 64 } 65 Log.e("PoiItem" + "pois.size=" ,pois.size() + "----" + ps); 66 } 67 } 68 }
本文為博主原創文章,請尊重版權,未經博主允許不得轉載,轉載請注明出處:http://www.cnblogs.com/details-666/p/AMap.html
另附定位類型對照表:
