本文主要是介绍【高德地图】Android高德地图初始化定位并显示小蓝点,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
📖第3章 初始化定位并显示小蓝点
- ✅第1步:配置AndroidManifest.xml
- ✅第2步:设置定位蓝点
- ✅第3步:初始化定位
- ✅完整代码
✅第1步:配置AndroidManifest.xml
- 在application标签下声明
Service
组件
<service android:name="com.amap.api.location.APSService"></service>
- 声明权限
<!--地图相关--><uses-permission android:name="android.permission.INTERNET" /> <!-- 访问网络--><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- 网络定位 --><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- GPS定位 --><uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <!-- 访问WiFi网络定位 --><uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <!-- 获取wifi权限,进行网络定位 --><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><!-- 用于读数据 --><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- 用于写入缓存数据到扩展存储卡 --><uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" /> <!-- 用于申请调用A-GPS模块 --><uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <!-- 如果设置了target >= 28 如果需要启动后台定位则必须声明这个权限 --><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!--允许程序获取网络状态-->
- 设置高德Key,在上一步显示地图时已经完成
<meta-data android:name="com.amap.api.v2.apikey" android:value="key">//开发者申请的key </meta-data>
✅第2步:设置定位蓝点
//设置了定位的监听aMap.setLocationSource(this);//初始化定位蓝点样式类MyLocationStyle myLocationStyle;myLocationStyle = new MyLocationStyle();myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_MAP_ROTATE);//设置定位模式myLocationStyle.interval(2000); //只在连续定位模式下生效myLocationStyle.showMyLocation(true);//设置是否显示定位小蓝点// 将定位蓝点移动到屏幕中心myLocationStyle.anchor(0.5f, 0.5f).myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);aMap.setMyLocationStyle(myLocationStyle);aMap.setMyLocationEnabled(true);// 是否启动显示定位蓝点,默认是false
如果你不想显示蓝点精度圆圈,可以参考下面设置:
myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));//设置定位蓝点精度圆圈的边框颜色:无色myLocationStyle.radiusFillColor(Color.argb(0, 255, 255, 255)); // 设置精度圆圈背景色:透明无色
✅第3步:初始化定位
- 实现
LocationSource
和AMapLocationListener
接口,重写activate
、deactivate
和onLocationChanged
方法。
@Overridepublic void activate(OnLocationChangedListener onLocationChangedListener) {}@Overridepublic void deactivate() {}@Overridepublic void onLocationChanged(AMapLocation aMapLocation) {}
- 在
activate
中实现定位激活。
private OnLocationChangedListener mListener;//声明位置监听private AMapLocationClient mlocationClient;//声明定位客户端private AMapLocationClientOption mLocationOption;//声明定位参数配置选项/*** 激活定位*/@Overridepublic void activate(LocationSource.OnLocationChangedListener listener) {mListener = listener;if (mlocationClient == null) {//初始化定位try {mLocationOption = new AMapLocationClientOption();//初始化定位参数mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//设置为高精度定位模式mlocationClient = new AMapLocationClient(this);//声明定位客户端mlocationClient.setLocationListener(this);//设置定位回调监听mlocationClient.setLocationOption(mLocationOption);//设置定位参数mlocationClient.startLocation();//启动定位} catch (Exception e) {throw new RuntimeException(e);}}}
- 在
deactivate
中实现停止定位。
/*** 停止定位*/@Overridepublic void deactivate() {mListener = null;if (mlocationClient != null) {mlocationClient.stopLocation();mlocationClient.onDestroy();}mlocationClient = null;}
- 在
onLocationChanged
中监听定位回调。
private boolean isFirstLoc = true;//判断是否第一次定位private LatLng currentLatLng;//当前定位/*** 监听定位回调* @param aMapLocation*/@Overridepublic void onLocationChanged(AMapLocation aMapLocation) {if (mListener != null && aMapLocation != null) {if (aMapLocation.getErrorCode() == 0) {//定位成功回调信息,设置相关消息aMapLocation.getLocationType();//获取当前定位结果来源,如网络定位结果,详见官方定位类型表aMapLocation.getLatitude();//获取纬度aMapLocation.getLongitude();//获取经度aMapLocation.getAccuracy();//获取精度信息SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date date = new Date(aMapLocation.getTime());df.format(date);//定位时间aMapLocation.getAddress();//地址,如果option中设置isNeedAddress为false,则没有此结果,网络定位结果中会有地址信息,GPS定位不返回地址信息。aMapLocation.getCountry();//国家信息aMapLocation.getProvince();//省信息aMapLocation.getCity();//城市信息aMapLocation.getDistrict();//城区信息aMapLocation.getStreet();//街道信息aMapLocation.getStreetNum();//街道门牌号信息aMapLocation.getCityCode();//城市编码aMapLocation.getAdCode();//地区编码// 是否第一次定位if (isFirstLoc) {aMap.moveCamera(CameraUpdateFactory.zoomTo(16));//设置缩放级别currentLatLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()); //获取当前定位aMap.moveCamera(CameraUpdateFactory.changeLatLng(currentLatLng));//移动到定位点//点击定位按钮 能够将地图的中心移动到定位点mListener.onLocationChanged(aMapLocation);isFirstLoc = false;}} else {//显示错误信息Log.e("AmapError", "location Error, ErrCode:"+ aMapLocation.getErrorCode() + ", errInfo:"+ aMapLocation.getErrorInfo());}}}
**注意:**检查是否开启了应用定位权限和高精度定位
✅完整代码
MainActivity类:
package com.st.demo;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
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.MapsInitializer;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import java.text.SimpleDateFormat;
import java.util.Date;public class MainActivity extends AppCompatActivity implements LocationSource, AMapLocationListener {private MapView mMapView;//声明一个地图视图对象private AMap aMap;//声明一个地图图层private OnLocationChangedListener mListener;//声明位置监听private AMapLocationClient mlocationClient;//声明定位客户端private AMapLocationClientOption mLocationOption;//声明定位参数配置选项private boolean isFirstLoc = true;//判断是否第一次定位private LatLng currentLatLng;//当前定位@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//初始化地图定位initMap(savedInstanceState);}/*** 初始化地图* @param savedInstanceState*/private void initMap(Bundle savedInstanceState) {//隐私合规接口MapsInitializer.updatePrivacyShow(this, true, true);MapsInitializer.updatePrivacyAgree(this, true);AMapLocationClient.updatePrivacyAgree(this, true);AMapLocationClient.updatePrivacyShow(this, true, true);//获取地图视图对象mMapView = findViewById(R.id.map);//创建地图mMapView.onCreate(savedInstanceState);if (aMap == null) {aMap = mMapView.getMap();}//设置了定位的监听aMap.setLocationSource(this);//初始化定位蓝点样式类MyLocationStyle myLocationStyle;myLocationStyle = new MyLocationStyle();myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_MAP_ROTATE);//设置定位模式myLocationStyle.interval(2000); //只在连续定位模式下生效myLocationStyle.showMyLocation(true);//设置是否显示定位小蓝点// 将定位蓝点移动到屏幕中心myLocationStyle.anchor(0.5f, 0.5f).myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);aMap.setMyLocationStyle(myLocationStyle);aMap.setMyLocationEnabled(true);// 是否启动显示定位蓝点,默认是false。}/*** 激活定位*/@Overridepublic void activate(LocationSource.OnLocationChangedListener listener) {mListener = listener;if (mlocationClient == null) {//初始化定位try {mLocationOption = new AMapLocationClientOption();//初始化定位参数mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//设置为高精度定位模式mlocationClient = new AMapLocationClient(this);//声明定位客户端mlocationClient.setLocationListener(this);//设置定位回调监听mlocationClient.setLocationOption(mLocationOption);//设置定位参数mlocationClient.startLocation();//启动定位} catch (Exception e) {throw new RuntimeException(e);}}}/*** 停止定位*/@Overridepublic void deactivate() {mListener = null;if (mlocationClient != null) {mlocationClient.stopLocation();mlocationClient.onDestroy();}mlocationClient = null;}/*** 监听定位回调* @param aMapLocation*/@Overridepublic void onLocationChanged(AMapLocation aMapLocation) {if (mListener != null && aMapLocation != null) {if (aMapLocation.getErrorCode() == 0) {//定位成功回调信息,设置相关消息aMapLocation.getLocationType();//获取当前定位结果来源,如网络定位结果,详见官方定位类型表aMapLocation.getLatitude();//获取纬度aMapLocation.getLongitude();//获取经度aMapLocation.getAccuracy();//获取精度信息SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date date = new Date(aMapLocation.getTime());df.format(date);//定位时间aMapLocation.getAddress();//地址,如果option中设置isNeedAddress为false,则没有此结果,网络定位结果中会有地址信息,GPS定位不返回地址信息。aMapLocation.getCountry();//国家信息aMapLocation.getProvince();//省信息aMapLocation.getCity();//城市信息aMapLocation.getDistrict();//城区信息aMapLocation.getStreet();//街道信息aMapLocation.getStreetNum();//街道门牌号信息aMapLocation.getCityCode();//城市编码aMapLocation.getAdCode();//地区编码// 是否第一次定位if (isFirstLoc) {aMap.moveCamera(CameraUpdateFactory.zoomTo(16));//设置缩放级别currentLatLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()); //获取当前定位aMap.moveCamera(CameraUpdateFactory.changeLatLng(currentLatLng));//移动到定位点//点击定位按钮 能够将地图的中心移动到定位点mListener.onLocationChanged(aMapLocation);isFirstLoc = false;}} else {//显示错误信息Log.e("AmapError", "location Error, ErrCode:"+ aMapLocation.getErrorCode() + ", errInfo:"+ aMapLocation.getErrorInfo());}}}/*** 生命周期-onDestroy*/@Overrideprotected void onDestroy() {super.onDestroy();mMapView.onDestroy(); //销毁地图}/*** 生命周期-onResume*/@Overrideprotected void onResume() {super.onResume();mMapView.onResume(); //重新绘制加载地图}/*** 生命周期-onPause*/@Overrideprotected void onPause() {super.onPause();mMapView.onPause();//暂停地图的绘制}/*** 生命周期-onSaveInstanceState*/@Overrideprotected void onSaveInstanceState(Bundle outState) {super.onSaveInstanceState(outState);mMapView.onSaveInstanceState(outState);//保存地图当前的状态}
}
activity_main.xml布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><com.amap.api.maps.MapViewandroid:id="@+id/map"android:layout_width="match_parent"android:layout_height="match_parent"></com.amap.api.maps.MapView></LinearLayout>
AndroidManifest.xml中的权限相关省略,参考上面的。
✅第1,2章 Android搭建3D高德地图详细教
✅第 3 章 初始化定位并显示小蓝点
✅第 4 章Android高德地图绘制标记点Marker
✅第 5 章Android高德地图控件交互详细介绍
这篇关于【高德地图】Android高德地图初始化定位并显示小蓝点的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!