How to draw polyline on google map in android passing json array? - android

Hye guys I am working on the project of vehicle tracking system when user can enters the number of vehicle the the draw a poly line on the vehicles route...
I have stored route locations with their latitude and longitude into mysql database I used asynctask method to fetch this data....
now this is my code in getRoute method
getRoute method will be call on the button click when user enters the number in EditText
public void getRoute()
{
final String BusNo = editBusNo.getText().toString().trim();
Log.i(TAG,"value of the Bus No is "+ BusNo);
class GetRoute extends AsyncTask<Void,Void,String>
{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.i(TAG,"in pre execute");
loading = ProgressDialog.show(MapsActivity.this, "Fetching...", "Wait...", false, false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Log.i(TAG,"post execute");
JSON_STRING = s;
Log.i(TAG,"value of json_string "+ JSON_STRING);
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequestParam("http://192.168.1.35/projects/map.php?name=", BusNo);
Log.i(TAG,"value of s is "+ s);
//Log.i(T,"The value of s is "+ s);
return s;
}
}
GetRoute gr = new GetRoute();
gr.execute();
}
Looking for this type of polyline

Try this,
Polyline polyline;
PolylineOptions polylineOptions = new PolylineOptions();
JSONArray arr = response.getJSONArray("result");
for (int i = 0; i < arr.length(); i++)
{
JSONObject obj = arr.getJSONObject(i);
String latitude = obj.getString("latitude");
String longitude = obj.getString("longitude");
polylineOptions.color(Color.RED);
polylineOptions.width(3);
Double lat = Double.parseDouble(latitude);
Double Longitude = Double.parseDouble(longitude);
polylineOptions.add(new LatLng(lat, Longitude));
}
polyline=map.addPolyline(polylineOptions);
Then when you want to remove it:
polyline.remove();

To plot polyline on google map you need to have List<LatLng> which are stop points between source and destination.
Once you've that List you can plot polyline using below code
// I consider here is list of latlng from database.
List<LatLng> list = getListOfLatLng();
PolylineOptions options = new PolylineOptions().width(10).color(Color.BLUE);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
map.addPolyline(options);
This will plot polylines on map object of GoogleMap.

Related

Draw route between two address [closed]

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.

How to prevent Polyline from overlapping in google maps android?

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.

How to create multi polyline with multiple color in google map android?

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);

Marker is not appearing to select from and to position to calculate and draw path between two marker in google map

Marker is not appearing to select from and to position to calculate and draw path between two marker in google map .
I want to select two location with marker and calculate distance and draw a path between two marker after selection .But unable to selection two location with marker and unable to calculate distance.
I am unable to set from Location with marker ,set to location with marker and not able to calculate distance also .
MapsActivity.java
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnMarkerDragListener,
GoogleMap.OnMapLongClickListener,
View.OnClickListener{
//Our Map
private GoogleMap mMap;
//To store longitude and latitude from map
private double longitude;
private double latitude;
//From -> the first coordinate from where we need to calculate the distance
private double fromLongitude;
private double fromLatitude;
//To -> the second coordinate to where we need to calculate the distance
private double toLongitude;
private double toLatitude;
//Google ApiClient
private GoogleApiClient googleApiClient;
//Our buttons
private Button buttonSetTo;
private Button buttonSetFrom;
private Button buttonCalcDistance;
#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);
//Initializing googleapi client
// ATTENTION: This "addApi(AppIndex.API)"was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(AppIndex.API).build();
buttonSetTo = (Button) findViewById(R.id.buttonSetTo);
buttonSetFrom = (Button) findViewById(R.id.buttonSetFrom);
buttonCalcDistance = (Button) findViewById(R.id.buttonCalcDistance);
buttonSetTo.setOnClickListener(this);
buttonSetFrom.setOnClickListener(this);
buttonCalcDistance.setOnClickListener(this);
}
#Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Maps Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://net.simplifiedcoding.googlemapsdistancecalc/http/host/path")
);
AppIndex.AppIndexApi.start(googleApiClient, viewAction);
}
#Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Maps Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://net.simplifiedcoding.googlemapsdistancecalc/http/host/path")
);
AppIndex.AppIndexApi.end(googleApiClient, viewAction);
}
//Getting current location
private void getCurrentLocation() {
mMap.clear();
//Creating a location object
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
//Getting longitude and latitude
longitude = location.getLongitude();
latitude = location.getLatitude();
//moving the map to location
moveMap();
}
}
//Function to move the map
private void moveMap() {
//Creating a LatLng Object to store Coordinates
LatLng latLng = new LatLng(latitude, longitude);
//Adding marker to map
mMap.addMarker(new MarkerOptions()
.position(latLng) //setting position
.draggable(true) //Making the marker draggable
.title("Current Location")); //Adding a title
//Moving the camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Animating the camera
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){
StringBuilder urlString = new StringBuilder();
urlString.append("https://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString(sourcelat));
urlString.append(",");
urlString
.append(Double.toString( sourcelog));
urlString.append("&destination=");// to
urlString
.append(Double.toString( destlat));
urlString.append(",");
urlString.append(Double.toString(destlog));
urlString.append("&sensor=false&mode=driving&alternatives=true");
urlString.append("&key=AIzaSyB2iWnsp0TvWCrBB5AYYxG8J3Mad4q1npo");
return urlString.toString();
}
private void getDirection(){
//Getting the URL
String url = makeURL(fromLatitude, fromLongitude, toLatitude, toLongitude);
//Showing a dialog till we get the route
final ProgressDialog loading = ProgressDialog.show(this, "Getting Route", "Please wait...", false, false);
//Creating a string request
StringRequest stringRequest = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
//Calling the method drawPath to draw the path
drawPath(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
}
});
//Adding the request to request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
//The parameter is the server response
public void drawPath(String result) {
//Getting both the coordinates
LatLng from = new LatLng(fromLatitude,fromLongitude);
LatLng to = new LatLng(toLatitude,toLongitude);
//Calculating the distance in meters
Double distance = SphericalUtil.computeDistanceBetween(from, to);
//Displaying the distance
Toast.makeText(this,String.valueOf(distance+" Meters"),Toast.LENGTH_SHORT).show();
try {
//Parsing json
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
Polyline line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(20)
.color(Color.RED)
.geodesic(true)
);
}
catch (JSONException e) {
}
}
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;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng latLng = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.setOnMarkerDragListener(this);
mMap.setOnMapLongClickListener(this);
}
#Override
public void onConnected(Bundle bundle) {
getCurrentLocation();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onMapLongClick(LatLng latLng) {
//Clearing all the markers
mMap.clear();
//Adding a new marker to the current pressed position
mMap.addMarker(new MarkerOptions()
.position(latLng)
.draggable(true));
latitude = latLng.latitude;
longitude = latLng.longitude;
}
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
//Getting the coordinates
latitude = marker.getPosition().latitude;
longitude = marker.getPosition().longitude;
//Moving the map
moveMap();
}
#Override
public void onClick(View v) {
if(v == buttonSetFrom){
fromLatitude = latitude;
fromLongitude = longitude;
Toast.makeText(this,"From set",Toast.LENGTH_SHORT).show();
}
if(v == buttonSetTo){
toLatitude = latitude;
toLongitude = longitude;
Toast.makeText(this,"To set",Toast.LENGTH_SHORT).show();
}
if(v == buttonCalcDistance){
getDirection();
}
}
}
activity_maps.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="net.simplifiedcoding.mymapapp.MapsActivity" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#cc3b60a7"
android:orientation="horizontal">
<Button
android:id="#+id/buttonSetFrom"
android:text="Set From"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/buttonSetTo"
android:text="Set To"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/buttonCalcDistance"
android:text="Calc Distance"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
</FrameLayout>
Try this code for draw line between two origin and dest:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(latitude, longitude);
mMap.clear();
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 16);
mMap.animateCamera(cameraUpdate);
System.out.println("Latitude "+latitude+ " \n Longitude "+longitude);
mMap.setMyLocationEnabled(true);
LatLng origin = new LatLng(latitude,longitude);
LatLng dest = new LatLng(Double.parseDouble(destLatitude),Double.parseDouble(destLongitude));
// 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 downloading", 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(5);
lineOptions.color(Color.RED);
}
tvDistanceDuration.setText("Distance:"+distance + ", Duration:"+duration);
// Drawing polyline in the Google Map for the i-th route
mMap.addPolyline(lineOptions);
mMap.addMarker(new MarkerOptions()
.position(new LatLng(Double.parseDouble(destLatitude), Double.parseDouble(destLongitude)))
.title(getLocationStringAddress(new LatLng(Double.parseDouble(destLatitude), Double.parseDouble(destLongitude))))
// .snippet(getLocationStringAddress(new LatLng(Double.parseDouble(destLatitude), Double.parseDouble(destLongitude))))
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.map_set_marker)));
}
}

Can't show google maps android markers from coords stored in mysql db

I can't fetch markers from coordinates stored in a mysql db. Where's the error in my codes?
P.S. LAT and LON fields in my table have VARCHAR type.
--MapsActivity.java
private GoogleMap mMap;
private Double Latitude = 0.00;
private Double Longitude = 0.00;
#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);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
ArrayList<HashMap<String, String>> location = new ArrayList<HashMap<String, String>>();
String url = "http://192.168.1.101/crud/markers_android.php";
try {
JSONArray data = new JSONArray(url);
location = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("LAT", c.getString("LAT"));
map.put("LON", c.getString("LON"));
location.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < location.size(); i++) {
Latitude = Double.parseDouble(location.get(i).get("LAT").toString());
Longitude = Double.parseDouble(location.get(i).get("LON").toString());
MarkerOptions marker = new MarkerOptions().position(new LatLng(Latitude, Longitude));
mMap.addMarker(marker);
}
}
}
file php markers_android.php is here
Use a log to see what response you get from json
for (int i = 0; i < data.length(); i++)
{
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("LAT", c.getString("LAT"));
map.put("LON", c.getString("LON"));
Log.w("eeee", "Lat : " + c.getString("LAT") + " Lon : " + c.getString("LON")); // add this line
location.add(map);
}
And give us the answer back if you can!

Categories

Resources