Hello guys this may be dumb question but am struggling with this so far haven't found any solution. Now let me ask my doubt am using multiple polyline for plotting multiple routes each and every polyline has different colors but when two point intersects last polyline get overridden how to prevent it. How it must look is only first route should get one color and all the other routes must have same color how to do this let me post the code what i have tried so far:
public class GetDistance extends AsyncTask<Double, Void, String> {
private ProgressDialog pd;
private static final int READ_TIMEOUT = 6000;
private static final int CONNECTION_TIMEOUT = 6000;
private int flag;
public GetDistance(int flag) {
this.flag=flag;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(VisitTravel.this);
pd.setMessage("Please wait");
pd.show();
}
#Override
protected String doInBackground(Double... strings) {
URL url;
try {
url = new URL("http://maps.googleapis.com/maps/api/directions/json?origin=" + strings[0] + "," + strings[1] + "&destination=" + strings[2] + "," + strings[3] + "&sensor=false&units=metric&mode=driving&alternatives=true");
HttpURLConnection conn;
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
InputStream in;
in = new BufferedInputStream(conn.getInputStream());
StringBuilder buffer = new StringBuilder();
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(in));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine).append("\n");
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
Log.e("empty", "empty");
}
JsonResponse = buffer.toString();
Log.d("response", JsonResponse);
} catch (IOException e1) {
e1.printStackTrace();
}
return JsonResponse;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pd.dismiss();
if(flag==1) {
new ParserTask().execute(result);
}}
}
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
private ArrayList<LatLng> points;
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionJSONParser parser = new DirectionJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
PolylineOptions polylineOptionss=null;
// MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<>();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
if (j == 0) {
duration = point.get("duration");
Log.d("duration", duration);
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
polylineOptionss=new PolylineOptions();
// Adding all the points in the route to LineOptions
polylineOptionss.addAll(points);
// polylineOptions.width(7);
// Random rnd = new Random();
// int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
if(i==0) {
polylineOptions0=new PolylineOptions();
polylineOptions0.addAll(points);
// mGoogleMap.setTrafficEnabled(true);
polylineOptions0.width(15);
polylineOptions0.color(Color.parseColor("#9c27b0"));
polylineOptions0.geodesic(true);
Polyline polyline= mGoogleMap.addPolyline(polylineOptions0);
polyline.setTag(duration);
polyline.setClickable(true);
}
//Here only differentiating each and every route.
else if(i==1){
polylineOptions1=new PolylineOptions();
polylineOptions1.addAll(points);
polylineOptions1.geodesic(true);
polylineOptions1.width(15);
// mGoogleMap.setTrafficEnabled(true);
polylineOptions1.color(Color.parseColor("#9e9e9e"));
Polyline polyline= mGoogleMap.addPolyline(polylineOptions1);
polyline.setTag(duration);
polyline.setClickable(true);
///
}
else if(i==2){
polylineOptions2=new PolylineOptions();
polylineOptions2.addAll(points);
polylineOptions2.geodesic(true);
polylineOptions2.width(15);
polylineOptions2.color(Color.parseColor("#9c27b0"));
Polyline polyline= mGoogleMap.addPolyline(polylineOptions2);
polyline.setTag(duration);
polyline.setClickable(true);
// mGoogleMap.setTrafficEnabled(true);
//
}
else {
polylineOptions3=new PolylineOptions();
polylineOptions3.addAll(points);
// mGoogleMap.setTrafficEnabled(true);
polylineOptions3.width(15);
polylineOptions3.geodesic(true);
polylineOptions3.color(Color.parseColor("#9e9e9e"));
Polyline polyline= mGoogleMap.addPolyline(polylineOptions3);
polyline.setTag(duration);
polyline.setClickable(true);
/// polylineOptions3.color(Color.parseColor("#ffffff"));
}
}
setBottomSheet(jsonresponse, edt.getText().toString(),1);
CameraAnimation(polylineOptionss);
// mGoogleMap.addPolyline(polylineOptions);
// Drawing polyline in the Google Map for the i-th route
}
}
How to plot first route with one color from starting to end and then remaining routes with other color. Thanks in advance !!
Use Z-Index variable of Polyline and Use Polylineclick listener to change the z-index of the polylines. Means whenever you click any line, its z-index will be increased and other lines z-index will be decreased so that the line you clicked will always override others. See the attached code for help.
Z-Index
The order in which this tile overlay is drawn with respect to other overlays (including GroundOverlays, TileOverlays, Circles, and Polygons but not Markers). An overlay with a larger z-index is drawn over overlays with smaller z-indices. The order of overlays with the same z-index is arbitrary. The default zIndex is 0.
final List<Polyline> polylines = new ArrayList<>();
for(int i= 0; i<paths.size(); i++ ){
polylines.add(mMap.addPolyline(paths.get(i)));
}
mMap.setOnPolylineClickListener(new GoogleMap.OnPolylineClickListener() {
#Override
public void onPolylineClick(Polyline polyline) {
for(int i= 0; i<polylines.size(); i++ ){
polylines.get(i).setColor(Color.argb(255,187,189,191));
polylines.get(i).setZIndex(0);
}
polyline.setColor(Color.argb(255,102,157,246));
polyline.setZIndex(2);
}
});
One possible solution might be to vary the strokeWidth of the overlapping section of the polyline so that the first one drawn is wider and therefore can still be seen under the subsequent ones. Just an idea, not tested.
Related
I have a code to draw a route for the user. But, I would like it to be drawn, the alternative routes, too. I changed the URL by passing the parameter alternatives=true and also the source code to bring the other routes. But, it's just being drawn, just one route.
I made these changes, based on the questions and answers, also here on the page.
Code:
Map, receive the polylines and draw to user:
if (rota != null) {
map.addPolyline(ApplicationUtils.getApplicationUtils().getPolylineOptions());
//Adicionando ponto inicial
CircleOptions circle = new CircleOptions().center(ultimaLocation);
circle.fillColor(Color.DKGRAY);
circle.radius(15); // Em metros
map.addCircle(circle);
}
Calculate route:
public void calculateRoute(LatLng origin, LatLng dest, String mode, RotaListener rotaListener) {
this.rotaListener = rotaListener;
try {
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origem, destino, modo);
Log.d(TAG, "URL DIRECTIONS = " + url);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
} catch (Exception e) {
rotaListener.onFailure(e);
}
}
private String getDirectionsUrl(LatLng origin, LatLng dest, String mode) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
String str_mode = "mode=" + mode;
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + str_mode +"&alternatives=true" ;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters + "&key=" + MY_API_KEY;
;
return url;
}
/**
* A class to download data from Google Directions URL
*/
private class DownloadTask extends AsyncTask<String, Void, String> {
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
try {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
} catch (Exception e) {
rotaListener.onFailure(e);
return "";
}
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
try {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
if (rotaListener != null) {
rotaListener.onRotaChanged(result);
parserTask.execute(result);
}
} catch (Exception e) {
rotaListener.onFailure(e);
}
}
}
/**
* A class to parse the Google Directions in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, PolylineOptions> {
// Parsing the data in non-ui thread
#Override
protected PolylineOptions doInBackground(String... jsonData) {
try {
JSONObject jObject;
List<Rota> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
// Traversing through all the routes
for (int i = 0; i < routes.size(); i++) {
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = routes.get(i).Pontos;
rotaListener.onTempoRotaChanged(routes.get(i).TempoEstimadoMin);
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(LARGURA_ROTA);
lineOptions.color(COR_ROTA);
lineOptions.geodesic(true);
ApplicationUtils.getApplicationUtils().setPolylineOptions(lineOptions);
}
return lineOptions;
} catch (Exception e) {
rotaListener.onFailure(e);
return null;
}
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(PolylineOptions result) {
// Drawing polyline in the Google Map for the i-th route
try {
if (rotaListener != null) {
rotaListener.onInstrucoesRotaChanged(result);
rotaListener = null;
}
} catch (Exception e) {
rotaListener.onFailure(e);
}
}
}
public class DirectionsJSONParser {
/**
* Receives a JSONObject and returns a list of lists containing latitude and longitude
*/
public List<Rota> parse(JSONObject jObject) {
List<Rota> routes = new ArrayList<Rota>();
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
JSONObject jDuration = null;
Rota rota;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for (int i = 0; i < jRoutes.length(); i++) {
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for (int j = 0; j < jLegs.length(); j++) {
jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
rota = new Rota();
jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
if (jDuration != null) {
rota.TempoEstimadoMin = jDuration.getInt("value") / 60;
}
/** Traversing all steps */
for (int k = 0; k < jSteps.length(); k++) {
String polyline = "";
polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
/** Traversing all points */
for (int l = 0; l < list.size(); l++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng) list.get(l)).latitude));
hm.put("lng", Double.toString(((LatLng) list.get(l)).longitude));
path.add(hm);
}
}
rota.Pontos = path;
routes.add(rota);
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
}
return routes;
}
If possible, I would like some help so that I can draw more than one route for the user.
Thank you!
I think you should be doing this inside of the doInBackground task:
for (int i = 0; i < routes.size(); i++) {
...
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(LARGURA_ROTA);
// Change the color with every new iteration of the route
lineOptions.color(COR_ROTA);
lineOptions.geodesic(true);
ApplicationUtils.getApplicationUtils().setPolylineOptions(lineOptions)
map.addPolyline(ApplicationUtils.getApplicationUtils().getPolylineOptions());
lineOptions = null;
}
We're using slightly different libraries, but this is what my code looks like (encoded path is a string representing a group of lat/lons):
pathDynamic = new PolylineOptions().width(15).color(Color.RED);
pathDynamic.addAll(decode(item.getEncodedPath()));
if (mMap != null) {
mMap.addPolyline(pathDynamic);
}
I resolved by changing my parser class.
Adding points in each iteration of FOR to specific variables
private class ParserTask1 extends AsyncTask<String, Integer, List<List<List<HashMap<String, String>>>>> {
// Parsing the data in non-ui thread
#Override
protected List<List<List<HashMap<String, String>>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<List<HashMap<String, String>>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser1 parser = new DirectionsJSONParser1();
// Starts parsing data
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<List<HashMap<String, String>>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = new PolylineOptions();
PolylineOptions lineOptions1 = null;
List<LatLng> aline1 = new ArrayList<LatLng>();
List<LatLng> aline2 = new ArrayList<LatLng>();
List<LatLng> aline3 = new ArrayList<LatLng>();
Rota rota = new Rota();
List<HashMap<String, String>> rotaNumero = new ArrayList<>();
HashMap<String, String> pointNumber = null;
if (result != null) {
int i = 0;
Log.d(SHETTY, "onPostExecute: result size " + result.size());
while (i < result.size()) {
// for(int i=0;i<result.size();i++){
//result.size()
//int g= i-1;
points = new ArrayList<LatLng>();
// lineOptions = new PolylineOptions();
// if(i==1){
// }else{
List<List<HashMap<String, String>>> path1 = result.get(i);
for (int s = 0; s < path1.size(); s++) {
Log.d("pathsize1", path1.size() + "");
// Fetching i-th route
List<HashMap<String, String>> path = path1.get(s);
Log.d("pathsize", path.size() + "");
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
lineOptions1 = new PolylineOptions();
HashMap<String, String> point = path.get(j);
pointNumber = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
// Log.d("latlng", position.toString());
points.add(position);
}
}
if (i == 0) {
rotaNumero.add(pointNumber);
ApplicationUtils.getApplicationUtils().setPoints(rotaNumero);
aline1.addAll(points);
ApplicationUtils.getApplicationUtils().setAline1(aline1);
rotaNumero.clear();
} else if (i == 1) {
rotaNumero.add(pointNumber);
ApplicationUtils.getApplicationUtils().setPoints2(rotaNumero);
aline2.addAll(points);
ApplicationUtils.getApplicationUtils().setAline2(aline2);
rotaNumero.clear();
} else if (i == 2) {
rotaNumero.add(pointNumber);
ApplicationUtils.getApplicationUtils().setPoints2(rotaNumero);
aline3.addAll(points);
ApplicationUtils.getApplicationUtils().setAline3(aline3);
rotaNumero.clear();
}
// Adding all the points in the route to LineOptions
i++;
}
try {
if (rotaListener != null) {
rotaListener.onInstrucoesRotaChanged(lineOptions.addAll(ApplicationUtils.getApplicationUtils().getAline1()));
rotaListener = null;
}
} catch (Exception e) {
rotaListener.onFailure(e);
}
}
}
}
After inserting the points, in my class where I have the map, I draw the routes.
private void drawRoutes() {
line1 = new PolylineOptions().width(10).color(baseActivity.getResources().getColor(R.color.btn_map_inserir_pressed));
line2 = new PolylineOptions().width(10).color(baseActivity.getResources().getColor(R.color.verde_novo));
line3 = new PolylineOptions().width(10).color(baseActivity.getResources().getColor(R.color.azul));
line1.addAll(ApplicationUtils.getApplicationUtils().getAline1());
map.addPolyline(line1);
if (ApplicationUtils.getApplicationUtils().getAline2() != null) {
line2.addAll(ApplicationUtils.getApplicationUtils().getAline2());
map.addPolyline(line2);
}
if (ApplicationUtils.getApplicationUtils().getAline3() != null) {
line3.addAll(ApplicationUtils.getApplicationUtils().getAline3());
map.addPolyline(line3);
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have to draw a route between two addresses which are written in two place autocomplete fragments. I searched for it but most code are of onclick event. I have to draw polyline based on the address written in the fragments. Can you give me a general idea on how to write a code for this?
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
Context context;
Polyline polyline;
Marker markers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
addMarker(place);
// Log.i(TAG, "Place: " + place.getName());
String placeName = place.getName().toString();
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
//Log.i(TAG, "An error occurred: " + status);
}
});
final PlaceAutocompleteFragment autocompleteFragments = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragments);
autocompleteFragments.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
addMarker(place);
// Log.i(TAG, "Place: " + place.getName());
String placeName = place.getName().toString();
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
//Log.i(TAG, "An error occurred: " + status);
}
});
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(final GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
//LatLng warora = new LatLng(20.2407, 79.0136);
//LatLng amravati=new LatLng(20.9374,77.7796);
/*LatLng nagpur=new LatLng(21.1458,79.0882);
PolylineOptions polylineOptions=new PolylineOptions().add(warora).add(nagpur).width(5).color(Color.BLUE)
.geodesic(true);
googleMap.addPolyline(polylineOptions);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(warora,8));
mMap.addMarker(new MarkerOptions().position(warora).title("Marker in India"));
//mMap.addMarker(new MarkerOptions().position(amravati).title("Marker in Pune"));
mMap.addMarker(new MarkerOptions().position(nagpur).title("Marker in Nagpur"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(warora));
*/
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
}
public void addMarker(Place p) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(p.getLatLng()).title(p.getName() + "");
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(p.getLatLng()));
mMap.animateCamera(CameraUpdateFactory.zoomTo(9));
}
}
In my code, I have added the marker but both the search box are calling one method(addMarker). I guess that's the reason i can't get the polyline between them. I tried make to different method with same code and then add polyline but it did not work.
I'm giving you code for drawing path plus getting driving distance and travel time.
Create a new java file namely “DirectionsJSONParser.java”:
public class DirectionsJSONParser {
/** Receives a JSONObject and returns a list of lists containing
latitude and longitude */
public List<List<HashMap<String,String>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new
ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
JSONObject jDistance = null;
JSONObject jDuration = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List<HashMap<String, String>> path = new
ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
/** Getting distance from the json data */
jDistance = ((JSONObject)
jLegs.get(j)).getJSONObject("distance");
HashMap<String, String> hmDistance = new HashMap<String,
String>();
hmDistance.put("distance", jDistance.getString("text"));
/** Getting duration from the json data */
jDuration = ((JSONObject)
jLegs.get(j)).getJSONObject("duration");
HashMap<String, String> hmDuration = new HashMap<String,
String>();
hmDuration.put("duration", jDuration.getString("text"));
/** Adding distance object to the path */
path.add(hmDistance);
/** Adding duration object to the path */
path.add(hmDuration);
jSteps = (
(JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)
((JSONObject)jSteps.get(k)).get("polyline"))
.get("points");
List<LatLng> list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l<list.size();l++){
HashMap<String, String> hm = new HashMap<String,
String>();
hm.put("lat",
Double.toString(((LatLng)list.get(l))
.latitude) );
hm.put("lng",
Double.toString(((LatLng)list.get(l))
.longitude) );
path.add(hm);
}
}
}
routes.add(path);
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes;
}
/**
* Method to decode polyline points
* Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-
google-maps-direction-api-with-java
* */
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.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 = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
Now in MainActivity where your map exists:
public class MainActivity extends FragmentActivity {
GoogleMap map;
ArrayList<LatLng> markerPoints;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing
markerPoints = new ArrayList<LatLng>();
// Getting reference to SupportMapFragment of the activity_main
SupportMapFragment fm =
(SupportMapFragment)getSupportFragmentManager().
findFragmentById(R.id.map);
// Getting Map for the SupportMapFragment
map = fm.getMap();
// Enable MyLocation Button in the Map
map.setMyLocationEnabled(true);
// Setting onclick event listener for the map
map.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
// Already two locations
if(markerPoints.size()>1){
markerPoints.clear();
map.clear();
}
// Adding new item to the ArrayList
markerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if(markerPoints.size()==1){
options.icon(BitmapDescriptorFactory.
defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}else if(markerPoints.size()==2){
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
// Add new marker to the Google Map Android API V2
map.addMarker(options);
// Checks, whether start and end locations are captured
if(markerPoints.size() >= 2){
LatLng origin = markerPoints.get(0);
LatLng dest = markerPoints.get(1);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions
API
downloadTask.execute(url);
}
}
});
}
private String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor;
// Output format
String output = "json";
// Building the url to the web service
String url =
"https://maps.googleapis.com/maps/api/directions/"+output+"?"
+parameters;
return url;
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new
InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String>{
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer,
List<List<HashMap<String,String>>> >{
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>>
doInBackground(String...
jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try{
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String,
String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
String distance = "";
String duration = "";
if(result.size()<1){
Toast.makeText(getBaseContext(), "No Points",
Toast.LENGTH_SHORT).show();
return;
}
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
if(j==0){ // Get distance from the list
distance = (String)point.get("distance");
continue;
}else if(j==1){ // Get duration from the list
duration = (String)point.get("duration");
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
That's it!
Here is the link if you need more explanation.
You need to get the coordinates of your two addresses - Google Maps has an API library that does this. Then follow the guide to draw a polyline on your map at this link. Follow the guides at both links and you should be sorted. Hope this helps.
Use google directions API to get the waypoints between your 2 addresses.There is a Util lib by Google to help you show the "overview_polyline" from the response on the map.
I'm making an android studio application in which a user can see the best sortest paths between two location points. I use Normal android studio map frame and SupportMapFragment to show google map.I want to find the best route in multiple waypoints.These are the file of my android application. only one issue in this project file MapsActivity.java file getmap method is not working. is there any other way develop this one?
public class MapsActivity extends FragmentActivity {
GoogleMap map;
ArrayList<LatLng> markerPoints;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Initializing
markerPoints = new ArrayList<LatLng>();
// Getting reference to SupportMapFragment of the activity_main
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
// Getting reference to Button
Button btnDraw = (Button)findViewById(R.id.btn_draw);
// Getting Map for the SupportMapFragment
map = fm.getMap();
// Enable MyLocation Button in the Map
map.setMyLocationEnabled(true);
// Setting onclick event listener for the map
map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
// Already 10 locations with 8 waypoints and 1 start location and 1 end location.
// Upto 8 waypoints are allowed in a query for non-business users
if(markerPoints.size()>=10){
return;
}
// Adding new item to the ArrayList
markerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED and
* for the rest of markers, the color is AZURE
*/
if(markerPoints.size()==1){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}else if(markerPoints.size()==2){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}else{
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
}
// Add new marker to the Google Map Android API V2
map.addMarker(options);
}
});
// The map will be cleared on long click
map.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
// Removes all the points from Google Map
map.clear();
// Removes all the points in the ArrayList
markerPoints.clear();
}
});
// Click event handler for Button btn_draw
btnDraw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Checks, whether start and end locations are captured
if(markerPoints.size() >= 2){
LatLng origin = markerPoints.get(0);
LatLng dest = markerPoints.get(1);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
});
}
private String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Waypoints
String waypoints = "";
for(int i=2;i<markerPoints.size();i++){
LatLng point = (LatLng) markerPoints.get(i);
if(i==2)
waypoints = "waypoints=";
waypoints += point.latitude + "," + point.longitude + "|";
}
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor+"&"+waypoints;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
return url;
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String>{
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> > {
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try{
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
}
}
}
other file DirectionsJSONParser.java
public class DirectionsJSONParser {
/**
* Receives a JSONObject and returns a list of lists containing latitude and longitude
*/
public List<List<HashMap<String, String>>> parse(JSONObject jObject) {
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for (int i = 0; i < jRoutes.length(); i++) {
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for (int j = 0; j < jLegs.length(); j++) {
jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for (int k = 0; k < jSteps.length(); k++) {
String polyline = "";
polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
/** Traversing all points */
for (int l = 0; l < list.size(); l++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng) list.get(l)).latitude));
hm.put("lng", Double.toString(((LatLng) list.get(l)).longitude));
path.add(hm);
}
}
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
}
return routes;
}
/**
* Method to decode polyline points
* Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
*/
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.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 = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
other file activity_maps.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="#+id/btn_draw"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<fragment
android:id="#+id/map"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#id/btn_draw" />
</RelativeLayout>
To get map, use this:
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Your activity must implement OnMapReadyCallback and override onMapReady(GoogleMap googleMap) function.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{
.....
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
}
See Getting Started guide.
This may be asked many time but none of the solutions worked for me when i try to plot multiple routes with different polyline i need to show the each polyline with different color but what am getting is black color polyline which i haven't used anywhere let me post my screen shot of the map
Let me post my colde ,am using google map api for fetching location;
public class GetDistance extends AsyncTask<Double, Void, String> {
private ProgressDialog pd;
private static final int READ_TIMEOUT = 6000;
private static final int CONNECTION_TIMEOUT = 6000;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(VisitTravel.this);
pd.setMessage("Please wait");
pd.show();
}
#Override
protected String doInBackground(Double... strings) {
URL url;
try {
url = new URL("http://maps.googleapis.com/maps/api/directions/json?origin=" + strings[0] + "," + strings[1] + "&destination=" + strings[2] + "," + strings[3] + "&sensor=false&units=metric&mode=driving&alternatives=true");
HttpURLConnection conn;
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
InputStream in;
in = new BufferedInputStream(conn.getInputStream());
StringBuilder buffer = new StringBuilder();
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(in));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine).append("\n");
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
Log.e("empty", "empty");
}
JsonResponse = buffer.toString();
Log.d("response", JsonResponse);
} catch (IOException e1) {
e1.printStackTrace();
}
return JsonResponse;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pd.dismiss();
new ParserTask().execute(result);
}
}
This is paresertask code:
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
private ArrayList<LatLng> points;
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionJSONParser parser = new DirectionJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
PolylineOptions polylineOptionss=null;
// MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<>();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
if (j == 0) {
duration = point.get("duration");
Log.d("duration", duration);
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
polylineOptionss=new PolylineOptions();
// Adding all the points in the route to LineOptions
polylineOptionss.addAll(points);
// polylineOptions.width(7);
// Random rnd = new Random();
// int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
//Here only am creating polyline for different points but am getting black
if(i==0) {
PolylineOptions polylineOptions0=new PolylineOptions();
polylineOptions0.addAll(points);
// mGoogleMap.setTrafficEnabled(true);
polylineOptions0.width(15);
polylineOptions0.color(Color.parseColor("#9c27b0"));
polylineOptions0.geodesic(true);
mGoogleMap.addPolyline(polylineOptions0);
}
else if(i==1){
PolylineOptions polylineOptions1=new PolylineOptions();
polylineOptions1.addAll(points);
polylineOptions1.geodesic(true);
polylineOptions1.width(15);
// mGoogleMap.setTrafficEnabled(true);
mGoogleMap.addPolyline(polylineOptions1);
polylineOptions1.color(Color.parseColor("#ffffff"));
}
else if(i==2){
PolylineOptions polylineOptions2=new PolylineOptions();
polylineOptions2.addAll(points);
polylineOptions2.geodesic(true);
polylineOptions2.width(15);
mGoogleMap.addPolyline(polylineOptions2);
// mGoogleMap.setTrafficEnabled(true);
polylineOptions2.color(Color.parseColor("#ffffff"));
}
else {
PolylineOptions polylineOptions3=new PolylineOptions();
polylineOptions3.addAll(points);
// mGoogleMap.setTrafficEnabled(true);
polylineOptions3.width(15);
polylineOptions3.geodesic(true);
mGoogleMap.addPolyline(polylineOptions3);
polylineOptions3.color(Color.parseColor("#ffffff"));
}
}
CameraAnimation(polylineOptionss);
// mGoogleMap.addPolyline(polylineOptions);
// Drawing polyline in the Google Map for the i-th route
}
Can someone please tell me how to differentiate the polyline with different colors am struggling with this. Thanks in advance!!!
Just move your polylineOptions.color(); code before mGoogleMap.addPolyline().
For example:
polylineOptions1.color(Color.parseColor("#ffffff"));
mGoogleMap.addPolyline(polylineOptions1);
I'm trying to implement an simple navigation app using Google maps. Initially I developed a code for marking two Geo points on map and showing route between them.
Now I am trying to move the first marker towards second marker (destination) based on users location.
For this I used LocationListener and implemented code in onLocationChanged.
The problem is onLocationChanged is not getting fired and marker is not moving based on user location.
Here is my code.
MapActivity.java
public class MapActivity extends FragmentActivity implements OnMapClickListener, LocationListener{
private GoogleMap gMap;
private ArrayList<LatLng> markersArray; //Marker points ArrayList
private ArrayList<Marker> markers;
private MarkerOptions options; //Marker options
String distance="";
String duration="";
private TextView travelDetails;
private ProgressDialog pDialog;
private double lattitude=0.0;
private double longitude=0.0;
Marker mMarker;
String bestAvailableProvider;
private LocationManager mLocationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
//Loading Google Maps
try{
loadMapView();
markersArray=new ArrayList<LatLng>();
markers=new ArrayList<Marker>();
gMap.setOnMapClickListener(this);
gMap.setMyLocationEnabled(true);
gMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
travelDetails=(TextView) findViewById(R.id.lbl_traveldetails);
pDialog=new ProgressDialog(MapActivity.this);
}catch(Exception e){
e.printStackTrace();
}
}
/*
* This method loads map
*
*/
private void loadMapView(){
if (gMap==null) {
gMap=((SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map_fragment)).getMap();
}
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
// Specify Location Provider criteria
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setSpeedRequired(false);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,this);
}
/*
* catches onclick event of map
* #see com.google.android.gms.maps.GoogleMap.OnMapClickListener#onMapClick(com.google.android.gms.maps.model.LatLng)
*/
#Override
public void onMapClick(LatLng point) {
//Clearing markers in map
if (markersArray.size()>1) {
markersArray.clear();
gMap.clear();
}
//Adding marker to array
markersArray.add(point);
//marking point on Map
addMarkerOnMap(point);
//Drawing route when two markers are placed
if(markersArray.size() >= 2){
LatLng origin = markersArray.get(0);
LatLng dest = markersArray.get(1);
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}
}
/*
* This method places markers on map
*/
private void addMarkerOnMap(LatLng point){
//Marking points on map
options=new MarkerOptions();
options.position(point);
//Setting marker icons
if (markersArray.size()==1) {
//Source marker point
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}else if(markersArray.size()==2){
//Destination marker point
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
//adding marker point to map
try{
Marker mMarker=gMap.addMarker(options);
markers.add(mMarker);
}catch(Exception e){
e.printStackTrace();
}
}
/*
* Getting direction url between two points
*
*/
private String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor;
// Output format
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
return url;
}
/*
* passing the direction url
*
*/
private class DownloadTask extends AsyncTask<String, Void, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.show();
pDialog.setMessage("Loading route...");
pDialog.setCancelable(false);
}
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/*
* downloading from url
*
*/
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>>>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try{
jObject = new JSONObject(jsonData[0]);
DirectionsJsonParser parser = new DirectionsJsonParser();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
// MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
if(j==0){ // Get distance from the list
distance = (String)point.get("distance");
continue;
}else if(j==1){ // Get duration from the list
duration = (String)point.get("duration");
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(5);
lineOptions.color(Color.BLUE);
}
// Drawing polyline in the Google Map for the i-th route
try{
gMap.addPolyline(lineOptions);
travelDetails.setText("Distance:"+distance+"Duration:"+duration);
pDialog.dismiss();
}catch (Exception e) {
if (pDialog.isShowing()) {
pDialog.dismiss();
}
Toast.makeText(getApplicationContext(), "No Road route found.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
#Override
protected void onResume() {
super.onResume();
loadMapView();
}
#Override
protected void onPause() {
super.onPause();
mLocationManager.removeUpdates(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
/*
* (non-Javadoc)
* #see com.google.android.gms.maps.LocationSource.OnLocationChangedListener#onLocationChanged(android.location.Location)
*/
#Override
public void onLocationChanged(Location location) {
Log.e("loca", ""+location.getLatitude());
try {
if(markersArray.size()>0){
lattitude=location.getLatitude();
longitude=location.getLongitude();
LatLng mLatLng=new LatLng(lattitude, longitude);
Marker newMarker=markers.get(0);
newMarker.setPosition(mLatLng);
gMap.animateCamera(CameraUpdateFactory.newLatLng(mLatLng));
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
DirectionsJsonParser.java
public class DirectionsJsonParser {
public List<List<HashMap<String,String>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
JSONObject jDistance = null;
JSONObject jDuration = null;
try {
jRoutes = jObject.getJSONArray("routes");
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
for(int j=0;j<jLegs.length();j++){
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Getting distance from the json data */
jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
HashMap<String, String> hmDistance = new HashMap<String, String>();
hmDistance.put("distance", jDistance.getString("text"));
/** Getting duration from the json data */
jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
HashMap<String, String> hmDuration = new HashMap<String, String>();
hmDuration.put("duration", jDuration.getString("text"));
/** Adding distance object to the path */
path.add(hmDistance);
/** Adding duration object to the path */
path.add(hmDuration);
/** Getting poly points */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
for(int l=0;l<list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
/** Adding poly points */
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes;
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.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 = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
I think you have not used location provider , use googleapiclient
and read about this topic , it allows you to show your current position on map when location changed, that provides you your current locations.
Hint
Implements GoogleApiClient.ConnectionCallbacks , GoogleApiClient.OnConnectionFailedListener
in your activity then you can easily do that.