设置新航点后如何删除以前的折线... Google Map Android Studio
Posted
技术标签:
【中文标题】设置新航点后如何删除以前的折线... Google Map Android Studio【英文标题】:How to remove the previous polylines after setting a new waypoint... Google Map Android Studio 【发布时间】:2021-03-03 14:30:16 【问题描述】:我是 android Studio 的新手,我正在学习它几天。我试图实现一个地图,我们可以在其中设置两个标记来找到它们之间的路线。今天我试图在它们之间实现航路点。在地图中设置航点后,不会删除两个标记之间的旧路线,即从起点到终点。我正在获取旧路线以及从起点到航路点再到目的地的新路线。注意:我正在尝试实现两个航路点,因此如果我设置一个航路点,它将显示新路线(origin-waypoint-destination),如果我设置两个航路点,它将显示新路线(origin-waypoint-waypoint1-destination)删除旧的一个。
代码如下: 地图活动
''' 公共类 MapsActivity 扩展 FragmentActivity 实现 OnMapReadyCallback
private GoogleMap mMap;
ArrayList markerPoints = new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
@Override
public void onMapReady(GoogleMap googleMap)
mMap = googleMap;
LatLng chennai = new LatLng(13.04984411, 80.21033674);
//mMap.addMarker(new MarkerOptions().position(chennai).title("Marker in chennai"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(chennai,16));
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener()
@Override
public void onMapClick(LatLng latLng)
if (markerPoints.size() > 3)
markerPoints.clear();
mMap.clear();
// Adding new item to the ArrayList
markerPoints.add(latLng);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(latLng);
if (markerPoints.size() == 1)
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
else if (markerPoints.size() == 2)
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
else if(markerPoints.size() == 3)
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
else
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
// Add new marker to the Google Map Android API V2
mMap.addMarker(options);
// Checks, whether start and end locations are captured
if (markerPoints.size() >= 2)
LatLng origin = (LatLng) markerPoints.get(0);
LatLng dest = (LatLng) markerPoints.get(1);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
);
private String getDirectionsUrl(LatLng origin, LatLng dest)
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
//waypoints
String waypoints = "";
for(int i=2;i<markerPoints.size();i++)
LatLng point = (LatLng) markerPoints.get(i);
LatLng point1 = (LatLng) markerPoints.get(i);
if(i==2)
waypoints = "waypoints=optimize:true|via:";
waypoints += point.latitude + "%2C" + point.longitude + "%7C";
else if(i==3)
waypoints = "waypoints=optimize:true|via:";
waypoints += point.latitude + "%2C" + point.longitude + "%7C" + "via:" + point1.latitude + "%2C" + point1.longitude + "%7C";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + waypoints;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters + "&" + "key=AIzaSyBFrVlAmYqllaDiFZFfr62aLKZoOoP9xdo";
return url;
private class DownloadTask extends AsyncTask<String, Void, String>
@Override
protected String doInBackground(String... url)
String data = "";
try
data = downloadUrl(url[0]);
catch (Exception e)
Log.d("Background Task", e.toString());
return data;
@Override
protected void onPostExecute(String result)
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null)
sb.append(line);
data = sb.toString();
br.close();
catch (Exception e)
Log.d("Exception", e.toString());
finally
iStream.close();
urlConnection.disconnect();
return data;
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>>
// Parsing the data in non-ui thread
@Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData)
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
routes = parser.parse(jObject);
catch (Exception e)
e.printStackTrace();
return routes;
@Override
protected void onPostExecute(List<List<HashMap<String, String>>> result)
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
for (int i = 0; i < result.size(); i++)
points = new ArrayList<>();
lineOptions = new PolylineOptions();
List<HashMap<String, String>> path = result.get(i);
for (int j = 0; j < path.size(); j++)
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(String.valueOf(point.get("lat")));
double lng = Double.parseDouble(String.valueOf(point.get("lng")));
LatLng position = new LatLng(lat, lng);
points.add(position);
lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.RED);
lineOptions.geodesic(true);
if(lineOptions != null)
mMap.addPolyline(lineOptions);
DirectionJsonParser::
公共类DirectionsJSONParser
/** Receives a JSONObject and returns a list of lists containing latitude and longitude */
public List<List<HashMap<String,String>>> parse(JSONObject jObject)
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes;
JSONArray jLegs;
JSONArray jSteps;
try
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++)
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++)
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++)
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l <list.size();l++)
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
routes.add(path);
catch (JSONException e)
e.printStackTrace();
catch (Exception e)
return routes;
/**
* Method to decode polyline points
* Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
* */
private List decodePoly(String encoded)
List poly = new ArrayList();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len)
int b, shift = 0, result = 0;
do
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
return poly;
【问题讨论】:
【参考方案1】:第 1 步: 在 ArrayList markerpoints = new ArraylList(); 之后创建一个 =>
Polyline polylines;
第 2 步: 在 ParserTask OnPostExecute 内部 像这样分配 =>
polylines = mMap.addPolyline(lineOptions);
第 3 步:
//Inside OnMapReady
// The waypoints starts from 3
if(markerPoints.size() > 2
polylines.remove();
因此,当设置新标记时,这将删除以前的多段线,通过航路点创建一条新的多段线。
【讨论】:
以上是关于设置新航点后如何删除以前的折线... Google Map Android Studio的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Google Maps Android SDK 的折线上添加形状
如何自定义折线看起来像 Google Maps Android 应用程序?