Android开发项目时常常会遇到定位这个功能,所以写了这篇博客,今天主要讲的高德地图的定位并获取相应信息。
首先导入高德的jar包
选中jar包右键点击 Add As Library, 在build.fradle中看到如下代码 表示导包成功
compile files('libs/AMap_Location_V3.0.0_20160922.jar')
之后到高德申请key值,登录打开控制台 点击创建应用,如图:
填写相应信息,
名称,PackageName:项目的包名,至于SHA1安全码可以这样获取,可以 Window+R 打开控制台 输入cmd点击确定
之后在弹框中完成以下操作就可以看到SHA1安全码了
上图的密钥库口令默认的是:android (注:输入口令是看不见的,输入完成Enter即可)
以上是测试版获取SHA1,发布版SHA1获取请看博客
输入完信息确定就可以看到key值了
AndroidManifest.xml中加入权限
<application>标签中添加Key值信息
MainActivity.Java
public class MainActivity extends AppCompatActivity implements AMapLocationListener { private AMapLocationClient locationClient = null; private AMapLocationClientOption locationOption = null; private TextView textView; private String[] strMsg; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.text_map); Location(); } @Override public void onLocationChanged(AMapLocation loc) { if (null != loc) { Message msg = mHandler.obtainMessage(); msg.obj = loc; msg.what = Utils.MSG_LOCATION_FINISH; mHandler.sendMessage(msg); } } Handler mHandler = new Handler() { public void dispatchMessage(android.os.Message msg) { switch (msg.what) { //定位完成 case Utils.MSG_LOCATION_FINISH: String result = ""; try { AMapLocation loc = (AMapLocation) msg.obj; result = Utils.getLocationStr(loc, 1); strMsg = result.split(","); Toast.makeText(MainActivity.this, "定位成功", Toast.LENGTH_LONG).show(); textView.setText("地址:" + strMsg[0] + "\n" + "经 度:" + strMsg[1] + "\n" + "纬 度:" + strMsg[1]); } catch (Exception e) { Toast.makeText(MainActivity.this, "定位失败", Toast.LENGTH_LONG).show(); } break; default: break; } }; }; public void Location() { // TODO Auto-generated method stub try { locationClient = new AMapLocationClient(this); locationOption = new AMapLocationClientOption(); // 设置定位模式为低功耗模式 locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving); // 设置定位监听 locationClient.setLocationListener(this); locationOption.setOnceLocation(true);//设置为单次定位 locationClient.setLocationOption(locationOption);// 设置定位参数 // 启动定位 locationClient.startLocation(); mHandler.sendEmptyMessage(Utils.MSG_LOCATION_START); } catch (Exception e) { Toast.makeText(MainActivity.this, "定位失败", Toast.LENGTH_LONG).show(); } }}
运行效果如图: