我正在尝试删除之前添加的折线并在更改位置时重新绘制新的折线。我试过了两个
this.routeToDestination.setPoints(pointsToDestination)和 this.routeToDestination.remove()
但他们都没有奏效。
我关注How to draw a dynamic line (route) with Google Maps Android API v2但无法解决问题
@Override
public void onResume() {
super.onResume();
routeToDestination = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(location.getLatitude(), location.getLongitude()),
new LatLng(this.destinationLatitude, this.destinationLongitude))
.width(1)
.color(Color.DKGRAY)
);
}
@Override
public void onLocationChanged(Location location) {
List<LatLng> pointsToDestination = new ArrayList<LatLng>();
pointsToDestination.add(new LatLng(location.getLatitude(), location.getLongitude()));
pointsToDestination.add(new LatLng(destinationLatitude, destinationLongitude));
this.routeToDestination.setPoints(pointsToDestination);
}
}
答案 0 :(得分:34)
要删除折线,您只需使用API中所述的remove()方法。
//Add line to map
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(location.getLatitude(), location.getLongitude()),
new LatLng(this.destinationLatitude, this.destinationLongitude))
.width(1)
.color(Color.DKGRAY)
//Remove the same line from map
line.remove();
答案 1 :(得分:0)
在折线的地图活动中创建一个成员变量
Polyline polyline_final = null;
每次将折线添加到地图时,都会像这样分配地图的值
polyline_final = mMap.addPolyline(polylineOptions);
然后在创建新折线的同时删除以前的折线形式地图应用此条件之前 polyline_final = mMap.addPolyline(polylineOptions);
if (polylineOptions_final!=null)
{
polylineOptions_final.remove();
}
现在完成了
答案 2 :(得分:0)
最简单的方法
implementation 'com.akexorcist:google-direction-library:1.2.1'
使用这个库获取 Api 密钥
https://developers.google.com/maps/documentation/directions/get-api-key
您必须为此方向 api 启用计费方式。
https://console.cloud.google.com/projectselector2/billing/enable
在任何函数中设置此代码,但不在onmapready函数中
String serverKey = "AIzaSyCHEn5TVLk6xxuYn0-g11xxVzCu9eZiVbU";
GoogleDirection.
GoogleDirection.withServerKey(serverKey)
.from(new LatLng(30.677717,73.106812))
.to(new LatLng(31.345394,73.429810))
.transitMode(TransportMode.WALKING)
.unit(Unit.METRIC)
.execute(new DirectionCallback() {
@Override
public void onDirectionSuccess(@Nullable Direction direction) {
Log.d("eeeeee", direction.getStatus());
if(direction.isOK()) {
// Do something
Route route = direction.getRouteList().get(0);
Leg leg = route.getLegList().get(0);
ArrayList<LatLng> directionPositionList = leg.getDirectionPoint();
Log.d("eeeeee", directionPositionList.size()+"eeeeee");
if (polylineOptions_final!=null)
{
polylineOptions_final.remove();
}
PolylineOptions polylineOptions = DirectionConverter.createPolyline(getApplication(), directionPositionList, 10, Color.RED);
polylineOptions_final = mMap.addPolyline(polylineOptions);
} else {
// Do something
}
// Log.d("eeeeee"+direction.getGeocodedWaypointList().toString(), "onDirectionSuccess: ");
}
@Override
public void onDirectionFailure(@NonNull Throwable t) {
Toast.makeText(ClientMap.this, "d"+t.getMessage().toLowerCase(), Toast.LENGTH_SHORT).show();
}
});
new LatLng(31.345394,73.429810));