google maps v2 draw polyline depends on speed - android

i have this database:
and i've tried to make a simple polyline drawing which is depends on the speed this way:
Cursor curTAB = myDataBase.rawQuery("SELECT * FROM GPS_Values;", null);
Integer count = 0;
while (curTAB.moveToNext()) {
String s_latitude = curTAB.getString(1);
String s_longitude = curTAB.getString(2);
String s_speed = curTAB.getString(5);
count++;
double latitude = Double.parseDouble(s_latitude);
double longitude = Double.parseDouble(s_longitude);
int speed = Integer.parseInt(curTAB.getString(5).toString());
if (speed <= 50) {
Log.i("Coordinates",
s_latitude.toString() + " --- " + s_longitude.toString() + " --- " +s_speed.toString());
line.add(new LatLng(latitude, longitude)).color(Color.GREEN);
line.color(Color.GREEN);
map.addPolyline(line);
} else {
Log.e("Coordinates",
s_latitude.toString() + " --- " + s_longitude.toString() + " --- " +s_speed.toString());
line.add(new LatLng(latitude, longitude)).color(Color.BLUE);
line.color(Color.BLUE);
map.addPolyline(line);
}
Log.i("Coordinates",
s_latitude.toString() + " --- " + s_longitude.toString() + " --- " +s_speed.toString());
}
curTAB.close();
myDataBase.close();
double latitude = Double.parseDouble(first_lat);
double longitude = Double.parseDouble(first_long);map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,
longitude), 15));
map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
But every line is with the same color.
Please help me what did i wrong!
update:
the working code(at the last point it doesn't work but not a big problem)
Integer count = 0;
while (curTAB.moveToNext()) {
String s_latitude = curTAB.getString(1);
String s_longitude = curTAB.getString(2);
String s_speed = curTAB.getString(5);
double latitude = Double.parseDouble(s_latitude);
double longitude = Double.parseDouble(s_longitude);
int speed = Integer.parseInt(curTAB.getString(5).toString());
int position = curTAB.getPosition();
count++;
System.out.println("Curr " + latitude + " --- " + longitude
+ " --- " + speed);
if (curTAB.moveToNext()) {
String next_speed = curTAB.getString(5);
String ss_latitude = curTAB.getString(1);
String ss_longitude = curTAB.getString(2);
System.out.println("Next " + ss_latitude + " --- "
+ ss_longitude + " --- " + next_speed);
curTAB.moveToPosition(position);
double n_latitude = Double.parseDouble(ss_latitude);
double n_longitude = Double.parseDouble(ss_longitude);
if (speed > 60) {
map.addPolyline(new PolylineOptions()
.add(new LatLng(latitude, longitude),
new LatLng(n_latitude, n_longitude))
.width(10).color(Color.RED));
} else if ((speed < 56) && (speed > 31)) {
map.addPolyline(new PolylineOptions()
.add(new LatLng(latitude, longitude),
new LatLng(n_latitude, n_longitude))
.width(10).color(Color.GREEN));
} else if (speed < 31) {
map.addPolyline(new PolylineOptions()
.add(new LatLng(latitude, longitude),
new LatLng(n_latitude, n_longitude))
.width(10).color(Color.rgb(255, 127, 80)));
}
}else{
System.out.println("VÉGE");
}
line.add(new LatLng(latitude, longitude));
}

I'm not familiar with the maps-android-API, but it looks as if you add a new Polyline for each db-entry which will have the same path as the polyline added before plus the new LatLng from the current entry.
The result will be that you only see the polyline created for the last entry which will cover all the other polylines.
I guess you need to set up a new PolylineOptions-object on each iteration and add as Points the LatLngs of the recent entry and of the current entry to get the desired result.

Related

How do I retrieve the JSON response for each click on Google Map Marker?

I was able to make multiple marks on the google map on android by getting data from JSON. So NOW each of those markers has their own corresponding bukken_name, latitute and longitude.
Each time I click a specific marker on the map. I want it to display in console their retrieved JSON data.
In my current code, onMarkerClick gets the values and then displays it in System.out.println. But whenever I do so click the marker it only keeps on display the exact same value of the last JSON data.
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");
JSONArray bukken_list = data.getJSONArray("bukken_list");
for (int i = 0; i < bukken_list.length(); i++) {
JSONObject returnBukken = bukken_list.getJSONObject(i);
String latitude = returnBukken.getString("ido_hokui"); //latitude
String longitude = returnBukken.getString("keido_tokei"); //longitude
final String bukken_name = returnBukken.getString("bukken_name"); //longitude
final Double x = Double.parseDouble(latitude);
final Double y = Double.parseDouble(longitude);
System.out.println("COORDINATES: " + i);
System.out.println("LATITUDE: " + latitude);
System.out.println("LONGITUDE: " + longitude);
System.out.println("BUKKEN NAME: " + longitude);
LatLng japan = new LatLng(x, y);
MarkerOptions client_marker = new MarkerOptions().position(new LatLng(x, y));
client_marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.mapicon_rent));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(japan, 10f));
mMap.addMarker(client_marker);
mMap.moveCamera(CameraUpdateFactory.newLatLng(japan));
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker arg0) {
//FAULT: does not get value of each marker
System.out.println("MARKER " + x + " " + y + " " + bukken_name);
return true;
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
int x = 1;
// Anything you want
}
});
Set bukken_name as marker's tag:
Marker marker = mMap.addMarker(client_marker);
marker.setTag(bukken_name);
On marker click:
public boolean onMarkerClick(Marker clickedMarker) {
LatLng location = clickedMarker.getPosition();
System.out.println("MARKER " + location.latitude + " " + location.longitude + " " + clickedMarker.getTag());
return true;
}

Getting some weird strings while i was trying to get location name using marker on touch event on maps

I'm trying to make an app to get the location name where the marker is placed on the map in android. When I used marker.position() function it gave me a weird string. Starts with, com.google.android.gms.maps.model.MarkerOptions#28f817d
I tried to use geocode but didn't work for me. I might be using it in an improper way.
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
mMap.clear();
MarkerOptions marker = new MarkerOptions();
mMap.addMarker(marker.position(point)
.draggable(true)
.title(String.valueOf(marker.position(point)))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.snippet(point.latitude + "," + point.longitude));
}
});
}
I wish that I can get the location name on the title.
Thats becouse marker.position(point)) returns an object of class LatLng and is not an String itself. You could use any of its properties (latitude & longitude):
String.valueOf(marker.position(point))
to
"" + marker.position(point).latitude + marker.position(point).longitude
Do something like this
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
mMap.clear();
MarkerOptions marker = new MarkerOptions();
mMap.addMarker(marker.position(point)
.draggable(true)
.title(getAddress(point.getLatitude(),point.getLongitude()))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.snippet(point.latitude + "," + point.longitude));
}
});
}
write a function called getAddress like this
public string getAddress(double lat, double lng) {
Geocoder geocoder = new Geocoder(HomeActivity.mContext, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Address obj = addresses.get(0);
String add = obj.getAddressLine(0);
add = add + "\n" + obj.getCountryName();
add = add + "\n" + obj.getCountryCode();
add = add + "\n" + obj.getAdminArea();
add = add + "\n" + obj.getPostalCode();
add = add + "\n" + obj.getSubAdminArea();
add = add + "\n" + obj.getLocality();
add = add + "\n" + obj.getSubThoroughfare();
Log.v("IGA", "Address" + add);
// Toast.makeText(this, "Address=>" + add,
// Toast.LENGTH_SHORT).show();
// TennisAppActivity.showDialog(add);
return add;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return e;
}
}

Polyline is not following the actual path betweeen two locations

I'm getting Latitudes and Longitudes from Google Directions API and using them to show polyline between two locations. Polyline is being drawn but not following the exact road or path that it must follow.
Here are my screenshots-
Screenshot 1
Screenshot 2
Here is my code through which i'm getting LatLngs and displaying polyline.
public void requestDirections(final String mode, String origin, String destination)
{
final ProgressDialog progress=new ProgressDialog(this);
progress.setMessage("Finding route");
progress.show();
Retrofit retrofit= new Retrofit.Builder().baseUrl("https://maps.googleapis.com/").addConverterFactory(GsonConverterFactory.create()).build();
Call<DirectionResponse> call=retrofit.create(ApiDirections.class).getDirections(mode, origin, destination);
call.enqueue(new Callback<DirectionResponse>() {
#Override
public void onResponse(Call<DirectionResponse> call, Response<DirectionResponse> response) {
for(int i=0; i<response.body().getRoutes().get(0).getLegs().get(0).getSteps().size(); i++)
{
LatLng startLoc=new LatLng(response.body().getRoutes().get(0).getLegs().get(0).getSteps().get(i).getStartLocation().getLat(), response.body().getRoutes().get(0).getLegs().get(0).getSteps().get(i).getStartLocation().getLng());
LatLng endLoc=new LatLng(response.body().getRoutes().get(0).getLegs().get(0).getSteps().get(i).getEndLocation().getLat(), response.body().getRoutes().get(0).getLegs().get(0).getSteps().get(i).getEndLocation().getLng());
Polyline polyline=response.body().getRoutes().get(0).getLegs().get(0).getSteps().get(i).getPolyline();
DataHandler.startingLocations.add(startLoc);
DataHandler.endingLocations.add(endLoc);
System.out.println("Starting Loc "+i+" "+startLoc);
System.out.println("Ending Loc "+i+" "+endLoc);
System.out.println("polyline "+i+" "+polyline.getPoints());
}
LatLng endLocation=new LatLng(response.body().getRoutes().get(0).getLegs().get(0).getEndLocation().getLat(), response.body().getRoutes().get(0).getLegs().get(0).getEndLocation().getLng());
marker=mMap.addMarker(new MarkerOptions().position(endLocation).flat(true));
marker.setTag(destinationName);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(DataHandler.startingLocations.get((response.body().getRoutes().get(0).getLegs().get(0).getSteps().size())/2), 10));
polylineOptions=new PolylineOptions();
polylineOptions.addAll(DataHandler.endingLocations);
polylineOptions.color(getResources().getColor(R.color.colorAccent));
polylineOptions.width(12);
polylineOptions.startCap(new RoundCap());
polylineOptions.endCap(new RoundCap());
mMap.addPolyline(polylineOptions);
textViewJourneyDistance.setText(response.body().getRoutes().get(0).getLegs().get(0).getDistance().getText());
textViewJourneyTime.setText(response.body().getRoutes().get(0).getLegs().get(0).getDuration().getText());
progress.dismiss();
}
#Override
public void onFailure(Call<DirectionResponse> call, Throwable t) {
progress.dismiss();
}
});
}
public interface ApiDirections{
#GET("maps/api/directions/json?key=My_API_KEY")
Call<DirectionResponse> getDirections(#Query("mode") String mode,
#Query("origin") String origin,
#Query("destination") String destination);
}
you need to get routelist
ArrayList<LatLng> routelist = new ArrayList<LatLng>();
if (response.body().getRoutes().size() > 0) {
ArrayList<LatLng> decodelist;
Route routeA = response.body().getRoutes().get(0);
Log.e("ad", "Legs length : " + routeA.getLegs().size());
if (routeA.getLegs().size() > 0) {
List<Steps> steps = routeA.getLegs().get(0).getSteps();
Log.e("ad", "Steps size :" + steps.size());
Steps step;
Location location;
String polyline;
for (int i = 0; i < steps.size(); i++) {
step = steps.get(i);
location = step.getStart_location();
routelist.add(new LatLng(location.getLat(), location.getLng()));
Log.e("ad", "Start Location :" + location.getLat() + ", " + location.getLng());
polyline = step.getPolyline().getPoints();
decodelist = RouteDecode.decodePoly(polyline);
routelist.addAll(decodelist);
location = step.getEnd_location();
routelist.add(new LatLng(location.getLat(), location.getLng()));
Log.e("ad", "End Location :" + location.getLat() + ", " + location.getLng());
Integer disInMeters = routeA.getLegs().get(0).getDistance().getValue();
int kilometers = (int) (disInMeters * 0.001);
}
}
}
if (routelist.size() > 0) {
PolylineOptions rectLine = new PolylineOptions().width(10).color(ContextCompat.getColor(SendSomethingTodayActivityThree.this, R.color.colorPrimary));
for (int i = 0; i < routelist.size(); i++) {
rectLine.add(routelist.get(i));
}}
its work for me

Remove previous route in graphhopper android?

I am using graphhopper and mapsforge to show the route in my android app.The route is shown in my mapView from the polyline but when I change the location of second point the new route is shown above the previous route.So I need to delete this previous route when a new route is calculated. The code is as follows:
GraphHopper localGraphHopper = new GraphHopper().forMobile();
localGraphHopper.setCHShortcuts(true, true);
localGraphHopper.load(getFolderPath());
GHRequest localGHRequest = new GHRequest(paramDouble1, paramDouble2, paramDouble3, paramDouble4);
GHRequest a = localGHRequest.setAlgorithm("dijkstrabi");
GHResponse localGHResponse = localGraphHopper.route(localGHRequest);
int i = localGHResponse.getPoints().getSize();
PointList localPointList = localGHResponse.getPoints();
Polyline localPolyline = new Polyline(createPaint(AndroidGraphicFactory.INSTANCE.createColor(Color.RED), 4, Style.STROKE), AndroidGraphicFactory.INSTANCE);
this.latLongs_track = localPolyline.getLatLongs();
for (int j = 0;; j++)
{
if (j >= i)
{
this.mapView.getLayerManager().getLayers().add(localPolyline);
LatLong localLatLong = new LatLong((paramDouble1 + paramDouble3) / 2.0D, (paramDouble2 + paramDouble4) / 2.0D);
this.mapView.getModel().mapViewPosition.setCenter(localLatLong);
return;
}
this.latLongs_track.add(new LatLong(localPointList.getLatitude(j), localPointList.getLongitude(j)));
}
Use this function:
public void calcPath( final double fromLat, final double fromLon,
final double toLat, final double toLon ) {
log("calculating path ...");
new AsyncTask<Void, Void, GHResponse>(){
float time;
protected GHResponse doInBackground( Void... v ){
StopWatch sw = new StopWatch().start();
GHRequest req = new GHRequest(fromLat, fromLon, toLat, toLon).
setAlgorithm(AlgorithmOptions.DIJKSTRA_BI);
req.getHints().
put("instructions", "false");
GHResponse resp = hopper.route(req);
time = sw.stop().getSeconds();
return resp;
}
protected void onPostExecute( GHResponse resp ){
if (!resp.hasErrors()){
log("from:" + fromLat + "," + fromLon + " to:" + toLat + ","
+ toLon + " found path with distance:" + resp.getDistance()
/ 1000f + ", nodes:" + resp.getPoints().getSize() + ", time:"
+ time + " " + resp.getDebugInfo());
logUser("the route is " + (int) (resp.getDistance() / 100) / 10f
+ "km long, time:" + resp.getMillis() / 60000f + "min, debug:" + time);
mapView.getLayerManager().getLayers().add(createPolyline(resp));
//mapView.redraw();
} else{
logUser("Error:" + resp.getErrors());
}
shortestPathRunning = false;
}
}.execute();
}
All source you can find at https://github.com/graphhopper/graphhopper
I have found the answer for my problem and am posting here
Polyline localPolyline;
public void calcPath( final double fromLat, final double fromLon,
final double toLat, final double toLon )
{
log("calculating path ...");
new AsyncTask<Void, Void, GHResponse>()
{
float time;
protected GHResponse doInBackground( Void... v )
{
StopWatch sw = new StopWatch().start();
GHRequest req = new GHRequest(fromLat, fromLon, toLat, toLon).
setAlgorithm(AlgorithmOptions.DIJKSTRA_BI);
req.getHints()
.put("instructions", "false");
GHResponse resp = hopper.route(req);
time = sw.stop().getSeconds();
return resp;
}
protected void onPostExecute( GHResponse resp )
{
if (!resp.hasErrors())
{
if(localPolyline!=null){
mapView.getLayerManager().getLayers().remove(localPolyline);
}
else{
log("here");
}
log("from:" + fromLat + "," + fromLon + " to:" + toLat + ","
+ toLon + " found path with distance:" + resp.getDistance()
/ 1000f + ", nodes:" + resp.getPoints().getSize() + ", time:"
+ time + " " + resp.getDebugInfo());
logUser("the route is " + (int) (resp.getDistance() / 100) / 10f
+ "km long, time:" + resp.getMillis() / 60000f + "min, debug:" + time);
localPolyline=createPolyline(resp);
mapView.getLayerManager().getLayers().add(localPolyline);
} else
{
logUser("Error:" + resp.getErrors());
}
}
}.execute();
}
Thanks to everybody.

Get location name from fetched coordinates

What i have: currently my app is only telling me the coordinates of my current location.
What i want: Get location name from coordinates fetched by gps, so that i could know where exactly i am. (Name of location)
Here is complete code from fetching long - lat to getting address:
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), true);
Location locations = locationManager.getLastKnownLocation(provider);
List<String> providerList = locationManager.getAllProviders();
if(null!=locations && null!=providerList && providerList.size()>0){
double longitude = locations.getLongitude();
double latitude = locations.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if(null!=listAddresses&&listAddresses.size()>0){
String _Location = listAddresses.get(0).getAddressLine(0);
}
} catch (IOException e) {
e.printStackTrace();
}
}
You can us the GeoCoder which is available in android.location.Geocoder package. The JavaDocs gives u full explaination. The possible sample for u.
List<Address> list = geoCoder.getFromLocation(location
.getLatitude(), location.getLongitude(), 1);
if (list != null & list.size() > 0) {
Address address = list.get(0);
result = address.getLocality();
return result;
The result will return the name of the location.
Here i am given a single just pass the latitude and longitude in this function then you got all the information related to this latitude and longitude.
public void getAddress(double lat, double lng) {
Geocoder geocoder = new Geocoder(HomeActivity.mContext, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Address obj = addresses.get(0);
String add = obj.getAddressLine(0);
GUIStatics.currentAddress = obj.getSubAdminArea() + ","
+ obj.getAdminArea();
GUIStatics.latitude = obj.getLatitude();
GUIStatics.longitude = obj.getLongitude();
GUIStatics.currentCity= obj.getSubAdminArea();
GUIStatics.currentState= obj.getAdminArea();
add = add + "\n" + obj.getCountryName();
add = add + "\n" + obj.getCountryCode();
add = add + "\n" + obj.getAdminArea();
add = add + "\n" + obj.getPostalCode();
add = add + "\n" + obj.getSubAdminArea();
add = add + "\n" + obj.getLocality();
add = add + "\n" + obj.getSubThoroughfare();
Log.v("IGA", "Address" + add);
// Toast.makeText(this, "Address=>" + add,
// Toast.LENGTH_SHORT).show();
// TennisAppActivity.showDialog(add);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
I hope you get the solution to your answer.

Categories

Resources