最近项目需要到高德定图定位,就此记录下简单集成思路
下载文件之只放了libs和主要代码文件
https://download.csdn.net/download/qq_38355313/10352613
第一步 登录高德地图开发者平台,创建应用
第二步 生成key(填写 SHA1 、包名信息)
调试模式的可以按照下面代码获取SHA1(不用电脑不同环境的调试SHA1都不一样,所以项目换了电脑或者开发环境地图就会显示不出来,修改一下SHA1就好)
/**
* 获取sha1
*
* @param context
* @return
*/
public String getSHA1(Context context) {
try {
PackageInfo info = context.getPackageManager().getPackageInfo(
context.getPackageName(), PackageManager.GET_SIGNATURES);
byte[] cert = info.signatures[0].toByteArray();
MessageDigest md = MessageDigest.getInstance("SHA1");
byte[] publicKey = md.digest(cert);
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < publicKey.length; i++) {
String appendString = Integer.toHexString(0xFF & publicKey[i])
.toUpperCase(Locale.US);
if (appendString.length() == 1)
hexString.append("0");
hexString.append(appendString);
hexString.append(":");
}
String result = hexString.toString();
return result.substring(0, result.length() - 1);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
第三步 下载并安装定位开发包和事例代码
http://lbs.amap.com/api/android-sdk/download
下载的demo如图
然后AS->New-Import Module (androidstudio项目中导入module就可以查看demo了)
第四步 集成到自己项目
1、 把demo中的jar包和so库复制到自己的项目libs包下添加依赖
以3.3.3版本的地图功能为例,解压后,得到一个 AMap3DMap_3.3.3_20160726.jar 文件和一个 armeabi 文件夹(文件夹中包含:libgdinamapv4sdk752.so、libgdinamapv4sdk752ex.so、libtbt3631.so、libwtbt144.so 四个so文件)
如果so库放在libs 记得在builder 下添加如下代码:
sourceSets {
main {
jniLibs.srcDirs = ['libs']
}
}
2、 配置key和添加权限
在AndroidManifest.xml的application标签中配置Key:
在AndroidManifest.xml中配置权限:
<meta-data
android:name="com.amap.api.v2.apikey"
android:value="您的Key"/>
//地图包、搜索包需要的基础权限
<!--允许程序打开网络套接字-->
<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" />
<!--允许程序访问CellID或WiFi热点来获取粗略的位置-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
3、配置XML布局文件 在布局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>
4、地图展示
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basicmap_activity);//设置对应的XML布局文件
MapView mapView = (MapView) findViewById(R.id.map);
mapView.onCreate(savedInstanceState);// 此方法必须重写
AMap aMap = mapView.getMap();
}
到此 如果看到地图能显示图文了,就证明集成成功了
一下是自己测试用的一个定位和地理编码用的activity(测试可行)
package com.nxm.amap_demo_guangqi.activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
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.location.AMapLocationQualityReport;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.nxm.amap_demo_guangqi.amap.AMapUtil;
import com.nxm.amap_demo_guangqi.R;
import com.nxm.amap_demo_guangqi.iflyutils.Utils;
import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
public class LocationActivity extends AppCompatActivity {
private TextView tvResult;
//定位相关
private AMapLocationClient locationClient = null;
private AMapLocationClientOption locationOption = null;
//地图相关
private MapView mapView;
private AMap aMap;
//地理编码相关
private GeocodeSearch geocoderSearch;
private ProgressDialog progDialog = null;
private Marker geoMarker;
private String addressName;
private String address = null;
public static String LOCALTION_ACTION = "LocationActivity_localtion";
public static String SEARCH_ACTION = "LocationActivity_search";
public static String NAVIGATION_ACTION = "LocationActivity_navigation";
public static String CLOSE_ACTION = "LocationActivity_navigation";
private MyBraoadCast myBraoadCast;
protected NaviLatLng mEndLatlng = null;
protected NaviLatLng mStartLatlng = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);// 此方法必须重写
initView();
//初始化
initLocation();
}
/**
* 初始化定位
*
* @author lzx
* @since 2018年4月11日 15:38:31
*/
private void initLocation() {
//初始化client
locationClient = new AMapLocationClient(this.getApplicationContext());
locationOption = getDefaultOption();
//设置定位参数
locationClient.setLocationOption(locationOption);
// 设置定位监听
locationClient.setLocationListener(locationListener);
geocoderSearch = new GeocodeSearch(this);
geocoderSearch.setOnGeocodeSearchListener(geocodeSearchListener);
progDialog = new ProgressDialog(this);
geoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
}
private void initView() {
tvResult = f(R.id.tvResult);
if (aMap == null) {
aMap = mapView.getMap();
}
myBraoadCast = new MyBraoadCast();
IntentFilter filter = new IntentFilter();
filter.addAction(LOCALTION_ACTION);
filter.addAction(SEARCH_ACTION);
filter.addAction(NAVIGATION_ACTION);
registerReceiver(myBraoadCast, filter);
}
/**
* 显示进度条对话框
*/
public void showDialog() {
progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDialog.setIndeterminate(false);
progDialog.setCancelable(true);
progDialog.setMessage("正在获取地址");
progDialog.show();
}
/**
* 隐藏进度条对话框
*/
public void dismissDialog() {
if (progDialog != null) {
progDialog.dismiss();
}
}
/**
* 响应地理编码
*/
public void getLatlon(final String name) {
showDialog();
GeocodeQuery query = new GeocodeQuery(name, "深圳市");// 第一个参数表示地址,第二个参数表示查询城市,中文或者中文全拼,citycode、adcode,
geocoderSearch.getFromLocationNameAsyn(query);// 设置同步地理编码请求
Log.d("sendBroadcast", "getLatlon: ");
}
private <T extends View> T f(int id) {
return findViewById(id);
}
/**
* 默认的定位参数
*
* @author hongming.wang
* @since 2.8.0
*/
private AMapLocationClientOption getDefaultOption() {
AMapLocationClientOption mOption = new AMapLocationClientOption();
mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选,设置定位模式,可选的模式有高精度、仅设备、仅网络。默认为高精度模式
mOption.setGpsFirst(false);//可选,设置是否gps优先,只在高精度模式下有效。默认关闭
mOption.setHttpTimeOut(30000);//可选,设置网络请求超时时间。默认为30秒。在仅设备模式下无效
mOption.setInterval(2000);//可选,设置定位间隔。默认为2秒
mOption.setNeedAddress(true);//可选,设置是否返回逆地理地址信息。默认是true
mOption.setOnceLocation(true);//可选,设置是否单次定位。默认是false
mOption.setOnceLocationLatest(false);//可选,设置是否等待wifi刷新,默认为false.如果设置为true,会自动变为单次定位,持续定位时不要使用
AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选, 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
mOption.setSensorEnable(false);//可选,设置是否使用传感器。默认是false
mOption.setWifiScan(true); //可选,设置是否开启wifi扫描。默认为true,如果设置为false会同时停止主动刷新,停止以后完全依赖于系统刷新,定位位置可能存在误差
mOption.setLocationCacheEnable(true); //可选,设置是否使用缓存定位,默认为true
return mOption;
}
/**
* 地址编译监听
*/
GeocodeSearch.OnGeocodeSearchListener geocodeSearchListener = new GeocodeSearch.OnGeocodeSearchListener() {
@Override
public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
}
@Override
public void onGeocodeSearched(GeocodeResult result, int rCode) {
dismissDialog();
if (rCode == AMapException.CODE_AMAP_SUCCESS) {
if (result != null && result.getGeocodeAddressList() != null
&& result.getGeocodeAddressList().size() > 0) {
GeocodeAddress address = result.getGeocodeAddressList().get(0);
if (address != null) {
aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
AMapUtil.convertToLatLng(address.getLatLonPoint()), 15));
geoMarker.setPosition(AMapUtil.convertToLatLng(address
.getLatLonPoint()));
addressName = "经纬度值:" + address.getLatLonPoint() + "\n位置描述:"
+ address.getFormatAddress();
tvResult.setText(addressName);
LatLonPoint LatLonPoint = address.getLatLonPoint();
mEndLatlng = new NaviLatLng(LatLonPoint.getLatitude(), LatLonPoint.getLongitude());
}
} else {
tvResult.setText("无结果");
}
} else {
tvResult.setText(rCode);
}
}
};
/**
* 定位监听
*/
AMapLocationListener locationListener = new AMapLocationListener() {
@Override
public void onLocationChanged(AMapLocation location) {
if (null != location) {
StringBuffer sb = new StringBuffer();
//errCode等于0代表定位成功,其他的为定位失败,具体的可以参照官网定位错误码说明
if (location.getErrorCode() == 0) {
sb.append("定位成功" + "\n");
sb.append("定位类型: " + location.getLocationType() + "\n");
sb.append("经 度 : " + location.getLongitude() + "\n");
sb.append("纬 度 : " + location.getLatitude() + "\n");
mStartLatlng = new NaviLatLng(location.getLatitude(), location.getLongitude());
sb.append("精 度 : " + location.getAccuracy() + "米" + "\n");
sb.append("提供者 : " + location.getProvider() + "\n");
sb.append("速 度 : " + location.getSpeed() + "米/秒" + "\n");
sb.append("角 度 : " + location.getBearing() + "\n");
// 获取当前提供定位服务的卫星个数
sb.append("星 数 : " + location.getSatellites() + "\n");
sb.append("国 家 : " + location.getCountry() + "\n");
sb.append("省 : " + location.getProvince() + "\n");
sb.append("市 : " + location.getCity() + "\n");
sb.append("城市编码 : " + location.getCityCode() + "\n");
sb.append("区 : " + location.getDistrict() + "\n");
sb.append("区域 码 : " + location.getAdCode() + "\n");
sb.append("地 址 : " + location.getAddress() + "\n");
sb.append("兴趣点 : " + location.getPoiName() + "\n");
//定位完成的时间
sb.append("定位时间: " + Utils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
//启动地图定位
moveToPosition(new LatLng(location.getLatitude(), location.getLongitude()));
} else {
//定位失败
sb.append("定位失败" + "\n");
sb.append("错误码:" + location.getErrorCode() + "\n");
sb.append("错误信息:" + location.getErrorInfo() + "\n");
sb.append("错误描述:" + location.getLocationDetail() + "\n");
}
sb.append("***定位质量报告***").append("\n");
sb.append("* WIFI开关:").append(location.getLocationQualityReport().isWifiAble() ? "开启" : "关闭").append("\n");
sb.append("* GPS状态:").append(getGPSStatusString(location.getLocationQualityReport().getGPSStatus())).append("\n");
sb.append("* GPS星数:").append(location.getLocationQualityReport().getGPSSatellites()).append("\n");
sb.append("****************").append("\n");
//定位之后的回调时间
sb.append("回调时间: " + Utils.formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");
//解析定位结果,
String result = sb.toString();
tvResult.setText(result);
} else {
tvResult.setText("定位失败,loc is null");
}
}
};
/**
* 移动到点
*
* @param latLng
*/
private void moveToPosition(LatLng latLng) {
changeCamera(
//v 比例 v1:
CameraUpdateFactory.newCameraPosition(new CameraPosition(
latLng, 14, 0, 0)));
aMap.clear();
aMap.addMarker(new MarkerOptions().position(latLng)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}
/**
* 根据动画按钮状态,调用函数animateCamera或moveCamera来改变可视区域
*/
private void changeCamera(CameraUpdate update) {
aMap.moveCamera(update);
}
/**
* 获取GPS状态的字符串
*
* @param statusCode GPS状态码
* @return
*/
private String getGPSStatusString(int statusCode) {
String str = "";
switch (statusCode) {
case AMapLocationQualityReport.GPS_STATUS_OK:
str = "GPS状态正常";
break;
case AMapLocationQualityReport.GPS_STATUS_NOGPSPROVIDER:
str = "手机中没有GPS Provider,无法进行GPS定位";
break;
case AMapLocationQualityReport.GPS_STATUS_OFF:
str = "GPS关闭,建议开启GPS,提高定位质量";
break;
case AMapLocationQualityReport.GPS_STATUS_MODE_SAVING:
str = "选择的定位模式中不包含GPS定位,建议选择包含GPS定位的模式,提高定位质量";
break;
case AMapLocationQualityReport.GPS_STATUS_NOGPSPERMISSION:
str = "没有GPS定位权限,建议开启gps定位权限";
break;
}
return str;
}
/**
* 方法必须重写
*/
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
// 启动定位
locationClient.startLocation();
}
/**
* 方法必须重写
*/
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
/**
* 方法必须重写
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
/**
* 方法必须重写
*/
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
//注销广播
unregisterReceiver(myBraoadCast);
}
public static void startLocationActivity(Context context) {
Intent intent = new Intent(context, LocationActivity.class);
intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
private class MyBraoadCast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("IflyService", "action:" + intent.getAction());
Log.d("sendBroadcast", "onReceive:");
if (LOCALTION_ACTION.equals(intent.getAction())) {
//退出定位功能
finish();
} else if (SEARCH_ACTION.equals(intent.getAction())) {
//根据地址搜到目标
String address = intent.getStringExtra("address");
if (null != address) {
if (!address.trim().isEmpty() || address.trim().length() > 2)
getLatlon(address);
}
} else if (NAVIGATION_ACTION.equals(intent.getAction())) {
Log.d("sendBroadcast", "startActivity");
//启动导航功能
if (mEndLatlng != null && mStartLatlng != null) {
Intent intent1 = new Intent(LocationActivity.this, IflyVoiceNaviActivity.class);
intent1.putExtra("mEndLatlng", mEndLatlng);
intent1.putExtra("mStartLatlng", mStartLatlng);
Log.d("sendBroadcast", "startActivity");
startActivity(intent1);
}
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.nxm.amap_demo_guangqi.activity.LocationActivity">
<com.amap.api.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"></com.amap.api.maps.MapView>
<TextView
android:id="@+id/tvResult"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="@color/colorAccent" />
</RelativeLayout>