How to make a Marker traverse a Polyline in Java? - java

I'm working on an app, similar to uber, didi, etc. I have a problem when making the animations of the vehicles (going from point A to point B), I found this code on Internet and it works quite well:
public void animateMarker(final LatLng startPosition, final LatLng toPosition,final boolean hideMarke) {
final Handler handler = new Handler();
final Marker m = map.addMarker(new MarkerOptions()
.position(startPosition)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.bus2))
.title("Camión"));
final long start = SystemClock.uptimeMillis();
Projection proj = map.getProjection();
Point startPoint = proj.toScreenLocation(m.getPosition());
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
final long duration = 5000;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed
/ duration);
double lng = t * toPosition.longitude + (1 - t)
* startLatLng.longitude;
double lat = t * toPosition.latitude + (1 - t)
* startLatLng.latitude;
m.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
if (hideMarke) {
m.setVisible(false);
} else {
m.setVisible(true);
}
}
}
});
markers_animations.add(m);
}
I have this method that is in charge of passing it the positions of a list with all the coordinates that I require for the Polylines:
private void controlAnimaciones(List<LatLng> ruta) {
for (int i=0; i<ruta.size()-1; i++) {
if (i<ruta.size()) {
animateMarker3(ruta.get(i), ruta.get(i+1), true);
}
}
}
It does what I expected it to do, if it moves the marker from point A to point B, but, just by iterating the list, I don't know how to explain it, there are many markers that move only from one element of the list to the next and after that they stop. What I want to do is to achieve that a single marker can move through all the points of the list, I have been trying in some ways with the code I got from the internet, to try to understand it, but I have not had much success. How could I do it?

Currently in your posted code, animateMarker creates a marker for each "segment" of the polyline - it starts and stops the movement of the marker along the one segment, and it does this asynchronously. This would have the effect of a marker created (simultaneously) at the start of every segment and each one animated in parallel (nearly). Not what you want.
So you have two things to change:
Create the marker once at the start of the first segment.
Continue the animation of the second and later segments after the first (or previous leg completes.)
Easy way to do the above is to modify the animateMarker to accept the list of points rather than a single point. The list of points is your polyline (ruta).
I made some comments where the method was modified from your original.
public void animateMarker(List<LatLng> pts,final boolean hideMarker) {
// Simple check to make sure there are enough points in the list.
if (pts.size() <= 1) {
// need at least two points.
return;
}
final Handler handler = new Handler();
// Use first point in list as start.
final Marker m = mMap.addMarker(new MarkerOptions()
.position(pts.get(0))
.title("Camión"));
Projection proj = mMap.getProjection();
Point startPoint = proj.toScreenLocation(m.getPosition());
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
final long duration = 5000;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
// start at first segment
private int segment = 0;
// initial start time
long start = SystemClock.uptimeMillis();
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed
/ duration);
// Use next point in list as destination
double lng = t * pts.get(segment+1).longitude + (1 - t)
* pts.get(segment).longitude;
double lat = t * pts.get(segment+1).latitude + (1 - t)
* pts.get(segment).latitude;
m.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
// check if to move to next segment (or done)
else if (segment < (pts.size()-2)) {
// move to next segment
segment++;
start = SystemClock.uptimeMillis();
handler.postDelayed(this,16);
} else {
if (hideMarker) {
m.setVisible(false);
} else {
m.setVisible(true);
}
}
}
});
markers_animations.add(m);
}
And to call the animation with your list just modify your
private void controlAnimaciones(List<LatLng> ruta) {
animateMarker(ruta, true);
}
And this is the result.
(Note that the "velocity" of the marker movement is dependent on the length of the segment. Since the duration is fixed per segment, longer segments would make the marker appear to move faster. You could change this to a constant velocity for any segment by changing duration as a function of the distance between the two points.)
Note that the animaterMarker supports multiple animations naturally without modification. So in this example the map onMapClickListener invokes controlAnimaciones on every map click which was done every few seconds for demonstration purposes.
Hope this helps!

Related

Animate a car on google map on firebase change event [duplicate]

What is the best way to animate markers on Google Maps using v2 API?
I am working on a map-centered game where I track locations of people and display them on the map for each other to see. As people move, I want to animate a marker from his current to his latest position. Every person has a direction, so I need to rotate the marker appropriately.
What is the best way to do it using the new Google Maps API?
Some Google engineers have provided a nice demo video with some elegant sample code about how to animate markers from a starting point to an ending point, for all various versions of Android:
The relevant code is here:
https://gist.github.com/broady/6314689
And a nice demo video of all of it in action.
http://youtu.be/WKfZsCKSXVQ
OLD DEPRECATED ANSWER BELOW
In the documentation, it is mentioned that Marker Icons cannot be changed:
Icon
A bitmap that's displayed for the marker. If the icon is left unset, a default icon is displayed. You can specify an alternative coloring of the default icon using defaultMarker(float). You can't change the icon once you've created the marker.
Google Maps API v2 Documentation
You're going to have to keep track of specific markers, perhaps using a method similar to that described here: Link a Marker to an Object, then figure out which marker you need to update. Call .remove() on the marker, then create a rotated image depending on the "direction" you want, create a new Marker with that image, and add the new Marker to the map.
You do not need to "clear" the map, simply remove the marker you want to modify, create a new one, then add it back to the map.
Unfortunately, the new Maps API is not very flexible yet. Hopefully Google continues to improve upon it.
Full Example for DiscDev's answer (Above):
LatLng fromLocation = new LatLng(38.5, -100.4); // Whatever origin coordinates
LatLng toLocation = new LatLng(37.7, -107.7); // Whatever destination coordinates
Marker marker = mMap.addMarker(new MarkerOptions().position(firstLocation));
MarkerAnimation.animateMarkerToICS(marker, toLocation, new LatLngInterpolator.Spherical());
And for those of you who uses GPS / or any position provider that receives location updates:
Marker ourGlobalMarker;
// We've got a location from some provider of ours, now we can call:
private void updateMarkerPosition(Location newLocation) {
LatLng newLatLng = new LatLng(newLocation.getLatitude(), newLocation.getLongitude());
if(ourGlobalMarker == null) { // First time adding marker to map
ourGlobalMarker = mMap.addMarker(new MarkerOptions().position(newLatLng));
}
else {
MarkerAnimation.animateMarkerToICS(ourGlobalMarker, newLatLng, new LatLngInterpolator.Spherical());
}
}
IMPORTANT:
Within 1MarkerAnimation.java If the animation duration is set to X,
and you are receiving location updates in a rate smaller then X, multiple animations will be triggered, and you might see the marker animation flickers a bit (which is not a nice user experience).
To avoid this, the animationMarkerToICS method (I took here animationMarkerToICS for example), should look something like this,
full method implementation:
private static Animator animator; // MAKING ANIMATOR GLOBAL INSTEAD OF LOCAL TO THE STATIC FUNCTION
...
// Ice Cream Sandwich compatible
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void animateMarkerToICS(Marker marker, LatLng finalPosition, final LatLngInterpolator latLngInterpolator) {
TypeEvaluator<LatLng> typeEvaluator = new TypeEvaluator<LatLng>() {
#Override
public LatLng evaluate(float fraction, LatLng startValue, LatLng endValue) {
return latLngInterpolator.interpolate(fraction, startValue, endValue);
}
};
Property<Marker, LatLng> property = Property.of(Marker.class, LatLng.class, "position");
// ADD THIS TO STOP ANIMATION IF ALREADY ANIMATING TO AN OBSOLETE LOCATION
if(animator != null && animator.isRunning()) {
animator.cancel();
animator = null;
}
animator = ObjectAnimator.ofObject(marker, property, typeEvaluator, finalPosition);
animator.setDuration((long) ANIMATION_DURATION);
animator.start();
}
Enjoy.
Marker has a new function added as of rev.7 of API v2. Marker.setIcon, so you can use multiple icons to show direction.
//Your code
double bearing = 0.0;
bearing = getBearing(new LatLng(
currentPosition.latitude
,currentPosition.longitude),
new LatLng(
nextPosition.latitude,
nextPosition.longitude));
bearing -= 90;
CameraPosition cameraPosition = new CameraPosition
.Builder()
.target(new LatLng(nextPosition.latitude, nextPosition.longitude))
.bearing((float) bearing)
.zoom(ZOOM_LEVEL).build();
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), 5000, null);
animatedMarker(currentPosition,nextPosition,busMarker);
//Method for finding bearing between two points
private float getBearing(LatLng begin, LatLng end) {
double lat = Math.abs(begin.latitude - end.latitude);
double lng = Math.abs(begin.longitude - end.longitude);
if (begin.latitude < end.latitude && begin.longitude < end.longitude)
return (float) (Math.toDegrees(Math.atan(lng / lat)));
else if (begin.latitude >= end.latitude && begin.longitude < end.longitude)
return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 90);
else if (begin.latitude >= end.latitude && begin.longitude >= end.longitude)
return (float) (Math.toDegrees(Math.atan(lng / lat)) + 180);
else if (begin.latitude < end.latitude && begin.longitude >= end.longitude)
return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 270);
return -1;
}
private void animatedMarker(final LatLng startPosition,final LatLng nextPosition,final Marker mMarker)
{
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final Interpolator interpolator = new AccelerateDecelerateInterpolator();
final float durationInMs = 3000;
final boolean hideMarker = false;
handler.post(new Runnable() {
long elapsed;
float t;
float v;
#Override
public void run() {
// Calculate progress using interpolator
elapsed = SystemClock.uptimeMillis() - start;
t = elapsed / durationInMs;
v = interpolator.getInterpolation(t);
LatLng currentPosition = new LatLng(
startPosition.latitude * (1 - t) + nextPosition.latitude * t,
startPosition.longitude * (1 - t) + nextPosition.longitude * t);
mMarker.setPosition(currentPosition);
// Repeat till progress is complete.
if (t < 1) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
if (hideMarker) {
mMarker.setVisible(false);
} else {
mMarker.setVisible(true);
}
}
}
});
}

How to have multiple Textboxes travel in random directions with specific time interval between them?

I am currently making a type speed game using JavaFX where words should fall from the top and the user has to type them as fast as they can before the fall to the bottom. I have the basic set up of the game ready. The only thing I am struggling with is how to get the words to fall from the top and go to the bottom (currently they travel from bottom to top). And also I want multiple words to fall down from random location at the top (not the same point of origin) at specific time interval between them, say 30 milliseconds. The code I have so far:
public void showWords() throws InterruptedException
{
int missedWords = 0; // number of words the user failed to type
while (missedWords != 10)
{
dequedWord = queue.dequeue(); // the word that the Text object will contain
Text runWord = new Text(dequedWord);
wordsPane.getChildren().add(runWord); // the canvas in which the words will travel from top to bottom
double PaneHeight = wordsPane.getHeight();
//double PaneWidth = wordsPane.getWidth();
double runWordWidth = runWord.getLayoutBounds().getWidth();
KeyValue initKeyValue = new KeyValue(runWord.translateYProperty(), PaneHeight);
KeyFrame initFrame = new KeyFrame(Duration.ZERO, initKeyValue);
KeyValue endKeyValue = new KeyValue(runWord.translateYProperty(), -1.0 * runWordWidth);
KeyFrame endFrame = new KeyFrame(Duration.seconds(12), endKeyValue);
Timeline timeline = new Timeline(initFrame, endFrame);
timeline.setCycleCount(1);
timeline.play();
// add code to check whether user typed the word in the Text object
missedWords++;
}
}
I am new to animation so I do not know much about Timeline, KeyValue and KeyFrame classes. I tried reading the documentation for the APIs, but did not help me much. Any help is greatly appreciated. Thank you :)
The y axis of the coordinate system points down (which is quite common in computer graphics). This is why your nodes move in the wrong direction. Furthermore Timeline does not seem to be well suited here, since you'd need to run a Timeline per word and another Timeline for adding new words.
I recommend using a AnimationTimer instead which contains a method called for every frame which allows you to update the positions, remove old words and add new words depending on the time.
Example:
#Override
public void start(Stage primaryStage) {
final Queue<String> words = new LinkedList<>(Arrays.asList(
"Hello",
"World",
"foo",
"bar"
));
final Pane wordsPane = new Pane();
wordsPane.setPrefSize(800, 400);
final long wordDelay = 500_000_000L; // 500 ms
final long fallDuration = 12_000_000_000L; // 12 s
AnimationTimer animation = new AnimationTimer() {
private long lastWordAdd = Long.MIN_VALUE; // never added a word before
private final Map<Text, Long> nodes = new LinkedHashMap<>();
private double nextX = 0;
private void assignXPosition(Text text) {
text.setTranslateX(nextX);
nextX += text.getBoundsInLocal().getWidth();
}
#Override
public void handle(long now) {
// updates & cleanup
long deletionLimit = now - fallDuration;
for (Iterator<Map.Entry<Text, Long>> iter = nodes.entrySet().iterator(); iter.hasNext();) {
Map.Entry<Text, Long> entry = iter.next();
final Text text = entry.getKey();
final long startTime = entry.getValue();
if (startTime < deletionLimit) {
// delete old word
iter.remove();
wordsPane.getChildren().remove(text);
} else {
// update existing word
double factor = ((double) (now - startTime)) / fallDuration;
Bounds bounds = text.getBoundsInLocal();
text.setTranslateY((wordsPane.getHeight() + bounds.getHeight()) * factor - bounds.getMaxY());
}
}
if (words.isEmpty()) {
if (nodes.isEmpty()) {
stop(); // end animation since there are no more words
}
} else if (lastWordAdd + wordDelay <= now) {
lastWordAdd = now;
// add new word
Text text = new Text(words.remove());
wordsPane.getChildren().add(text);
assignXPosition(text);
text.setTranslateY(-text.getBoundsInLocal().getMaxY());
nodes.put(text, now);
}
}
};
animation.start();
Scene scene = new Scene(wordsPane);
primaryStage.setScene(scene);
primaryStage.show();
}

android here sdk moving markers

I need to be able to show moving cars using Here maps android sdk.
Is it possible in the current version? I tried to remove and add map marker object in a render like loop logic as the following;
// this is a render like loop which is called in each 1 secs
public void update(Map map, float deltaTime) {
float displacement = mCars.get(0).getVelocity() * deltaTime;
float delta = displacement / ((float) Math.sqrt(2));
MapMarker mapMarker = new MapMarker();
Image image = new Image();
image.setBitmap(mCars.get(0).getIcon().toBitmap());
mapMarker.setCoordinate(mCars.get(0).getCoordinate());
mapMarker.setIcon(image);
// remove old coordinate
map.removeMapObject(mapMarker);
mCars.get(0).addDelta(delta);
mapMarker.setCoordinate(mCars.get(0).getCoordinate());
map.addMapObject(mapMarker);
}
The removeMapObject() doesn't seem to be working. Any ideas to have a moving map object ?
The problem here was to create each marker and remove them and re-add them.
The render loop would be the following;
// this is a render like loop which is called in each 1 secs
public void update(Map map, float deltaTime) {
Timber.d("Before coordinate: %f %f", mCars.get(0).getCoordinate().getLatitude(), mCars.get(0).getCoordinate().getLongitude());
map.removeMapObject(mCars.get(0).getMarker());
mCars.get(0).addDelta(deltaTime);
map.addMapObject(mCars.get(0).getMarker());
Timber.d("Update call, delta time: %f", deltaTime);
}
The addDelta() call should update the marker coordinate and its own coordinate;
public void addDelta(float deltaTime) {
if (mDestination.equals(mCoordinate)) {
return;
}
double deltaLatitude = mDestination.getLatitude() - mCoordinate.getLatitude();
double deltaLongitude = mDestination.getLongitude() - mCoordinate.getLongitude();
double lat = getCoordinate().getLatitude() + (0.01 * deltaLatitude);
double lng = getCoordinate().getLongitude() + (0.01 * deltaLongitude);
mCoordinate.setLatitude(lat);
mCoordinate.setLongitude(lng);
updateMarker();
}
And lastly, updateMarker implementation is the following;
public void updateMarker() {
mMarker = new MapMarker();
Image image = new Image();
image.setBitmap(mIcon.toBitmap());
mMarker.setCoordinate(mCoordinate);
mMarker.setIcon(image);
}

Setting appropriate zoom Android Google Maps API [duplicate]

I have 10 markers in the GoogleMap. I want to zoom in as much as possible and keep all markers in view? In the earlier version this can be achieved from zoomToSpan() but in v2 I have no idea how about doing that. Further, I know the radius of the circle that needs to be visible.
You should use the CameraUpdate class to do (probably) all programmatic map movements.
To do this, first calculate the bounds of all the markers like so:
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker marker : markers) {
builder.include(marker.getPosition());
}
LatLngBounds bounds = builder.build();
Then obtain a movement description object by using the factory: CameraUpdateFactory:
int padding = 0; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
Finally move the map:
googleMap.moveCamera(cu);
Or if you want an animation:
googleMap.animateCamera(cu);
That's all :)
Clarification 1
Almost all movement methods require the Map object to have passed the layout process. You can wait for this to happen using the addOnGlobalLayoutListener construct. Details can be found in comments to this answer and remaining answers. You can also find a complete code for setting map extent using addOnGlobalLayoutListener here.
Clarification 2
One comment notes that using this method for only one marker results in map zoom set to a "bizarre" zoom level (which I believe to be maximum zoom level available for given location). I think this is expected because:
The LatLngBounds bounds instance will have northeast property equal to southwest, meaning that the portion of area of the earth covered by this bounds is exactly zero. (This is logical since a single marker has no area.)
By passing bounds to CameraUpdateFactory.newLatLngBounds you essentially request a calculation of such a zoom level that bounds (having zero area) will cover the whole map view.
You can actually perform this calculation on a piece of paper. The theoretical zoom level that is the answer is +∞ (positive infinity). In practice the Map object doesn't support this value so it is clamped to a more reasonable maximum level allowed for given location.
Another way to put it: how can Map object know what zoom level should it choose for a single location? Maybe the optimal value should be 20 (if it represents a specific address). Or maybe 11 (if it represents a town). Or maybe 6 (if it represents a country). API isn't that smart and the decision is up to you.
So, you should simply check if markers has only one location and if so, use one of:
CameraUpdate cu = CameraUpdateFactory.newLatLng(marker.getPosition()) - go to marker position, leave current zoom level intact.
CameraUpdate cu = CameraUpdateFactory.newLatLngZoom(marker.getPosition(), 12F) - go to marker position, set zoom level to arbitrarily chosen value 12.
Google Map V2
The following solution works for Android Marshmallow 6 (API 23, API 24, API 25, API 26, API 27, API 28). It also works in Xamarin.
LatLngBounds.Builder builder = new LatLngBounds.Builder();
//the include method will calculate the min and max bound.
builder.include(marker1.getPosition());
builder.include(marker2.getPosition());
builder.include(marker3.getPosition());
builder.include(marker4.getPosition());
LatLngBounds bounds = builder.build();
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
int padding = (int) (width * 0.10); // offset from edges of the map 10% of screen
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);
mMap.animateCamera(cu);
I couldnt use the onGlobalLayoutlistener, so here is another solution to prevent the
"Map size can't be 0. Most likely, layout has not yet occured for the map view. Either wait until layout has occurred or use newLatLngBounds(LatLngBounds, int, int, int) which allows you to specify the map's dimensions." error:
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 15));
}
});
So
I needed to use addOnGlobalLayoutListener to get the appropriate sample
for example, your Google Map is inside RelativeLayout:
RelativeLayout mapLayout = (RelativeLayout)findViewById(R.id.map_layout);
mapLayout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
//and write code, which you can see in answer above
}
});
Working fine for me.
From this code, I am displaying multiple markers with particular zoom on map screen.
// Declared variables
private LatLngBounds bounds;
private LatLngBounds.Builder builder;
// Method for adding multiple marker points with drawable icon
private void drawMarker(LatLng point, String text) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(point).title(text).icon(BitmapDescriptorFactory.fromResource(R.drawable.icon));
mMap.addMarker(markerOptions);
builder.include(markerOptions.getPosition());
}
// For adding multiple markers visible on map
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
builder = new LatLngBounds.Builder();
for (int i = 0; i < locationList.size(); i++) {
drawMarker(new LatLng(Double.parseDouble(locationList.get(i).getLatitude()), Double.parseDouble(locationList.get(i).getLongitude())), locationList.get(i).getNo());
}
bounds = builder.build();
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 0);
mMap.animateCamera(cu);
Note - This is not a solution to the original question. This is a solution to one of the subproblems discussed above.
Solution to #andr Clarification 2 -
Its really problematic when there's only one marker in the bounds and due to it the zoom level is set to a very high level (level 21). And Google does not provide any way to set the max zoom level at this point. This can also happen when there are more than 1 marker but they are all pretty close to each other. Then also the same problem will occur.
Solution - Suppose you want your Map to never go beyond 16 zoom level. Then after doing -
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
mMap.moveCamera(cu);
Check if your zoom level has crossed level 16(or whatever you want) -
float currentZoom = mMap.getCameraPosition().zoom;
And if this level is greater than 16, which it will only be if there are very less markers or all the markers are very close to each other, then simply zoom out your map at that particular position only by seting the zoom level to 16.
mMap.moveCamera(CameraUpdateFactory.zoomTo(16));
This way you'll never have the problem of "bizarre" zoom level explained very well by #andr too.
this would help.. from google apis demos
private List<Marker> markerList = new ArrayList<>();
Marker marker = mGoogleMap.addMarker(new MarkerOptions().position(geoLatLng)
.title(title));
markerList.add(marker);
// Pan to see all markers in view.
// Cannot zoom to bounds until the map has a size.
final View mapView = getSupportFragmentManager().findFragmentById(R.id.map).getView();
if (mapView!=null) {
if (mapView.getViewTreeObserver().isAlive()) {
mapView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#SuppressWarnings("deprecation") // We use the new method when supported
#SuppressLint("NewApi") // We check which build version we are using.
#Override
public void onGlobalLayout() {
//Calculate the markers to get their position
LatLngBounds.Builder b = new LatLngBounds.Builder();
for (Marker m : markerList) {
b.include(m.getPosition());
}
// also include current location to include in the view
b.include(new LatLng(mLocation.getLatitude(),mLocation.getLongitude()));
LatLngBounds bounds = b.build();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
mapView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));
}
});
}
}
for clear info look at this url.
https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/java/com/example/mapdemo/MarkerDemoActivity.java
Show All Markers with Google map
In these Methods store all Markers and automatically zoom to show all markers in google map.
// Declare the Markers List.
List<MarkerOptions> markerList;
private BitmapDescriptor vnrPoint,banPoint;
public void storeAllMarkers()
{
markerList=new ArrayList<>();
markerList.removeAll(markerList);
// latitude and longitude of Virudhunagar
double latitude1=9.587209;
double longitude1=77.951431;
vnrPoint=BitmapDescriptorFactory.fromResource(R.drawable.location_icon_1);
LatLng vnr = new LatLng(latitude1, longitude1);
MarkerOptions vnrMarker = new MarkerOptions();
vnrMarker.position(vnr);
vnrMarker.icon(vnrPoint);
markerList.add(vnrMarker);
// latitude and longitude of Bengaluru
double latitude2=12.972442;
double longitude2=77.580643;
banPoint=BitmapDescriptorFactory.fromResource(R.drawable.location_icon_2);
LatLng ban = new LatLng(latitude2, longitude2);
MarkerOptions bengalureMarker = new MarkerOptions();
bengalureMarker.position(ban);
bengalureMarker.icon(banPoint);
markerList.add(bengalureMarker);
// You can add any numbers of MarkerOptions like this.
showAllMarkers();
}
public void showAllMarkers()
{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (MarkerOptions m : markerList) {
builder.include(m.getPosition());
}
LatLngBounds bounds = builder.build();
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
int padding = (int) (width * 0.30);
// Zoom and animate the google map to show all markers
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);
googleMap.animateCamera(cu);
}
I had similar problem, using following code solved the issue:
CameraUpdateFactory.newLatLngBounds(bounds, 200, 200, 5) generally the location differences in my case are no more than two neighbour cities.
zoom to fit all markers on map google maps v2
I have one other way to do this same thing works perfectly. so the idea behind to show all markers on the screen we need a center lat long and zoom level. here is the function which will give you both and need all marker's Latlng objects as input.
public Pair<LatLng, Integer> getCenterWithZoomLevel(LatLng... l) {
float max = 0;
if (l == null || l.length == 0) {
return null;
}
LatLngBounds.Builder b = new LatLngBounds.Builder();
for (int count = 0; count < l.length; count++) {
if (l[count] == null) {
continue;
}
b.include(l[count]);
}
LatLng center = b.build().getCenter();
float distance = 0;
for (int count = 0; count < l.length; count++) {
if (l[count] == null) {
continue;
}
distance = distance(center, l[count]);
if (distance > max) {
max = distance;
}
}
double scale = max / 1000;
int zoom = ((int) (16 - Math.log(scale) / Math.log(2)));
return new Pair<LatLng, Integer>(center, zoom);
}
This function return Pair object which you can use like
Pair pair = getCenterWithZoomLevel(l1,l2,l3..);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pair.first, pair.second));
you can instead of using padding to keep away your markers from screen boundaries, you can adjust zoom by -1.
I worked the same problem for showing multiple markers in Kotlin using a fragment
first declare a list of markers
private lateinit var markers: MutableList<Marker>
initialize this in the oncreate method of the frament
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
//initialize markers list
markers = mutableListOf()
return inflater.inflate(R.layout.fragment_driver_map, container, false)
}
on the OnMapReadyCallback add the markers to the markers list
private val callback = OnMapReadyCallback { googleMap ->
map = googleMap
markers.add(
map.addMarker(
MarkerOptions().position(riderLatLng)
.title("Driver")
.snippet("Driver")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))))
markers.add(
map.addMarker(
MarkerOptions().position(driverLatLng)
.title("Driver")
.snippet("Driver")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))))
Still on the callback
//create builder
val builder = LatLngBounds.builder()
//loop through the markers list
for (marker in markers) {
builder.include(marker.position)
}
//create a bound
val bounds = builder.build()
//set a 200 pixels padding from the edge of the screen
val cu = CameraUpdateFactory.newLatLngBounds(bounds,200)
//move and animate the camera
map.moveCamera(cu)
//animate camera by providing zoom and duration args, callBack set to null
map.animateCamera(CameraUpdateFactory.zoomTo(10f), 2000, null)
Merry coding guys
Use the method "getCenterCoordinate" to obtain the center coordinate and use in CameraPosition.
private void setUpMap() {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setScrollGesturesEnabled(true);
mMap.getUiSettings().setTiltGesturesEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
clientMarker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(Double.valueOf(-12.1024174), Double.valueOf(-77.0262274)))
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_taxi))
);
clientMarker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(Double.valueOf(-12.1024637), Double.valueOf(-77.0242617)))
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_location))
);
camPos = new CameraPosition.Builder()
.target(getCenterCoordinate())
.zoom(17)
.build();
camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
mMap.animateCamera(camUpd3);
}
public LatLng getCenterCoordinate(){
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(new LatLng(Double.valueOf(-12.1024174), Double.valueOf(-77.0262274)));
builder.include(new LatLng(Double.valueOf(-12.1024637), Double.valueOf(-77.0242617)));
LatLngBounds bounds = builder.build();
return bounds.getCenter();
}
//For adding a marker in Google map
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)));
mp.snippet(strAddress);
map.addMarker(mp);
try {
b = new LatLngBounds.Builder();
if (MapDetailsList.list != null && MapDetailsList.list.size() > 0) {
for (int i = 0; i < MapDetailsList.list.size(); i++) {
b.include(new LatLng(Double.parseDouble(MapDetailsList.list.get(i).getLatitude()),
Double.parseDouble(MapDetailsList.list.get(i).getLongitude())));
}
LatLngBounds bounds = b.build();
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
// Change the padding as per needed
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width-200, height-200, 5);
// map.setCenter(bounds.getCenter());
map.animateCamera(cu);
}
} catch (Exception e) {
}
http://i64.tinypic.com/2qjybh4.png
http://i63.tinypic.com/flzwus.png
http://i63.tinypic.com/112g5fm.png

LibGDX Path (CatmullRomSpline) Constant Speed

I’m trying to achieve constant speed on a path using the LibGDX CatmullRomSpline and I’m having problems getting it to work. I’ve tried researching on this topic a lot including reading the LibGDX wiki, but their explanation for achieving constant speed doesn’t really make sense and I wasn’t able to get their method to work. https://github.com/libgdx/libgdx/wiki/Path-interface-&-Splines
In my case, the derivative values are very large (in the hundreds) so when dividing a number between 0-1 by the derivative the result is very small and the movement is very slow and still not constant. So I’m not sure exactly how their example works.
In my example I have a couple visual aids coinciding with the speed of the ball, the bar at the bottom of the screen increases in length as the speed increases and the color also changes from white to red as the speed increases.
In the act() method of MyPath.java I have two sections commented out starting with [1] and [2]. The first one is normal with the variable speed through the path and the second one is my failed attempt at getting the LibGDX wiki constant speed to work. So just un-comment these lines to switch between the two versions.
My idea for constant speed involves figuring out the speed based on the total length of the path (using the approxLength(1000) method on the spline), then using the derivative function to determine the actual speed at a given instant, and adjusting the percentage value sent into the spline to compensate for the speed changes in order to make the speed constant. However, I don’t quite understand what the derivative function actually represents. I posted a question about the derivative function earlier, but based a comment I received I figured it might be easier to ask about achieving constant speed instead. Here is my previous question on the derivative function:
LibGDX CatmullRomSpline Derivative Meaning?
Any ideas on how to achieve constant speed in my example (or explaining what the derivative function for the CatmullRomSpline actually represents so I could better understand how to use it) would be greatly appreciated.
For anyone who'd like to run the program, here are the two image files I created for my example (add these to the root of the assets folder):
http://dropshots.com/Tekker/date/2015-09-19
Here is my example code:
DesktopLauncher.java: (changed desktop window width and height to 1000)
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.width = 1000;
config.height = 1000;
new LwjglApplication(new TEST(), config);
}
}
TEST.java:
public class TEST extends Game {
Stage stage;
MyPath path;
#Override
public void create () {
stage = new Stage();
stage.setViewport(new ScreenViewport(stage.getViewport().getCamera()));
Gdx.input.setInputProcessor(stage);
path = new MyPath(1000, 1000);
stage.addActor(path);
}
#Override
public void render () {
Gdx.gl.glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
}
#Override
public void dispose(){
stage.dispose();
super.dispose();
}
}
MyPath.java:
public class MyPath extends WidgetGroup {
Image start, end, path, bar1, horizontal;
float time, percent, dVal, pathLength, dMax=1000, cycle=6, maxPercent, deltaCycle;
CatmullRomSpline<Vector2> catmull;
Vector2 result = new Vector2();
Vector2 previousResult = new Vector2(50,150);
Vector2 derivative = new Vector2();
Vector2 previousDerivative = new Vector2();
Vector2[] points = {
new Vector2(50,150), new Vector2(50,150),
new Vector2(400,800), new Vector2(600,150), new Vector2(700,400),
new Vector2(860,150), new Vector2(860,150)
};
boolean print = true;
public MyPath(int width, int height){
this.setSize(width, height);
catmull = new CatmullRomSpline<Vector2>(points, false);
createPath();
createBar();
pathLength = catmull.approxLength(1000);
}
#Override
public void act(float delta){
// [1] VARIABLE SPEED
//time += delta;
//percent = (time / cycle) % 1;
// [2] CONSTANT SPEED FAIL!
//catmull.derivativeAt(previousDerivative, percent);
//time += delta;
//percent = ((time / cycle) / previousDerivative.len() ) % 1;
catmull.valueAt(result, percent);
path.setPosition(result.x, this.getHeight() - result.y);
updateSpeedVisuals();
debugPrint();
previousResult.set(result);
}
private void createPath(){
start = new Image(new Texture("dot.png"));
start.setColor(Color.GRAY);
start.setPosition(50, this.getHeight() - 150);
this.addActor(start);
end = new Image(new Texture("dot.png"));
end.setColor(Color.GRAY);
end.setPosition(860, this.getHeight() - 150);
this.addActor(end);
path = new Image(new Texture("dot.png"));
path.setColor(Color.WHITE);
this.addActor(path);
}
private void createBar(){
Texture texture = new Texture("ninepatch.png");
int crop = (int)(texture.getWidth()/2)-1;
NinePatch patch9 = new NinePatch(texture, crop, crop, crop, crop);
bar1 = new Image(patch9);
bar1.setColor(Color.GRAY);
bar1.setPosition(5, this.getHeight()-900);
this.addActor(bar1);
}
private void updateSpeedVisuals(){
catmull.derivativeAt(derivative, percent);
dVal = derivative.len() / dMax;
path.setColor(1f, 1f-dVal, 1f-dVal, 1f);
bar1.setWidth(derivative.len());
bar1.setColor(1f, 1f-dVal, 1f-dVal, 1f);
}
private void debugPrint(){
maxPercent = (percent > maxPercent) ? percent : maxPercent;
if (maxPercent > percent){
print = false;
}
if (print){
String debugPrint = "";
debugPrint = debugPrint + "pathLength=" + pathLength + "\t";
debugPrint = debugPrint + "derivative=" + derivative.len() + "\t";
System.out.println(debugPrint);
}
}
}
Since the derivative is the rate of change of the spline position it is indeed the 'speed', and when the spline is bending away from the underlying data points it has to 'speed up' to make the calculated spline reach the next data point in time, you must divide out this speed to perceive a visual constant speed.
You aren't getting a constant speed because you are still incrementing your time variable by delta instead of delta divided by the rate of change (derivative). You should be adding a variable amount to the percent variable each frame, instead you were modifying everything by the derivative of a single point along the Catmull-Rom spline.
Instead of:
catmull.derivativeAt(previousDerivative, percent);
time += delta;
percent = ((time / cycle) / previousDerivative.len() ) % 1;
You should:
catmull.derivativeAt(previousDerivative, percent);
percent += derivativeAverage / cycle * delta / previousDerivative.len();
percent %= 1;
you should use the average derivative divided by cycle now since you can't use cycle alone as a percent per second variable anymore.
Iterating over the spline to find the average value of the derivativeAverage:
int samples = 100; //the higher the more accurate, however slower
float derivativeAverage = 0;
Vector2 out = new Vector2();
for (float i=0;i<1;i+=1f/samples) {
catmull.derivativeAt(out, i);
derivativeAverage += out.len();
}
derivativeAverage /= samples;

Categories