1、到高德开放平台申请,获取key
高德开放平台:https://lbs.amap.com/
2、下载高德定位及地址搜索SDK:https://download.csdn.net/download/meixi_android/10845407
3、项目绑定高德SDK
(1)配置key
<meta-data android:name="com.amap.api.v2.apikey"android:value="c8f6c5070cd7fd3ece3b50b342218487" /><service android:name="com.amap.api.location.APSService"></service>
</application>
(2)activity实现定位接口
implements AMapLocationListener
//实现方法
@Override
public void onLocationChanged(AMapLocation aMapLocation) {}
(3)已知地址获取经纬度方法:
private void getLatlon(String cityName){GeocodeSearch geocodeSearch=new GeocodeSearch(this);geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {@Overridepublic void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {}@Overridepublic void onGeocodeSearched(GeocodeResult geocodeResult, int i) {if (i==1000){if (geocodeResult!=null && geocodeResult.getGeocodeAddressList()!=null &&geocodeResult.getGeocodeAddressList().size()>0){GeocodeAddress geocodeAddress = geocodeResult.getGeocodeAddressList().get(0);double latitude = geocodeAddress.getLatLonPoint().getLatitude();//纬度double longititude = geocodeAddress.getLatLonPoint().getLongitude();//经度String adcode= geocodeAddress.getAdcode();//区域编码Log.e("lgq地理编码", geocodeAddress.getAdcode()+"");Log.e("lgq纬度latitude",latitude+"");Log.e("lgq经度longititude",longititude+"");Log.i("lgq","dddwww===="+longititude);}else {Toast.makeText(MainActivity.this,"地名出错",Toast.LENGTH_SHORT).show();
// ToastUtils.show(context,"地址名出错");}}}});GeocodeQuery geocodeQuery=new GeocodeQuery(cityName.trim(),"29");geocodeSearch.getFromLocationNameAsyn(geocodeQuery);}
测试数据:
getLatlon("东莞市东城街道温塘横岭工业区二街38号");
结果:
12-12 13:51:52.555 21394-21394/com.tianxin.mapclient.liteapp E/lgq地理编码: 441900
12-12 13:51:52.555 21394-21394/com.tianxin.mapclient.liteapp E/lgq纬度latitude: 23.036034
12-12 13:51:52.556 21394-21394/com.tianxin.mapclient.liteapp E/lgq经度longititude: 113.816161
4、计算两个坐标的距离
LatLng latLng2=new LatLng(23.025845,113.752532);
LatLng latLng=new LatLng(23.025845,113.772532);
float distance = AMapUtils.calculateLineDistance(latLng,latLng2);
float qianmifload =(float) distance/1000;
Log.i("lgq","sss===="+round(qianmifload,2)+" 千米");
四舍五入到两位小数
public static float round(float v, int scale) {if (scale < 0)throw new IllegalArgumentException("The scale must be a positive integer or zero");BigDecimal bgNum1 = new BigDecimal(Float.toString(v));BigDecimal bgNum2 = new BigDecimal("1");return bgNum1.divide(bgNum2, scale, BigDecimal.ROUND_HALF_UP).floatValue();// return b.setScale(scale, BigDecimal.ROUND_HALF_UP).floatValue(); }