在我的Android项目中,我正在显示一张Google地图,其中包括我的位置(作为起点)和我的朋友位置(作为目的地)。 如此,位置数据将保存在firebase中。随着位置的实时变化,我回想起API在地图上显示更新。
但是问题是- 在地图上显示更新时,它会显示与上一个更新的路径方向。因此,所有路径都与先前的路径重叠。但是我想根据更新的位置重新生成地图。
这是显示的输出,当位置更新时,图片中的标记A是我的位置,更新后,它会与前一个标记一起生成新的标记A。
我已经清除了所有originMarker,destinationMarker和polylinePaths列表。但仍然无法正常工作。
这是我的 MapActivity.js
的代码public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, DirectionFinderListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
final Intent intent = getIntent();
myLat = intent.getStringExtra("my_lat");
myLong = intent.getStringExtra("my_long");
//saving to database starts
users = new ArrayList<>();
friends = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference("users");
//saving to database ends
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
btnFindPath = (Button) findViewById(R.id.btnFindPath);
etOrigin = (EditText) findViewById(R.id.etOrigin);
etDestination = (EditText) findViewById(R.id.etDestination);
}
private void sendRequest() {
originMarkers.clear();
destinationMarkers.clear();
polylinePaths.clear();
for(int i = 0; i < users.size(); i++) {
if(users.get(i).getEmail().equals(userEmail)) {
origin = users.get(i).getLatitude()+","+users.get(i).getLongitude();
}
}
String destination = etDestination.getText().toString();
try {
new DirectionFinder(this, origin, address).execute();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
try {
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
users.clear();
polylinePaths.clear();
originMarkers.clear();
destinationMarkers.clear();
for(DataSnapshot postSnapShot : dataSnapshot.getChildren()) {
User user = postSnapShot.getValue(User.class);
users.add(user);
}
for(int i = 0; i < users.size(); i++) {
if(users.get(i).getEmail().equals(userEmail) ) {
myLat = users.get(i).getLatitude();
myLong = users.get(i).getLongitude();
}
}
sendRequest();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
} catch (Exception e) {
}
mMap = googleMap;
LatLng hcmus = new LatLng(Double.parseDouble(myLat), Double.parseDouble(myLong));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(hcmus, 18));
originMarkers.add(mMap.addMarker(new MarkerOptions()
.title("My Location")
.position(hcmus)));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
@Override
public void onDirectionFinderStart() {
try {
progressDialog = ProgressDialog.show(this, "Please wait.",
"Finding direction..!", true);
progressDialog.setCancelable(true);
if (originMarkers != null) {
for (Marker marker : originMarkers) {
marker.remove();
}
}
if (destinationMarkers != null) {
for (Marker marker : destinationMarkers) {
marker.remove();
}
}
if (polylinePaths != null) {
for (Polyline polyline:polylinePaths ) {
polyline.remove();
}
}
} catch (Exception e) {
}
}
@Override
public void onDirectionFinderSuccess(List<Route> routes) {
progressDialog.dismiss();
polylinePaths = new ArrayList<>();
originMarkers = new ArrayList<>();
destinationMarkers = new ArrayList<>();
originMarkers.clear();
destinationMarkers.clear();
polylinePaths.clear();
for (Route route : routes) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16));
((TextView) findViewById(R.id.tvDuration)).setText(route.duration.text);
((TextView) findViewById(R.id.tvDistance)).setText(route.distance.text);
originMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue))
.title(route.startAddress)
.position(route.startLocation)));
destinationMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green))
.title(route.endAddress)
.position(route.endLocation)));
PolylineOptions polylineOptions = new PolylineOptions().
geodesic(true).
color(Color.BLUE).
width(10);
for (int i = 0; i < route.points.size(); i++)
polylineOptions.add(route.points.get(i));
polylinePaths.add(mMap.addPolyline(polylineOptions));
}
}
@Override
public void onStart() {
super.onStart();
try {
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
users.clear();
address.clear();
polylinePaths.clear();
originMarkers.clear();
destinationMarkers.clear();
for(DataSnapshot postSnapShot : dataSnapshot.getChildren()) {
User user = postSnapShot.getValue(User.class);
users.add(user);
}
for(int i = 0; i < users.size(); i++) {
if(users.get(i).getLatitude() != null && users.get(i).getLongitude()!= null) {
address.add(users.get(i).getLatitude()+","+users.get(i).getLongitude());
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
} catch (Exception e) {
}
}
}
这是执行API调用部分并获取绘制地图方向的代码-
DirectionFinder.java
public class DirectionFinder {
private static final String DIRECTION_URL_API = "direction API url";
private static final String GOOGLE_API_KEY = "my API key";
private DirectionFinderListener listener;
private String origin;
private ArrayList<String> destination;
public DirectionFinder(DirectionFinderListener listener, String origin, ArrayList<String> destination) {
this.listener = listener;
this.origin = origin;
this.destination = destination;
}
public void execute() throws UnsupportedEncodingException {
listener.onDirectionFinderStart();
for(int i=0;i<destination.size();i++)
new DownloadRawData().execute(createUrl(destination.get(i)));
}
private String createUrl(String des) throws UnsupportedEncodingException {
String urlOrigin = URLEncoder.encode(origin, "utf-8");
String urlDestination = URLEncoder.encode(des, "utf-8");
Log.e("#LOCATION_PATH:", DIRECTION_URL_API + "origin=" + urlOrigin + "&destination=" + urlDestination +"&alternatives=true&key=" + GOOGLE_API_KEY);
return DIRECTION_URL_API + "origin=" + urlOrigin + "&destination=" + urlDestination + "&alternatives=true&key=" + GOOGLE_API_KEY;
}
private class DownloadRawData extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String link = params[0];
try {
URL url = new URL(link);
InputStream is = url.openConnection().getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String res) {
try {
parseJSon(res);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void parseJSon(String data) throws JSONException {
if (data == null)
return;
List<Route> routes = new ArrayList<Route>();
JSONObject jsonData = new JSONObject(data);
JSONArray jsonRoutes = jsonData.getJSONArray("routes");
for (int i = 0; i < jsonRoutes.length(); i++) {
JSONObject jsonRoute = jsonRoutes.getJSONObject(i);
Route route = new Route();
JSONObject overview_polylineJson = jsonRoute.getJSONObject("overview_polyline");
JSONArray jsonLegs = jsonRoute.getJSONArray("legs");
JSONObject jsonLeg = jsonLegs.getJSONObject(0);
JSONObject jsonDistance = jsonLeg.getJSONObject("distance");
JSONObject jsonDuration = jsonLeg.getJSONObject("duration");
JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location");
JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location");
route.distance = new Distance(jsonDistance.getString("text"), jsonDistance.getInt("value"));
route.duration = new Duration(jsonDuration.getString("text"), jsonDuration.getInt("value"));
route.endAddress = jsonLeg.getString("end_address");
route.startAddress = jsonLeg.getString("start_address");
route.startLocation = new LatLng(jsonStartLocation.getDouble("lat"), jsonStartLocation.getDouble("lng"));
route.endLocation = new LatLng(jsonEndLocation.getDouble("lat"), jsonEndLocation.getDouble("lng"));
route.points = decodePolyLine(overview_polylineJson.getString("points"));
routes.add(route);
}
listener.onDirectionFinderSuccess(routes);
}
private List<LatLng> decodePolyLine(final String poly) {
int len = poly.length();
int index = 0;
List<LatLng> decoded = new ArrayList<LatLng>();
int lat = 0;
int lng = 0;
while (index < len) {
int b;
int shift = 0;
int result = 0;
do {
b = poly.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 = poly.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
decoded.add(new LatLng(
lat / 100000d, lng / 100000d
));
}
return decoded;
}
}
因此,我需要一个解决方案来解决重写地图问题并仅显示从我的起点到终点的一个方向路径。如果有人帮我解决这个问题,那就太好了。