A demo app showing movement of car on map like in Uber.
A demo application which demonstrates movement of car on map developed after inspiration from Uber.
Steps:
"https://maps.googleapis.com/maps/api/directions/json?" +
"mode=driving&"
+ "transit_routing_preference=less_driving&"
+ "origin=" + latitude + "," + longitude + "&"
+ "destination=" + destination + "&"
+ "key=" + getResources().getString(R.string.google_directions_key)
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
valueAnimator.setDuration(3000);
valueAnimator.setInterpolator(new LinearInterpolator());
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
//CODE
});
v=valueAnimator.getAnimatedFraction();
lng = v * endPosition.longitude + (1 - v)* startPosition.longitude;
lat = v * endPosition.latitude + (1 - v)* startPosition.latitude;
where v is animation fraction
and startposition and endPostion refer to each pair of LatLng from the decoded list from polyline for eg (0,1) then (1,2) then(2,3)
and so on.
marker.setPosition(newPos);
marker.setAnchor(0.5f, 0.5f);
marker.setRotation(getBearing(startPosition, newPos));
mMap.moveCamera(CameraUpdateFactory
.newCameraPosition
(new CameraPosition.Builder()
target(newPos)
.zoom(15.5f)
.build()));
The application uses Google Maps Api Key and Google Map Directions key. Get these api key on google developers console after enabling them for your project. Replace your google maps directions api key in strings.xml and google maps key in google_maps_api.xml. For convenience a TODO has been added there just follow them.
build.gradle
:
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0' implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
MQTTHelper
class. The username, password and the server URI which is of form tcp://uri:port.UberMQTT.py
file.location/track
.
The android app will connect to the broker and subscribe to the topic of kind location/+
. As soon as the MQTT server receives the location it will push it to the android client.convertStringToLatLng
.messageReceived
callback:
@Override public void messageArrived(String topic, MqttMessage message) throws Exception { String payload = new String(message.getPayload()); LatLng currentLatLng = convertStringToLatLng(payload); Log.d(TAG, topic + " " + currentLatLng); latLngPublishRelay.accept(currentLatLng); }And subscribing to this relay with buffer 2:
latLngPublishRelay .buffer(2) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer>() {
@Override public void accept(List<LatLng> latLngs) throws Exception { emission++; animateCarOnMap(latLngs); }
});
animateCarOnMap
function will dispatch animation through ValueAnimator. This animation will be based on same logic as was explained above.If you found this code demo helpful or you learned something today and want to thank me, consider buying me a cup of :coffee: at PayPal