由於本人使用的是android studio,所以就以android studio為例。
1、在工程頂級 build.gradle 檔案中加入:
maven{
url "https://oss.sonatype.org/content/groups/public"
}
2、module build.gradle 檔案中新增依賴庫名稱:
implementation 'com.tencent.map:tencent-map-vector-sdk:4.3.5'
3、申請開發祕鑰,具體可參考開發檔案,此處就不演示。
https://lbs.qq.com/android_v1/guide-project-setup.html
4、在AndroidManifest.xml中新增許可權。
<uses-permission android:name="android.permission.INTERNET"/>
<!--檢查網路可用性-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- 存取WiFi狀態 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!--需要外部儲存寫許可權用於儲存地圖快取-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!--獲取 device id 辨別裝置-->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
5、在application中輸入開發祕鑰。
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".activity.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data android:name="TencentMapSDK" android:value="你的開發祕鑰" />
</application>
以下是定點陣圖片效果展示:
1、單獨實現定位功能。
建立一個MyMapActivity繼承BaseActivity,並實現一些父類別。
由於程式碼中有詳細的註釋,這裡就不一一解釋了。
public class MyMapActivity extends BaseActivity implements TencentLocationListener, LocationSource, TencentMapGestureListener {
@BindView(R.id.mv)
MapView mv;
private TencentLocationManager mLocationManager;
private TencentMap mTencentMap;
private TencentLocationRequest mRequest;
private OnLocationChangedListener mLocationChangedListener;
//將經緯度定義為全域性變數,方便導航功能使用
//為了方便導航,此處經緯度我寫固定的。可以視情況而定。
private double mLatitude = 23.112159;
private double mLongitude = 113.329768;
private Location mLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_map);
ButterKnife.bind(this);
initView();
checkPermission();
}
//檢測許可權
private void checkPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//申請許可權
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 222);//自定義的code
}
}
private void initView() {
mLocation = getLocation(this);
mLocationManager = TencentLocationManager.getInstance(this);
//建立定位請求
mRequest = TencentLocationRequest.create();
mTencentMap = mv.getMap();
//地圖上設定定位資料來源
mTencentMap.setLocationSource(this);
//設定當前位置可見
mTencentMap.setMyLocationEnabled(true);
mTencentMap.addTencentMapGestureListener(this);
mLocationManager.requestSingleFreshLocation(null, this, Looper.getMainLooper());
}
public Location getLocation(Context context) {
LocationManager locMan = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
Location location = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
location = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
return location;
}
/**
* 騰訊定位SDK位置變化回撥
*
* @param tencentLocation
* @param i
* @param s
*/
@Override
public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {
BJLog.i("onLocationChanged:" + tencentLocation.getAddress() + " i:" + i + " s:" + s);
if (i == TencentLocation.ERROR_OK && mLocationChangedListener != null) {
Location location = new Location(tencentLocation.getProvider());
//設定經緯度
location.setLatitude(tencentLocation.getLatitude());
location.setLongitude(tencentLocation.getLongitude());
//設定精度,這個值會被設定為定位點上表示精度的圓形半徑
location.setAccuracy(tencentLocation.getAccuracy());
//設定定位標的旋轉角度,注意 tencentLocation.getBearing() 只有在 gps 時才有可能獲取
location.setBearing((float) tencentLocation.getBearing());
//將位置資訊返回給地圖
mLocationChangedListener.onLocationChanged(location);
}
}
@Override
public void onStatusUpdate(String s, int i, String s1) {
}
@Override
public void activate(OnLocationChangedListener onLocationChangedListener) {
//這裡我們將地圖返回的位置監聽儲存為當前 Activity 的成員變數
mLocationChangedListener = onLocationChangedListener;
}
@Override
public void deactivate() {
//當不需要展示定位點時,需要停止定位並釋放相關資源
mLocationManager.removeUpdates(this);
mLocationManager = null;
mLocationManager = null;
mLocationManager = null;
}
@Override
public boolean onDoubleTap(float v, float v1) {
return false;
}
@Override
public boolean onSingleTap(float v, float v1) {
return false;
}
@Override
public boolean onFling(float v, float v1) {
return false;
}
@Override
public boolean onScroll(float v, float v1) {
return false;
}
@Override
public boolean onLongPress(float v, float v1) {
return false;
}
@Override
public boolean onDown(float v, float v1) {
return false;
}
@Override
public boolean onUp(float v, float v1) {
return false;
}
@Override
public void onMapStable() {
}
//建立地圖檢視之後,需要跟應用繫結生命週期,以保障地圖在應用的不同生命週期中,能夠正確地處理顯示和重新整理邏輯
@Override
protected void onStart() {
super.onStart();
mv.onStart();
}
@Override
protected void onResume() {
super.onResume();
mv.onResume();
}
@Override
protected void onStop() {
super.onStop();
mv.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
mv.onDestroy();
}
}
2、若想要實現導航功能,就拿我們經常使用的百度地圖、高德地圖、騰訊地圖而言吧。
首先自定義一個Dialog並設定為全域性變數。(這並不是唯一的方法,僅供參考)
private Dialog mMapDialog;
注:個人建議把自定義Dialog單獨寫出來,不要放在Activity中,在此為了方便閱讀,就放一起了。
3、定義一個initShareDialog()方法,彈出選擇地圖的視窗。
private void initShareDialog() {
// 可以使用這個: ll_dynamicDetail_bottom
mMapDialog = new Dialog(this, R.style.dialog_bottom_full);
mMapDialog.setCanceledOnTouchOutside(true); //手指觸碰到外界取消
mMapDialog.setCancelable(true); //可取消 為true
Window window = mMapDialog.getWindow(); // 得到dialog的表單
window.setGravity(Gravity.BOTTOM);
window.setWindowAnimations(R.style.share_animation);
View shareView = View.inflate(this, R.layout.dialog_maps, null); //獲取佈局檢視
TextView tvBaidu = shareView.findViewById(R.id.tv_baidu);
TextView tvTengxun = shareView.findViewById(R.id.tv_tengxun);
TextView tvGaode = shareView.findViewById(R.id.tv_gaode);
TextView tvCancel = shareView.findViewById(R.id.tv_cancel);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
//百度地圖
if (isAvilible(this, "com.baidu.BaiduMap")) {
tvBaidu.setVisibility(View.VISIBLE);
}
//高德地圖
if (isAvilible(this, "com.autonavi.minimap")) {
tvGaode.setVisibility(View.VISIBLE);
}
//騰訊地圖
if (isAvilible(this, "com.tencent.map")) {
tvTengxun.setVisibility(View.VISIBLE);
}
tvBaidu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Intent intent_baidu = Intent.getIntent("intent://map/direction?" +
"destination=latlng:" + mLatitude + "," + mLongitude +
"|name:我的終點" + //終點
"&mode=driving&" + //導航路線方式
"&src=appname#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
startActivity(intent_baidu); //啟動呼叫
mMapDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
});
tvGaode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//將功能Scheme以URI的方式傳入data
Uri uri = Uri.parse("androidamap://navi?sourceApplication=appname&poiname=fangheng&lat=" + mLatitude + "&lon=" + mLongitude + "&dev=1&style=2");
intent.setData(uri);
//啟動該頁面即可
startActivity(intent);
mMapDialog.dismiss();
}
});
tvTengxun.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//將功能Scheme以URI的方式傳入data
Uri uri = Uri.parse("qqmap://map/routeplan?type=drive&to=我的終點&tocoord=" + mLatitude + "," + mLongitude);
intent.setData(uri);
startActivity(intent);
mMapDialog.dismiss();
}
});
tvCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mMapDialog.dismiss();
}
});
//若手機沒有百度地圖、高德地圖、騰訊地圖,則提示使用者安裝。
if (!isAvilible(this,"com.tencent.map")
&& !isAvilible(this, "com.baidu.BaiduMap")
&& !isAvilible(this, "com.autonavi.minimap")){
Toast.makeText(this, "手機沒有地圖軟體,請安裝後重試!", Toast.LENGTH_SHORT).show();
return;
}
WindowManager.LayoutParams params = new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.WRAP_CONTENT);
window.setContentView(shareView, params);
window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);//設定橫向全螢幕
mMapDialog.show();
}
4、在定義一個isAvilible()方法,判斷手機中是否有某個程式的包。
private boolean isAvilible(Context context, String packageName) {
//獲取packagemanager
final PackageManager packageManager = context.getPackageManager();
//獲取所有已安裝程式的包資訊
List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
//用於儲存所有已安裝程式的包名
List<String> packageNames = new ArrayList<>();
//從pinfo中將包名字逐一取出,壓入pName list中
if (packageInfos != null) {
for (int i = 0; i < packageInfos.size(); i++) {
String packName = packageInfos.get(i).packageName;
packageNames.add(packName);
}
}
//判斷packageNames中是否有目標程式的包名,有TRUE,沒有FALSE
return packageNames.contains(packageName);
}
5、在initView()中加入以下程式碼,點選定位表便可實現。
//SDK版本4.3.5新增內建定位標點選回撥監聽
mTencentMap.setMyLocationClickListener(new TencentMap.OnMyLocationClickListener() {
@Override
public boolean onMyLocationClicked(LatLng latLng) {
initShareDialog();
return true;
}
});
下面是導航實現效果。
6、在style檔案中樣式:
<!-- 對話方塊樣式 -->
<style name="dialog_bottom_full" parent="android:style/Theme.Dialog">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:scrollHorizontally">true</item>
</style>
<!--彈出框動畫-->
<style name="share_animation" parent="android:Animation">
<item name="android:windowEnterAnimation">@anim/dialog_enter</item>
<item name="android:windowExitAnimation">@anim/dialog_exit</item>
</style>
7、Dialog的樣子:dialog_maps
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@drawable/round_share_bg"
android:paddingLeft="15dp"
android:paddingRight="15dp">
<TextView
android:id="@+id/tv_baidu"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"
android:text="百度地圖"
android:textColor="@color/color333"
android:textSize="18sp"
android:visibility="gone"/>
<TextView
android:id="@+id/tv_gaode"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"
android:text="高德地圖"
android:textColor="@color/color333"
android:textSize="18sp"
android:visibility="gone"/>
<TextView
android:id="@+id/tv_tengxun"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"
android:text="騰訊地圖"
android:textColor="@color/color333"
android:textSize="18sp"
android:visibility="gone"/>
<TextView
android:id="@+id/tv_cancel"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"
android:text="取消"
android:textColor="@color/dialog_submit_color"
android:textSize="18sp"/>
</LinearLayout>
以上就是定位與導航功能的實現,若有講得不好的地方,還請大佬們指出改正。