i am creating a user tracker project , and what i want to do is to draw the user path on the map , the method that i used it's Polyline and this is the code
public void drawOnMap(ArrayList<LatLng> directionPoints) {
PolylineOptions rectLine = new PolylineOptions().width(5).color(Color.GREEN).geodesic(false);
rectLine.addAll(directionPoints);
mMap.addPolyline(rectLine);
}
but after about 500 polyline the map going to laggy and after 1900 the app crash
so is there is better solution
i found a solution and this is the right code
private Polyline polyline;
public void drawOnMap(ArrayList<LatLng> directionPoints) {
if(polyline == null)
{
PolylineOptions rectLine = new PolylineOptions().width(5).color(Color.GREEN).geodesic(false);
rectLine.addAll(directionPoints);
polyline = mMap.addPolyline(rectLine);
}else{
polyline.setPoints(directionPoints);
}
}
Related
After trying all the previous answers on StackOverflow I am posting this answer.
I am showing live location of a driver and a path from that location to a specific destination. What i want is to remove the old polyline soon the live location of driver changes but it's not hapening and it's increasing number of polylines.
Here is the code where i am removing the polyline but it's not working.
private void drawRouteOnMap(GoogleMap map, List<LatLng> positions) {
PolylineOptions options = new PolylineOptions().width(12).color(Color.GREEN).geodesic(true);
options.addAll(positions);
if (polyline != null) {
polyline.remove();
Log.e("Old Poly", "Removed");
}
Log.e("Poly", "Added");
polyline = mMap.addPolyline(options);
}
Try like this.
// decleare it globally
List<Polyline> polylines = new ArrayList<Polyline>();
private void drawRouteOnMap(GoogleMap map, List<LatLng> positions) {
PolylineOptions options = new PolylineOptions().width(12).color(Color.GREEN).geodesic(true);
for(Polyline polyline: polylines){
polyline.remove();
}
polylines.clear();
for(LatLng latlng: positions){
options.add(latlng);
polylines.add(mMap.addPolyline(options);
}
}
I have solved it myself. It is because that function was being called from another call due to which polyline instance was null. Solved it by saving polyline in SharedPrefrence and retrieving that value again on next call.
I'm trying to draw a polyline from what the Google Directions Api returns, the api has this field, overview_polyline, I'm assuming that this field contains the entire polyline so I was thinking why not draw the polyline from there, this is what I have in my JSON, from Google:
{
geocoded_waypoints: [
{},
{}
],
routes: [
{
bounds: {},
copyrights: "Dados do mapa ©2017 Google, Inst. Geogr. Nac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tFj]nUrEzC~[pTfLfG|EbB~KfCnTvDpmAxSzs#~LhOfDzOdFfOxGdY`O`k#zYnVzMlK|HrFjFbXj[rCbCvDfB|FfBbD^xRBlb#nBrIdArJvDfD|B|FzFvFzHnCbIDrCk#dA_A_#q#mHz#sAvAJ^f#r#n#x#UR_#fBGjET`S~#ro#pCpXpAfFp#dEhCnGtE#HXl#n#H^W|ASpShAbZxAtPp#~SjAzGZKdDStBd#x#dC#nEVz#HtAp#b#\OZ|AbBxDnFJf#"
},
summary: "A1",
warnings: [ ],
waypoint_order: [ ]
}
],
status: "OK"
}
How do I draw with that value?
This help me,you can use it..
Firstly create a google server key from google developer account
GoogleDirection.withServerKey(getResources().getString(R.string.SERVER_KEY))
.from(SourceLatlng)
.to(DestinationLatlng)
.execute(new DirectionCallback() {
#Override
public void onDirectionSuccess(Direction direction, String message) {
if (direction.isOK()) {
routeSucess2(direction, message,SourceLatlng,DestinationLatlng);
} else {
//selectedRawLine = ERROR;
}
}
#Override
public void onDirectionFailure(Throwable t) {
t.printStackTrace();
}
});
then draw a route using google direction
private void routeSucess2(Direction direction, String message,LatLng sourceLatlng,LatLng DestinationLng) {
for (Route route : direction.getRouteList()) {
PolylineOptions polyoptions = new PolylineOptions();
polyoptions.color(getResources().getColor(R.color.primary__dark));
polyoptions.width(5);
polyoptions.addAll(route.getOverviewPolyline().getPointList());
poly = googleMap.addPolyline(polyoptions);
poly.setClickable(true);
}
LatLngBounds.Builder latLngBuilder = new LatLngBounds.Builder();
if(sourceLatlng!=null)
latLngBuilder.include(sourceLatlng);
if(DestinationLng!=null)
latLngBuilder.include(DestinationLng);
try {
LatLngBounds bounds = latLngBuilder.build();
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds,
UiHelper.dpToPixel(getActivity(), 135));
googleMap.animateCamera(cu);
} catch (Exception e) {
e.printStackTrace();
}
}
This would help you.
#alb First you should parse lat,long from JSON. You can see this link:
https://developers.google.com/maps/documentation/directions/
Then you have to get lat, long values & put them in List<>.
After that you can use below code for draw polyline on map:
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
line = myMap.addPolyline(options);
I already have replied on similar question on below link
How to buffer a polyline in Android or draw a polygon around a polyline?
It will resolve your Issue probably
while loading google map on device i am receiving below screen sometimes.it comes on second load as shown below. otherwise it comes perfectly as normal google map with route I am using SupportmapFragment and get googleMap object as.
supportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_view_fragment);
below is code for displaying map in activity/fragment
public static void drawRouteIntoMap(final List<? extends MapHelper> position, final GoogleMap googleMap) {
/*List<MapHelper> position = new ArrayList<MapHelper>();
for (int i = lastPosition; i < maps.size(); i++) {
position.add(maps.get(i));
}*/
final LatLngBounds.Builder mapBounds = new LatLngBounds.Builder();
if (position.size() > 0 && Validator.isNotNull(googleMap)) {
googleMap.clear();
List<PolylineOptions> polylineOptionses = new ArrayList<PolylineOptions>();
PolylineOptions option = null;
Boolean lastPause = null;
for (MapHelper map : position) {
if (map.isPause()) {
if (Validator.isNull(lastPause) || !lastPause) {
option = new PolylineOptions().width(5).color(Color.rgb(255, 0, 155)).geodesic(true);
polylineOptionses.add(option);
}
mapBounds.include(new LatLng(map.getLatitude(),map.getLongitude()));
option.add(new LatLng(map.getLatitude(), map.getLongitude()));
} else {
if (Validator.isNull(lastPause) || lastPause) {
option = new PolylineOptions().width(5).color(Color.rgb(0, 179, 253)).geodesic(true);
polylineOptionses.add(option);
}
mapBounds.include(new LatLng(map.getLatitude(),map.getLongitude()));
option.add(new LatLng(map.getLatitude(), map.getLongitude()));
}
lastPause = map.isPause();
}
for (PolylineOptions options : polylineOptionses) {
googleMap.addPolyline(options);
}
if(Validator.isNotNull(option)){
//List<LatLng> points = option.getPoints();
googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
LatLng startPoint = new LatLng(position.get(0).getLatitude(), position.get(0).getLongitude());
googleMap.addMarker(new MarkerOptions().position(startPoint).title("start").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
mapBounds.include(startPoint);
LatLng endPoint = new LatLng(position.get(position.size() - 1).getLatitude(), position.get(position.size() - 1).getLongitude());
mapBounds.include(endPoint);
googleMap.addMarker(new MarkerOptions().position(endPoint).title("finish").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
googleMap.setPadding(15, 205, 10, 110);
googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(mapBounds.build(), 0));
//googleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(mapBounds.build(), 10));
googleMap.moveCamera(CameraUpdateFactory.zoomOut());
}
});
}
}
}
supportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
if (Validator.isNotNull(googleMap)) {
googleMap.setMyLocationEnabled(false);
googleMap.clear();
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
if (activity.preferences.isSaveScreen()) {
facebook.setChecked(false);
twitter.setChecked(false);
activity.replaceFragment(new FullMapFragment(), null);
}
if (!activity.preferences.isSaveScreen()) {
activity.preferences.setHistoryScreen(true);
activity.replaceFragment(new FullMapFragment(), null);
}
}
});
if (gps) {
nonGpsSummary.setVisibility(View.GONE);
List<HistoryMap> historyMaps = new ArrayList<HistoryMap>();
if (Validator.isNotNull(activity.preferences.getUserHistory().getHistoryMaps())) {
historyMaps.addAll(Arrays.asList(activity.preferences.getUserHistory().getHistoryMaps()));
}
if (historyMaps.size() > 0) {
if (Validator.isNotNull(googleMap)) {
drawRouteIntoMap(historyMaps, googleMap);
}
} else {
mapFrame.setVisibility(View.GONE);
}
} else {
gpsSummary.setVisibility(View.GONE);
}
}
}
});
this question is in relation with zoom over specific route google map.
by using that i get proper route with mapbounds but i m not getting why this screen is displaying.
i am not receiving cordinates 0.0 i debug that,api key is also proper.
You are calling moveCamera twice. The first one tries to move the camera but the second one doesn't wait for the first one to end and performs the zoom out.
This may not happen all the times and may behave differently on different devices.
The best option is to set a padding on your CameraUpdateFactory.newLatLngBounds(mapBounds.build(), 0) instead of 0
This problem occurs when your coordinates are not properly set. Make sure the coordinates that you are using is pointing in the land to get the maps correctly. Another possible reason is your API key is not working, try to generate new API key for this project.
For more information, check these related SO questions.
Android google maps return error and blue screen
Blue screen in Android Google Maps
The polyline which we will draw on the map is not similar to the polyline of google's map application.It is giving a nice 3d feel,can we draw the polyline similar to that polyline?.Is it possible to draw using 9-patch images?.Anyone please help?.
Hello this would help you, it helped me.
Firstly make the google api server key from Google developer account then add a dependency for google direction.
compile 'com.akexorcist:googledirectionlibrary:1.0.4'
then it check that feasible and shortest route between LatLongs.
use this code to check route is available or not.
GoogleDirection.withServerKey(getResources().getString(R.string.SERVER_KEY))
.from(SourceLatlng)
.to(DestinationLatlng)
.execute(new DirectionCallback() {
#Override
public void onDirectionSuccess(Direction direction, String message) {
if (direction.isOK()) {
DrawRoute(direction, message,SourceLatlng,DestinationLatlng);
} else {
//selectedRawLine = ERROR;
}
}
#Override
public void onDirectionFailure(Throwable t) {
t.printStackTrace();
}
});
Using this we can find that route is feasible or not
private void DrawRoute(Direction direction, String message,LatLng sourceLatlng,LatLng DestinationLng) {
for (Route route : direction.getRouteList()) {
PolylineOptions polyoptions = new PolylineOptions();
polyoptions.color(getResources().getColor(R.color.blackcolor));
polyoptions.width(5);
polyoptions.addAll(route.getOverviewPolyline().getPointList());
poly = googleMap.addPolyline(polyoptions);
poly.setClickable(true);
}
LatLngBounds.Builder latLngBuilder = new LatLngBounds.Builder();
if(sourceLatlng!=null)
latLngBuilder.include(sourceLatlng);
if(DestinationLng!=null)
latLngBuilder.include(DestinationLng);
try {
LatLngBounds bounds = latLngBuilder.build();
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds,
UiHelper.dpToPixel(getActivity(), 135));
googleMap.animateCamera(cu);
} catch (Exception e) {
e.printStackTrace();
}
}
Using this code we make polyline between two latLongs ...
previously I use GmapV2 from Android: How to draw route directions google maps API V2 from current location to destination. But now it's not work I got error about that class. How to fix that class?
This code will draw the line from origin to destination.
#Override
public void onDirectionSuccess(Direction direction, String rawBody) {
Log.d("Status", "Success");
Log.d("Direction", "" + direction);
mMap.addMarker(new MarkerOptions().position(origin));
mMap.addMarker(new MarkerOptions().position(destination));
if (waypoints != null){
for (int i = 0; i < waypoints.size(); i++){
mMap.addMarker(new MarkerOptions().position(waypoints.get(i)));
}
}
ArrayList<LatLng> directionPositionList = direction.getRouteList().get(0).getLegList().get(0).getDirectionPoint();
mMap.addPolyline(DirectionConverter.createPolyline(this, directionPositionList, 5, Color.BLUE));
Log.d("Status", "Success 2");
showRoute.setVisibility(View.GONE);
}