想集成百度API定位需要完成以下步骤:
1:注册开发者
2:申请key
3:下载jar包
4:代码集成
先看下效果:
1:注册开发者
最好提前申请,审核需要1,2天
2:申请key
本人用的是Android Studio,所以用命令行查看SHA1码
3:下载jar包
只需下载"定位功能"的开发包即可
4:代码集成(详细可见官方讲解,以下代码以简洁实用为主)
package com.union.roid.testroid; import android.app.Activity; import android.os.Bundle; import android.util.Log; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; public class MainActivity extends Activity { public LocationClient mLocationClient = null; public BDLocationListener myListener = new MyLocationListener(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mLocationClient = new LocationClient(getApplicationContext());//声明LocationClient类 mLocationClient.registerLocationListener(myListener);//注册监听函数 LocationClientOption option = new LocationClientOption();//设置请求参数 option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//设置定位模式 option.setCoorType("bd09ll");//返回的定位结果是百度经纬度,默认值gcj02 option.setScanSpan(5000);//设置发起定位请求的间隔时间为5000ms option.setIsNeedAddress(true);//返回的定位结果包含地址信息 option.setNeedDeviceDirect(true);//返回的定位结果包含手机机头的方向 mLocationClient.setLocOption(option); mLocationClient.start();//启动请求 if (mLocationClient != null && mLocationClient.isStarted()) mLocationClient.requestLocation(); else Log.d("Location", "locClient is null or not started"); } public class MyLocationListener implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { if (location == null) return; StringBuffer sb = new StringBuffer(256); sb.append("time : "); sb.append(location.getTime()); sb.append("\nerror code : "); sb.append(location.getLocType()); sb.append("\nlatitude : "); sb.append(location.getLatitude()); sb.append("\nlontitude : "); sb.append(location.getLongitude()); sb.append("\nradius : "); sb.append(location.getRadius()); if (location.getLocType() == BDLocation.TypeGpsLocation) { sb.append("\nspeed : "); sb.append(location.getSpeed()); sb.append("\nsatellite : "); sb.append(location.getSatelliteNumber()); } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) { sb.append("\naddr : "); sb.append(location.getAddrStr()); } Log.v("--->", "========="); Log.v("--->", sb.toString()); } } }
时间: 2024-12-27 17:01:53