java - 如何添加显示您在谷歌地图上经过的路线的行
问题描述
我是 Android 新手,需要帮助。我正在开发一个应用程序,如 Runkeeper、Nike Running Club 等。所以我想知道如何添加显示你在谷歌地图上经过的路线的行。像那样。我已经从这里、这里和这里尝试了很多方法,但我无法理解它们。我知道我必须使用 onLocationChanged drawpolyline,但我不知道怎么做,也找不到任何解释。
这是我尝试这样做的方法,但它总是崩溃
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
TextView textAutoUpdateLocation;
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private Boolean mLocationPermissionGranted = false;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private static final float DEFAULT_ZOOM = 15f;
private PolylineOptions polylineOptions;
private ArrayList<LatLng> arrayPoints;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textAutoUpdateLocation = (TextView) findViewById(R.id.autoupdatelocation);
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
getLocationPermission();
}
private void initMap() {
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync((OnMapReadyCallback) this);
}
private void getDeviceLocation() {
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try {
if (mLocationPermissionGranted) {
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()), DEFAULT_ZOOM);
} else {
}
}
});
}
} catch (SecurityException e) {
}
}
private void moveCamera(LatLng latLng, float zoom) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (mLocationPermissionGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
}
this.init();
}
private void init() {
String coordinates[] = { "37.517180", "127.041268" };
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
LatLng position = new LatLng(lat, lng);
GooglePlayServicesUtil.isGooglePlayServicesAvailable(
MainActivity.this);
// 맵 위치이동.
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 15));
}
private void getLocationPermission() {
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(this.getApplicationContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(), COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
initMap();
} else {
ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
}
}
public void RequestPermissionResult(int requestCode, @NonNull String[]permissions, @NonNull int[]grantResults) {
switch (requestCode){
case LOCATION_PERMISSION_REQUEST_CODE:{
if (grantResults.length > 0) {
for (int i = 0; i<grantResults.length;i++){
if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
mLocationPermissionGranted=false;
return;
}
}
mLocationPermissionGranted=true;
initMap();
}
}
}
}
@Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
@Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
@Override
public void onLocationChanged(Location location) {
if (location != null) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions marker = new MarkerOptions();
marker.position(latLng);
mMap.addMarker(marker);
polylineOptions = new PolylineOptions();
polylineOptions.color(Color.RED);
polylineOptions.width(5);
arrayPoints.add(latLng);
polylineOptions.addAll(arrayPoints);
mMap.addPolyline(polylineOptions);
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(MainActivity.this,
"onConnectionFailed: \n" + connectionResult.toString(),
Toast.LENGTH_LONG).show();
}
}
请帮助并向我解释。预先感谢。
LOGCAT 08-03 13:51:02.605 20065-20065/? E/Zygote: isWhitelistProcess - 进程被列入白名单 08-03 13:51:03.125 20065-20065/com.mcarrow.myapplication E/zygote64: String#value 字段在 Android 版本上不存在 >= 6.0 08-03 13:51 :03.810 20065-20065/com.mcarrow.myapplication E/AndroidRuntime:致命异常:主进程:com.mcarrow.myapplication,PID:20065 java.lang.NullPointerException:尝试调用虚拟方法'boolean java.util.ArrayList.add (java.lang.Object)' 在 com.google.android.gms.internal.location.zzay.notifyListener (Unknown Source: 4) 在 com.google.android.gms 的 com.google.android.gms.common.api.internal.ListenerHolder.notifyListenerInternal(Unknown Source:8)。
解决方案
你还没有初始化arrayPoints
。在您的代码中,将arrayPoints
声明更改为此
private ArrayList<LatLng> arrayPoints; = new ArrayList<LatLng>();
推荐阅读
- winapi - WinAPI:您如何获得 UAC 为已签名二进制文件显示的“已验证发布者”?
- python-3.x - Selenium Webdriver (Python):我们可以为文本验证实现页面对象模型吗?
- configuration - 使用 Apache MINA 实现 JGIT TransportConfigCallback
- haproxy - HAProxy ACL 与文件中的用户代理不匹配
- sql - PostgreSQL 条件连接的性能 - 查询优化
- html - 如何使文本区域中的文本开始略低?
- reactjs - SPFx ListView 控件-“defaultSelection”不起作用
- php - 如何通过 WP CLI 取消 WP All Import?
- discord - 当事件发生在 Discord、OBS 更新中的浏览器源时,如何做到这一点?
- reactjs - How do I properly set up my useEffect so I don't receive a missing dependency warning?