Android集成高德地圖詳細(xì)介紹
最終效果是,本App展示地圖,點擊地圖導(dǎo)航,調(diào)轉(zhuǎn)三方實現(xiàn)導(dǎo)航。

1.邁出第一步,去創(chuàng)建自己的應(yīng)用key https://lbs.amap.com/
1.1創(chuàng)建完應(yīng)用之后,點擊頁面的{添加},要求填寫自己項目的信息

對于調(diào)試獲取SHA1的方法是:
1.打開cmd,
2、在彈出的控制臺窗口中輸入 cd .android 定位到 .android 文件夾:

3、繼續(xù)在控制臺輸入命令:
調(diào)試版本使用 debug.keystore,命令為:keytool -list -v -keystore debug.keystore
發(fā)布版本使用 apk 對應(yīng)的 keystore,命令為:keytool -list -v -keystore 自己apk的keystore路徑(可以找到文件直接拖進(jìn)來) 如下所示:

4.提示輸入密鑰庫密碼,調(diào)試版本默認(rèn)密碼是 android,發(fā)布版本的密碼是為 apk 的 keystore 設(shè)置的密碼。輸入密鑰后回車(如果沒設(shè)置密碼,可直接回車),此時可在控制臺顯示的信息中獲取 Sha1 值,如下圖所示:

以上完成彈窗填寫,最終獲取到key了。
2.第二大步,依然是準(zhǔn)備工作,要下載高德地圖相關(guān)的SDK https://lbs.amap.com/api/android-sdk/download
下載完畢之后,導(dǎo)入Android studio,我使用的是libs方式。

記得右鍵

此時你的bulid .gradle (app)會出現(xiàn) implementation files('libs\…),同時我們要在android 閉包中加入
sourceSets {
main{
jniLibs.srcDirs = ['libs']
}
}
3.在清單中加入
<!-- 定位service -->
<service android:name="com.amap.api.location.APSService" />
<meta-data
android:name="com.amap.api.v2.apikey"
android:value="上面第一步生成的key" />
4.準(zhǔn)備完成,開敲
導(dǎo)入權(quán)限
implementation ‘pub.devrel:easypermissions:3.0.0’
public class MapActivity extends AppCompatActivity implements AMapLocationListener, LocationSource {
//請求權(quán)限碼
private static final int REQUEST_PERMISSIONS = 9527;
//聲明AMapLocationClient類對象
public AMapLocationClient mLocationClient = null;
//聲明AMapLocationClientOption對象
public AMapLocationClientOption mLocationOption = null;
private MapView mapView;
//地圖控制器
private AMap aMap = null;
//位置更改監(jiān)聽
private LocationSource.OnLocationChangedListener mListener;
private FloatingActionButton mNavi;
private static final String PN_GAODE_MAP = "com.autonavi.minimap";// 高德地圖包名
private static final String PN_BAIDU_MAP = "com.baidu.BaiduMap"; // 百度地圖包名
private static final String PN_TENCENT_MAP = "com.tencent.map"; // 騰訊地圖包名
private String mStartAddress;
private double mLatitude;
private double mLongitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
initLocation();
initMap(savedInstanceState);
checkingAndroidVersion();
mNavi = findViewById(R.id.fab_poi);
mNavi.setOnClickListener(view -> {
Dialog bottomDialog = new Dialog(MapActivity.this, R.style.BottomDialog);
View contentView = LayoutInflater.from(MapActivity.this).inflate(R.layout.dialog_content_normal, null);
bottomDialog.setContentView(contentView);
ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
layoutParams.width = getResources().getDisplayMetrics().widthPixels;
contentView.setLayoutParams(layoutParams);
bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
TextView mCancel = contentView.findViewById(R.id.cancel);
TextView mBai = contentView.findViewById(R.id.bai);
TextView mGao = contentView.findViewById(R.id.gao);
mBai.setOnClickListener(view1 -> {
if (isGdMapInstalled(PN_BAIDU_MAP)) {
/*
* slat 起點緯度
* @param slon 起點經(jīng)度
* @param sname 起點名稱 可不填(0,0,null)
* @param dlat 終點緯度
* @param dlon 終點經(jīng)度
* @param dname 終點名稱 必填
* */
OpenMap.openBaiDuNavi(MapActivity.this,mLatitude,mLongitude,mStartAddress,
42.904823d,129.513228d, "延邊");
Toast.makeText(MapActivity.this, "有", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MapActivity.this, "暫未安裝此應(yīng)用", Toast.LENGTH_SHORT).show();
}
});
mGao.setOnClickListener(view12 -> {
if (isGdMapInstalled(PN_GAODE_MAP)) {
OpenMap.openGaoDeNavi(MapActivity.this,mLatitude,mLongitude,mStartAddress,
42.904823d,129.513228d, "延邊");
Toast.makeText(MapActivity.this, "有", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MapActivity.this, "暫未安裝此應(yīng)用", Toast.LENGTH_SHORT).show();
}
});
mCancel.setOnClickListener(view13 -> bottomDialog.dismiss());
bottomDialog.show();
});
}
/*
* 是否安裝了該應(yīng)用
* */
private static boolean isInstallPackage(String packageName) {
return new File("/data/data/" + packageName).exists();
}
private static boolean isGdMapInstalled(String packageName) {
return isInstallPackage(packageName);
}
/**
* 初始化地圖
*
* @param savedInstanceState
*/
private void initMap(Bundle savedInstanceState) {
mapView = findViewById(R.id.map_view);
//在activity執(zhí)行onCreate時執(zhí)行mMapView.onCreate(savedInstanceState),創(chuàng)建地圖
mapView.onCreate(savedInstanceState);
//初始化地圖控制器對象
aMap = mapView.getMap();
// 設(shè)置定位監(jiān)聽
aMap.setLocationSource(this);
// 設(shè)置為true表示顯示定位層并可觸發(fā)定位,false表示隱藏定位層并不可觸發(fā)定位,默認(rèn)是false
aMap.setMyLocationEnabled(true);
}
/**
* 初始化定位
*/
private void initLocation() {
//初始化定位
try {
//隱私政策合規(guī)
ServiceSettings.updatePrivacyShow(this, true, true);
ServiceSettings.updatePrivacyAgree(this, true);
mLocationClient = new AMapLocationClient(getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
//設(shè)置定位回調(diào)監(jiān)聽
mLocationClient.setLocationListener(this);
//初始化AMapLocationClientOption對象
mLocationOption = new AMapLocationClientOption();
//設(shè)置定位模式為AMapLocationMode.Hight_Accuracy,高精度模式。
mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//獲取最近3s內(nèi)精度最高的一次定位結(jié)果:
//設(shè)置setOnceLocationLatest(boolean b)接口為true,啟動定位時SDK會返回最近3s內(nèi)精度最高的一次定位結(jié)果。如果設(shè)置其為true,setOnceLocation(boolean b)接口也會被設(shè)置為true,反之不會,默認(rèn)為false。
mLocationOption.setOnceLocationLatest(true);
//設(shè)置是否返回地址信息(默認(rèn)返回地址信息)
mLocationOption.setNeedAddress(true);
//設(shè)置定位請求超時時間,單位是毫秒,默認(rèn)30000毫秒,建議超時時間不要低于8000毫秒。
mLocationOption.setHttpTimeOut(20000);
//關(guān)閉緩存機制,高精度定位會產(chǎn)生緩存。
mLocationOption.setLocationCacheEnable(false);
//給定位客戶端對象設(shè)置定位參數(shù)
mLocationClient.setLocationOption(mLocationOption);
}
/**
* 檢查Android版本
*/
private void checkingAndroidVersion() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//Android6.0及以上先獲取權(quán)限再定位
requestPermission();
} else {
//Android6.0以下直接定位
mLocationClient.startLocation();
}
}
/**
* 動態(tài)請求權(quán)限
*/
@AfterPermissionGranted(REQUEST_PERMISSIONS)
private void requestPermission() {
String[] permissions = {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
if (EasyPermissions.hasPermissions(this, permissions)) {
//true 有權(quán)限 開始定位
mLocationClient.startLocation();
} else {
//false 無權(quán)限
EasyPermissions.requestPermissions(this, "需要權(quán)限", REQUEST_PERMISSIONS, permissions);
}
}
/**
* 請求權(quán)限結(jié)果
*
* @param requestCode
* @param permissions
* @param grantResults
*/
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//設(shè)置權(quán)限請求結(jié)果
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
/**
* Toast提示
*
* @param msg 提示內(nèi)容
*/
private void showMsg(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
/**
* 接收異步返回的定位結(jié)果
*
* @param aMapLocation
*/
@Override
public void onLocationChanged(AMapLocation aMapLocation) {
if (aMapLocation != null) {
if (aMapLocation.getErrorCode() == 0) {
//地址
mStartAddress = aMapLocation.getAddress();
//緯度
mLatitude = aMapLocation.getLatitude();
//經(jīng)度
mLongitude = aMapLocation.getLongitude();
showMsg(mStartAddress);
mLocationClient.stopLocation();
//顯示地圖定位結(jié)果
if (mListener != null) {
mListener.onLocationChanged(aMapLocation);
}
} else {
//定位失敗時,可通過ErrCode(錯誤碼)信息來確定失敗的原因,errInfo是錯誤信息,詳見錯誤碼表。
Log.e("AmapError", "location Error, ErrCode:"
+ aMapLocation.getErrorCode() + ", errInfo:"
+ aMapLocation.getErrorInfo());
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
//銷毀定位客戶端,同時銷毀本地定位服務(wù)。
mLocationClient.onDestroy();
mapView.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
//在activity執(zhí)行onResume時執(zhí)行mMapView.onResume (),重新繪制加載地圖
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
//在activity執(zhí)行onPause時執(zhí)行mMapView.onPause (),暫停地圖的繪制
mapView.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//在activity執(zhí)行onSaveInstanceState時執(zhí)行mMapView.onSaveInstanceState (outState),保存地圖當(dāng)前的狀態(tài)
mapView.onSaveInstanceState(outState);
}
/**
* 激活定位
*/
@Override
public void activate(OnLocationChangedListener onLocationChangedListener) {
mListener = onLocationChangedListener;
if (mLocationClient == null) {
mLocationClient.startLocation();//啟動定位
}
}
/**
* 停止定位
*/
@Override
public void deactivate() {
mListener = null;
if (mLocationClient != null) {
mLocationClient.stopLocation();
mLocationClient.onDestroy();
}
mLocationClient = null;
}
}
public class OpenMap {
private static final String PN_GAODE_MAP = "com.autonavi.minimap";// 高德地圖包名
private static final String PN_BAIDU_MAP = "com.baidu.BaiduMap"; // 百度地圖包名
private static final String PN_TENCENT_MAP = "com.tencent.map"; // 騰訊地圖包名
/**
* 打開騰訊地圖
* params
*
* @param context
* @param slat 起點緯度
* @param slon 起點經(jīng)度
* @param sname 起點名稱 可不填(0,0,null)
* @param dlat 終點緯度
* @param dlon 終點經(jīng)度
* @param dname 終點名稱 必填
*/
public static void openTencentMap(Context context, double slat, double slon, String sname, double dlat, double dlon, String dname) {
String uriString = null;
StringBuilder builder = new StringBuilder("qqmap://map/routeplan?type=drive&policy=0&referer=zhongshuo");
if (slat != 0) {
builder.append("&from=").append(sname)
.append("&fromcoord=").append(slat)
.append(",")
.append(slon);
}
builder.append("&to=").append(dname)
.append("&tocoord=").append(dlat)
.append(",")
.append(dlon);
uriString = builder.toString();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setPackage(PN_TENCENT_MAP);
intent.setData(Uri.parse(uriString));
context.startActivity(intent);
}
/**
* 打開百度地圖導(dǎo)航功能(默認(rèn)坐標(biāo)點是高德地圖,需要轉(zhuǎn)換)
*
* @param context
* @param slat 起點緯度
* @param slon 起點經(jīng)度
* @param sname 起點名稱 可不填(0,0,null)
* @param dlat 終點緯度
* @param dlon 終點經(jīng)度
* @param dname 終點名稱 必填
*/
public static void openBaiDuNavi(Context context, double slat, double slon, String sname, double dlat, double dlon, String dname) {
String uriString = null;
//終點坐標(biāo)轉(zhuǎn)換 需要實現(xiàn)的在此處進(jìn)行坐標(biāo)轉(zhuǎn)換
double destination[] = gaoDeToBaidu(dlat, dlon);
dlat = destination[0];
dlon = destination[1];
StringBuilder builder = new StringBuilder("baidumap://map/direction?mode=driving&");
if (slat != 0) {
//起點坐標(biāo)轉(zhuǎn)換
double[] origin = gaoDeToBaidu(slat, slon);
slat = origin[0];
slon = origin[1];
builder.append("origin=latlng:")
.append(slat)
.append(",")
.append(slon)
.append("|name:")
.append(sname);
}
builder.append("&destination=latlng:")
.append(dlat)
.append(",")
.append(dlon)
.append("|name:")
.append(dname);
uriString = builder.toString();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setPackage(PN_BAIDU_MAP);
intent.setData(Uri.parse(uriString));
context.startActivity(intent);
}
/**
* 打開高德地圖導(dǎo)航功能
*
* @param context
* @param slat 起點緯度
* @param slon 起點經(jīng)度
* @param sname 起點名稱 可不填(0,0,null)
* @param dlat 終點緯度
* @param dlon 終點經(jīng)度
* @param dname 終點名稱 必填
*/
public static void openGaoDeNavi(Context context, double slat, double slon, String sname, double dlat, double dlon, String dname) {
String uriString = null;
StringBuilder builder = new StringBuilder("amapuri://route/plan?sourceApplication=maxuslife");
if (slat != 0) {
builder.append("&sname=").append(sname)
.append("&slat=").append(slat)
.append("&slon=").append(slon);
}
builder.append("&dlat=").append(dlat)
.append("&dlon=").append(dlon)
.append("&dname=").append(dname)
.append("&dev=0")
.append("&t=0");
uriString = builder.toString();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setPackage(PN_GAODE_MAP);
intent.setData(Uri.parse(uriString));
context.startActivity(intent);
}
private static double[] gaoDeToBaidu(double gd_lon, double gd_lat) {
double[] bd_lat_lon = new double[2];
double PI = 3.14159265358979324 * 3000.0 / 180.0;
double x = gd_lon, y = gd_lat;
double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * PI);
double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * PI);
bd_lat_lon[0] = z * Math.cos(theta) + 0.0065;
bd_lat_lon[1] = z * Math.sin(theta) + 0.006;
return bd_lat_lon;
}
}
到此這篇關(guān)于Android集成高德地圖詳細(xì)介紹的文章就介紹到這了,更多相關(guān)Android集成高德地圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android 帶箭頭的指引tipLayout實現(xiàn)示例代碼
本篇文章主要介紹了Android 帶箭頭的指引tipLayout實現(xiàn)示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01

