/*** 判断定位服务是否开启** @param* @return true 表示开启*/ public static boolean isLocationEnabled(Context context) {int locationMode = 0;String locationProviders;if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {try {locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);} catch (Settings.SettingNotFoundException e) {e.printStackTrace();return false;}return locationMode != Settings.Secure.LOCATION_MODE_OFF;} else {locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);return !TextUtils.isEmpty(locationProviders);} } /*** 提示用户去开启定位服务**/ public static void toOpenGPS(Activity activity) {new AlertDialog.Builder(activity).setTitle("提示").setMessage("手机定位服务未开启,无法获取到您的准确位置信息,是否前往开启?").setNegativeButton("取消",null).setPositiveButton("去开启", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int i) {Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);activity.startActivity(intent);dialogInterface.dismiss();}}).show(); }
1、首先去高德开放平台注册应用
高德开放平台:https://lbs.amap.com/
2、点击 我的应用 ——>设置
注:SHA1获取方法:https://blog.csdn.net/meixi_android/article/details/72547966
3、下载SDK:https://lbs.amap.com/api/android-location-sdk/download/
4、添加配置文件
在工程的“ AndroidManifest.xml ”文件添加key和Service
<meta-data android:name="com.amap.api.v2.apikey"
android:value="afe02836f46f2c42f772ea621027e932" />
<service android:name="com.amap.api.location.APSService"></service>
5、代码实现
添加权限
<!--允许程序打开网络套接字-->
<uses-permission android:name="android.permission.INTERNET" />
<!--允许程序设置内置sd卡的写权限-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--允许程序获取网络状态-->
<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.READ_PHONE_STATE" />
<!--用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<!--用于访问GPS定位-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<!--用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<!--用于读取手机当前的状态-->
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<!--用于申请调用A-GPS模块-->
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/>
<!--获取运营商信息,用于支持提供运营商信息相关的接口-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--用于访问wifi网络信息,wifi信息会用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!--这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<!--用于访问网络,网络定位需要上网-->
<uses-permission android:name="android.permission.INTERNET" />
<!--用于读取手机当前的状态-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!--写入扩展存储,向扩展卡写入数据,用于写入缓存定位数据-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
acticity_main.xml布局文件
<com.amap.api.maps.MapView
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"></com.amap.api.maps.MapView>
MainActivity代码
package com.example.navi_map;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
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.UiSettings;
import com.amap.api.maps.model.LatLng;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity implements LocationSource, AMapLocationListener {
//AMap是地图对象
private AMap aMap;
private MapView mapView;
//声明AMapLocationClient类对象,定位发起端
private AMapLocationClient mLocationClient = null;
//声明mLocationOption对象,定位参数
public AMapLocationClientOption mLocationOption = null;
//声明mListener对象,定位监听器
private OnLocationChangedListener mListener = null;
//标识,用于判断是否只显示一次定位信息和用户重新定位
private boolean isFirstLoc = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取地图控件引用
mapView = (MapView) findViewById(R.id.map);
//在activity执行onCreate时执行mMapView.onCreate(savedInstanceState),实现地图生命周期管理
mapView.onCreate(savedInstanceState);
if (aMap == null) {
aMap = mapView.getMap();
//设置显示定位按钮 并且可以点击
UiSettings settings = aMap.getUiSettings();
aMap.setLocationSource(this);//设置了定位的监听
// 是否显示定位按钮
settings.setMyLocationButtonEnabled(true);
aMap.setMyLocationEnabled(true);//显示定位层并且可以触发定位,默认是flase
}
//开始定位
location();
}
private void location() {
//初始化定位
mLocationClient = new AMapLocationClient(getApplicationContext());
//设置定位回调监听
mLocationClient.setLocationListener(this);
//初始化定位参数
mLocationOption = new AMapLocationClientOption();
//设置定位模式为Hight_Accuracy高精度模式,Battery_Saving为低功耗模式,Device_Sensors是仅设备模式
mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置是否返回地址信息(默认返回地址信息)
mLocationOption.setNeedAddress(true);
//设置是否只定位一次,默认为false
mLocationOption.setOnceLocation(false);
//设置是否强制刷新WIFI,默认为强制刷新
mLocationOption.setWifiActiveScan(true);
//设置是否允许模拟位置,默认为false,不允许模拟位置
mLocationOption.setMockEnable(false);
//设置定位间隔,单位毫秒,默认为2000ms
mLocationOption.setInterval(2000);
//给定位客户端对象设置定位参数
mLocationClient.setLocationOption(mLocationOption);
//启动定位
mLocationClient.startLocation();
}
@Override
protected void onDestroy() {
super.onDestroy();
//在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理
mapView.onDestroy();
mLocationClient.stopLocation();//停止定位
mLocationClient.onDestroy();//销毁定位客户端。
}
@Override
protected void onResume() {
super.onResume();
//在activity执行onResume时执行mMapView.onResume (),实现地图生命周期管理
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
//在activity执行onPause时执行mMapView.onPause (),实现地图生命周期管理
mapView.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState),实现地图生命周期管理
mapView.onSaveInstanceState(outState);
}
@Override
public void onLocationChanged(AMapLocation aMapLocation) {
if (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(17));
//将地图移动到定位点
aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
//点击定位按钮 能够将地图的中心移动到定位点
mListener.onLocationChanged(aMapLocation);
//添加图钉
// aMap.addMarker(getMarkerOptions(amapLocation));
//获取定位信息
StringBuffer buffer = new StringBuffer();
buffer.append(aMapLocation.getCountry() + ""
+ aMapLocation.getProvince() + ""
+ aMapLocation.getCity() + ""
+ aMapLocation.getProvince() + ""
+ aMapLocation.getDistrict() + ""
+ aMapLocation.getStreet() + ""
+ aMapLocation.getStreetNum());
Toast.makeText(getApplicationContext(), buffer.toString(), Toast.LENGTH_LONG).show();
isFirstLoc = false;
}
} else {
//显示错误信息ErrCode是错误码,errInfo是错误信息,详见错误码表。
Log.e("AmapError", "location Error, ErrCode:"
+ aMapLocation.getErrorCode() + ", errInfo:"
+ aMapLocation.getErrorInfo());
Toast.makeText(getApplicationContext(), "定位失败", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void activate(OnLocationChangedListener onLocationChangedListener) {
mListener = onLocationChangedListener;
}
@Override
public void deactivate() {
mListener = null;
}
}
实现高德地图效果——定位、添加图标,画路线
demo链接:https://download.csdn.net/download/meixi_android/10848674
在线回复bug解决:qq1085220040
获取当前地理位置和经纬度实例:
1、实现定位监听接口
implements AMapLocationListener {
2、创建获取地理位置实例
//声明AMapLocationClient类对象,定位发起端private AMapLocationClient mLocationClient = null;//声明mLocationOption对象,定位参数public AMapLocationClientOption mLocationOption = null;//声明mListener对象,定位监听器private LocationSource.OnLocationChangedListener mListener = null;//标识,用于判断是否只显示一次定位信息和用户重新定位private boolean isFirstLoc = true;private void location() {//初始化定位mLocationClient = new AMapLocationClient(getApplicationContext());//设置定位回调监听mLocationClient.setLocationListener(this);//初始化定位参数mLocationOption = new AMapLocationClientOption();//设置定位模式为Hight_Accuracy高精度模式,Battery_Saving为低功耗模式,Device_Sensors是仅设备模式mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//设置是否返回地址信息(默认返回地址信息)mLocationOption.setNeedAddress(true);//设置是否只定位一次,默认为falsemLocationOption.setOnceLocation(false);//设置是否强制刷新WIFI,默认为强制刷新mLocationOption.setWifiActiveScan(true);//设置是否允许模拟位置,默认为false,不允许模拟位置mLocationOption.setMockEnable(false);//设置定位间隔,单位毫秒,默认为2000msmLocationOption.setInterval(30000);//给定位客户端对象设置定位参数mLocationClient.setLocationOption(mLocationOption);//启动定位mLocationClient.startLocation();}@Overridepublic void onLocationChanged(AMapLocation aMapLocation) {if (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) {//点击定位按钮 能够将地图的中心移动到定位点
// mListener.onLocationChanged(aMapLocation);//添加图钉// aMap.addMarker(getMarkerOptions(amapLocation));//获取定位信息StringBuffer buffer = new StringBuffer();buffer.append(aMapLocation.getCountry() + ""+ aMapLocation.getProvince() + ""+ aMapLocation.getCity() + ""+ aMapLocation.getProvince() + ""+ aMapLocation.getDistrict() + ""+ aMapLocation.getStreet() + ""+ aMapLocation.getStreetNum());addrlg = aMapLocation.getAddress();startlo =String.valueOf(aMapLocation.getLongitude()) ;dstartla = aMapLocation.getLatitude();dstartlo = aMapLocation.getLongitude();Log.i("lgq","谷歌等等-======"+dstartla+"......"+dstartlo);ShareUtil.sharedPstring("nowla", String.valueOf(dstartla));ShareUtil.sharedPstring("nowlo", String.valueOf(dstartlo));ShareUtil.sharedPstring("nowad", addrlg);isFirstLoc = false;}} else {//显示错误信息ErrCode是错误码,errInfo是错误信息,详见错误码表。Log.e("lgqAmapError", "location Error, ErrCode:"+ aMapLocation.getErrorCode() + ", errInfo:"+ aMapLocation.getErrorInfo());Toast.makeText(getApplicationContext(), "定位失败", Toast.LENGTH_LONG).show();}}}
3、执行
location();
设置显示中心位置,比例
aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLonPoint));//中心显示位置
aMap.moveCamera(CameraUpdateFactory.zoomTo(17));//比例
aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点,false表示隐藏定位蓝点并不进行定位,默认是false。
if (mMap != null && mLocation != null) {CameraUpdate newLatLngZoom = CameraUpdateFactory.newLatLngZoom(new LatLng(mLocation.getLatitude(), mLocation.getLongitude()), bili);mMap.moveCamera(newLatLngZoom);
}
地图刷新位置监听
aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {@Overridepublic void onCameraChange(CameraPosition cameraPosition) {}@Overridepublic void onCameraChangeFinish(CameraPosition cameraPosition) {
// addMarkerInScreenCenter();LatLng target = cameraPosition.target;LgqLog.e("刷新数据-=======");int ifyou = ShareUtil.getSharedInt("youss");if (ifyou==0){regeocodeSearch(target.latitude, target.longitude, 3000);}}});