在Android上使用百度地图SDK开发时,需要读取手机和GPS模块的定位坐标,然后在手机端的百度地图上显示出来,由于坐标系的不同,所以需要进行坐标的转换。我使用的是百度地图提供的API函数来进行转换。
1.在百度地图SDK开发包下载选择上“计算工具”
2.导入类接口
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.utils.CoordinateConverter;
3.坐标转换
LatLng ll = new LatLng(location.getLatitude(), location.getLongitude()); //获取手机定位坐标
CoordinateConverter converter = new CoordinateConverter()
.from(CoordinateConverter.CoordType.COMMON)
.coord(ll);
LatLng ll_bd = converter.convert();//将GCJ02坐标转换为百度坐标
GPS的话只需要将CoordinateConverter.CoordType.COMMON修改为CoordinateConverter.CoordType.GPS即可。
代码:
package com.example.phonelocation;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.utils.CoordinateConverter;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public LocationClient mLocationClient;
private TextView positionText;
private MapView mapView;
private BaiduMap baiduMap;
private boolean isFirstLocate = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationClient = new LocationClient(getApplicationContext());
mLocationClient.registerLocationListener(new MyLocationListener());
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.bmapView);
baiduMap = mapView.getMap();
baiduMap.setMyLocationEnabled(true);
positionText = (TextView) findViewById(R.id.position_text_view);
List<String> permissionList = new ArrayList<>();
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_PHONE_STATE)!=PackageManager.PERMISSION_DENIED){
permissionList.add(Manifest.permission.READ_PHONE_STATE);
}
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (!permissionList.isEmpty()){
String [] permission = permissionList.toArray(new String[permissionList.size()]);
ActivityCompat.requestPermissions(MainActivity.this, permission, 1);
}else {
requestLocation();
}
}
private void requestLocation( ){
initLocation();
mLocationClient.start();
}
private void initLocation( ){
LocationClientOption option = new LocationClientOption();
option.setScanSpan(2500);
option.setIsNeedAddress(true); //获取街道信息
option.setLocationMode(LocationClientOption.LocationMode.Device_Sensors); //指定了传感器模式,即只使用gps定位。去掉这句话可以使用流量定位
mLocationClient.setLocOption(option);
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
mLocationClient.stop();
mapView.onDestroy();
baiduMap.setMyLocationEnabled(false);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 1:
if (grantResults.length > 0){
for (int result : grantResults){
if (result != PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "必须同意所有权限才能使用程序",Toast.LENGTH_SHORT).show();
finish();
return;
}
}
requestLocation();
} else {
Toast.makeText(this,"发生未知错误",Toast.LENGTH_SHORT).show();
finish();
}
break;
default:
}
}
private void navigateTo(BDLocation location){
if (isFirstLocate){
LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
CoordinateConverter converter = new CoordinateConverter() //将GCJ02坐标转换为百度坐标
.from(CoordinateConverter.CoordType.COMMON)
.coord(ll);
LatLng ll_bd = converter.convert();
MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(ll_bd);
baiduMap.animateMapStatus(update);
update = MapStatusUpdateFactory.zoomTo(18f);
baiduMap.animateMapStatus(update);
isFirstLocate = false;
}
MyLocationData.Builder locationBuilder = new MyLocationData.Builder();
LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
CoordinateConverter converter = new CoordinateConverter() //将GCJ02坐标转换为百度坐标
.from(CoordinateConverter.CoordType.COMMON)
.coord(ll);
LatLng ll_bd = converter.convert();
locationBuilder.latitude(ll_bd.latitude);
locationBuilder.longitude(ll_bd.longitude);
MyLocationData locationData = locationBuilder.build();
baiduMap.setMyLocationData(locationData);
}
int timess=0;
public class MyLocationListener implements BDLocationListener{
@Override
public void onReceiveLocation(BDLocation Location) {
if (Location.getLocType() == BDLocation.TypeGpsLocation
|| Location.getLocType() == BDLocation.TypeNetWorkLocation){
navigateTo(Location);
}
int errora = Location.getLocType();
timess=timess+1;
StringBuffer currentPosition = new StringBuffer();
currentPosition.append("错误是:").append(errora).append(" times:").append
(timess).append("\n");
currentPosition.append("纬度: ").append(Location.getLatitude()).append("\n");
currentPosition.append("经度: ").append(Location.getLongitude()).append("\n");
currentPosition.append("国家:").append(Location.getCountry()).append("\n");
currentPosition.append("省:").append(Location.getProvince()).append("\n");
currentPosition.append("市:").append(Location.getCity()).append("\n");
currentPosition.append("区:").append(Location.getDistrict()).append("\n");
currentPosition.append("街道:").append(Location.getStreet()).append("\n");
positionText.setText(currentPosition);
}
}
}
参考资料:
http://lbsyun.baidu.com/index.php?title=androidsdk/guide/tool/coordinate
完整代码:
https://download.csdn.net/download/Emb_2333/12206247