在安卓开发中,使用腾讯地图实现定位与导航功能
程序员文章站
2022-06-15 21:42:42
由于本人使用的是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.4'3、申请开发秘钥,具体...
由于本人使用的是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>
以上就是定位与导航功能的实现,若有讲得不好的地方,还请大佬们指出改正。
本文地址:https://blog.csdn.net/gg820796/article/details/108715258