Android google map Find distance between - android

i successfully created google map .i can check mylocation and i wrote code witch can add point in google map (touch listener) and draw line between start location and point . and now i want to check distance . i do not know how i can this
i googled one example but this code does not working right?i always has one distance
this is a my code if anyone knows solution please help me
thanks
public class GPS extends Activity implements
OnMyLocationChangeListener, OnMapClickListener {
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
Circle myCircle;
TextView tvLocInfo, GPSLocation;
LatLng latLng;
boolean markerClicked;
ArrayList<LatLng> markerPoints;
double Startlatitude, Startlongitude, Endlatitude, Endlongitude;
public Button gpssize;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gps);
markerPoints = new ArrayList<LatLng>();
gpssize = (Button) findViewById(R.id.gpssize);
tvLocInfo = (TextView) findViewById(R.id.GpsTxt);
GPSLocation = (TextView) findViewById(R.id.GPSLocation);
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment = (MapFragment) myFragmentManager
.findFragmentById(R.id.GpsMap);
myMap = myMapFragment.getMap();
myMap.getUiSettings().setZoomControlsEnabled(true);
myMap.getUiSettings().setCompassEnabled(true);
myMap.getUiSettings().setMyLocationButtonEnabled(true);
myMap.setMyLocationEnabled(true);
myMap.setOnMyLocationChangeListener(this);
gpssize.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
double distance;
Location locationA = new Location("");
locationA.setLatitude(Startlatitude);
locationA.setLongitude(Startlongitude);
Location locationB = new Location("");
locationB.setLatitude(Endlatitude);
locationB.setLongitude(Endlongitude);
distance = locationA.distanceTo(locationB) / 1000;
Toast.makeText(getApplicationContext(), "" + distance,
Toast.LENGTH_LONG).show();
}
});
myMap.setOnMapClickListener(this);
myMap.setTrafficEnabled(true);
markerClicked = false;
}
#Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS) {
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS", Toast.LENGTH_LONG)
.show();
} else {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
RQS_GooglePlayServices);
}
}
#Override
public void onMyLocationChange(Location location) {
Startlatitude = location.getLatitude();
Startlongitude = location.getLongitude();
latLng = new LatLng(Startlatitude, Startlongitude);
myMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
GPSLocation.setText(Startlatitude + " " + Startlongitude);
// myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng locLatLng = new LatLng(location.getLatitude(),
location.getLongitude());
double accuracy = location.getAccuracy();
if (myCircle == null) {
CircleOptions circleOptions = new CircleOptions().center(locLatLng)
.radius(accuracy)
.fillColor(Color.RED).strokeColor(Color.BLACK).strokeWidth(5);
myCircle = myMap.addCircle(circleOptions);
} else {
myCircle.setCenter(locLatLng);
myCircle.setRadius(accuracy);
}
myMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
private String getDirectionsUrl(LatLng origin, LatLng dest) {
String str_origin = "origin=" + Startlatitude + "," + Startlongitude;
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
String sensor = "sensor=false";
String parameters = str_origin + "&" + str_dest + "&" + sensor;
String output = "json";
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);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
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 DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
String data = "";
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
private class ParserTask extends
AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
#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();
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();
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
List<HashMap<String, String>> path = result.get(i);
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"));
tvLocInfo.setText(lat + " " + lng);
LatLng position = new LatLng(lat, lng);
points.add(position);
}
lineOptions.addAll(points);
lineOptions.width(7);
lineOptions.geodesic(true);
lineOptions.color(getResources().getColor(R.color.mapColor));
}
myMap.addPolyline(lineOptions);
}
}
#Override
public void onMapClick(LatLng point) {
if (markerPoints.size() > 0) {
markerPoints.clear();
myMap.clear();
}
markerPoints.add(point);
MarkerOptions options = new MarkerOptions();
options.position(point);
if (markerPoints.size() == 1) {
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}
myMap.addMarker(options);
if (markerPoints.size() >= 1) {
LatLng dest = markerPoints.get(0);
LatLng origin = new LatLng(Endlatitude, Endlongitude);
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}
}
}

Try on this way to get Distance between to LatLng Points:
float[] distances = new float[1];
Location.distanceBetween(locationA.latitude, locationA.longitude,
locationB.latitude, locationB.longitude,
distances);
System.out.println("Distance: " + distances[0]);

Related

how to add turn to turn navigation on map activity for multiple points

i have android map with multiple points plotted from mysql data..i have added basic features of map like mylocation,zoom etc...Also added direction between multiple points from mylocation.
Now I need to add step by step direction route or navigate between points.
Most importantly i dont want to redirect to google maps and naviagate..
all actions should happen withen my google map api.
here is my Mapactivity code onMapReady
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Toast.makeText(getActivity(), Util.reslatitude + " " + Util.reslogitide+" "+Util.resname, Toast.LENGTH_LONG).show();
LatLng locations = new LatLng(Util.latitude,Util.longitude);
/* Location startPoint=new Location("locationA");
startPoint.setLatitude(Util.latitude);
startPoint.setLongitude(Util.longitude);
Location endPoint=new Location("locationA");
endPoint.setLatitude(13.073226);
endPoint.setLongitude(80.260921);
double distance=startPoint.distanceTo(endPoint);
Toast.makeText(this,String.valueOf(distance+" Meters"),Toast.LENGTH_SHORT).show();*/
/* LatLng loc = new LatLng(13.073226, 80.260921);*/
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);
//mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
mMap.getUiSettings().setMapToolbarEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.setTrafficEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(locations, 4.2f));
mMap.addMarker(new MarkerOptions()
.title("User")
.position(locations)
);
/* // Getting URL to the Google Directions API
String url = getDirectionsUrl(locations, loc);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);*/
/*LatLng dest = new LatLng(13.036791,80.26763);
mMap.addPolyline(new PolylineOptions().add(locations,dest).color(Color.RED) //draws straight line between points
);*/
}
private class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
String data = "";
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
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();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
for (int i = 0; i < result.size(); i++) {
points = new ArrayList();
lineOptions = new PolylineOptions();
List<HashMap<String, String>> path = result.get(i);
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);
}
lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.BLUE);
lineOptions.geodesic(true);
}
// Drawing polyline in the Google Map for the i-th route
mMap.addPolyline(lineOptions);
}
}
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";
String mode = "mode=driving";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;
// 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);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
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", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
help me to rectify the problem

Find distance between current location and user input field using button in Google Map

I am working with a project to find the distance between two places, one is current location and other is user input value using auto-complete text view.
How can I get the correct distance using button click. I got the values without a button click. How can I implement button click?
.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
MarkerPoints = new ArrayList<>();
final AutoCompleteTextView autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.list_item));
autoCompView.setOnItemClickListener(this);
b1=(Button)findViewById(R.id.search_button);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String location = autoCompView.getText().toString();
List<Address>addressList = null;
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(MapsActivity.this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng dest = new LatLng(address.getLatitude(), address.getLongitude());
lat1=String.valueOf(address.getLatitude());
lon1 = String.valueOf(address.getLongitude());
Toast.makeText(MapsActivity.this, "new Lati and new longi1 "+dest, Toast.LENGTH_LONG).show();
mMap.addMarker(new MarkerOptions().position(dest).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLng(dest));
// SendDataToServer(unique_id,lat1,lon1);
// mMap.clear();
findPath(point);
}
}
});
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// 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);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
}
private void findPath(LatLng point) {
if (MarkerPoints.size() >= 2) {
LatLng origin = MarkerPoints.get(0);
LatLng dest = MarkerPoints.get(1);
// Getting URL to the Google Directions API
String url = getUrl(origin, dest);
// Log.d("onMapClick", url.toString());
FetchUrl FetchUrl = new FetchUrl();
// Start downloading json data from Google Directions API
FetchUrl.execute(url);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(origin));
mMap.animateCamera(CameraUpdateFactory.zoomTo(16));
}
}
private void drawMarker(LatLng point) {
MarkerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
private String getUrl(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();
Log.d("downloadUrl", data.toString());
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class FetchUrl extends AsyncTask<String, Void, String> {
#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]);
Log.d("Background Task data", data.toString());
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#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]);
Log.d("ParserTask",jsonData[0].toString());
DataParser parser = new DataParser();
Log.d("ParserTask", parser.toString());
// Starts parsing data
routes = parser.parse(jObject);
Log.d("ParserTask","Executing routes");
Log.d("ParserTask",routes.toString());
} catch (Exception e) {
Log.d("ParserTask",e.toString());
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;
PolylineOptions lineOptions = null;
String distance = "";
String duration = "";
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<>();
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(10);
lineOptions.color(Color.RED);
Log.d("onPostExecute","onPostExecute lineoptions decoded");
tvDistanceDuration.setText("Distance:"+distance + ", Duration:"+duration);
}
// Drawing polyline in the Google Map for the i-th route
if(lineOptions != null) {
mMap.addPolyline(lineOptions);
}
else {
Log.d("onPostExecute","without Polylines drawn");
}
}
If you know the latitude and longitude of both locations then you can easily calculate the distance between both position. Visit http://www.geodatasource.com/developers/java for more information.
Here is how you can do it in android.
Create a method as following in some class
private static double distance(double lat1, double lon1, double lat2, double lon2, String unit) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit == "K") {
dist = dist * 1.609344;
} else if (unit == "N") {
dist = dist * 0.8684;
}
return (dist);
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*:: This function converts decimal degrees to radians :*/
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
private static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*:: This function converts radians to decimal degrees :*/
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
private static double rad2deg(double rad) {
return (rad * 180 / Math.PI);
}
Then you can use distance method
For example distance is static method of Helper Class then
int distance = Helper.distance(lat1,lon1,lat2,lon2,"K") use "K" for kilometer "N" for
I hope this will help you somehow.
This is the method I use to get the distance and time travel from user location to selected location. Add it below your AsyncTask:
public void getDistAndDuration(JSONObject jObj){
try{
JSONArray array = jObj.getJSONArray("routes");
JSONObject rou = array.getJSONObject(0);
JSONArray legs = rou.getJSONArray("legs");
JSONObject steps = legs.getJSONObject(0);
JSONObject distance = steps.getJSONObject("distance");
JSONObject duration = steps.getJSONObject("duration");
final String textDist = distance.getString("text");
final String textDur = duration.getString("text");
Log.i("DISTANCE", ""+textDist);
Log.i("TIME", ""+textDur);
}catch(Exception e){
e.printStackTrace();
}
}
Call this method in your ParserTask in the doInBackground method like this:
#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]);
////////// HERE //////////////
getDistAndDuration(jObject);
//////////////////////////////
Log.d("ParserTask",jsonData[0].toString());
DataParser parser = new DataParser();
Log.d("ParserTask", parser.toString());
// Starts parsing data
routes = parser.parse(jObject);
Log.d("ParserTask","Executing routes");
Log.d("ParserTask",routes.toString());
} catch (Exception e) {
Log.d("ParserTask",e.toString());
e.printStackTrace();
}
return routes;
}
If you only want to get the distance on button click, declare your jObject globally, and call the getDistAndDuration(JSONObject jObj) in the click listener of your button. Be sure to call it after you called the AsyncTask first.
Hope it helps :)

Android Google map get shortest path between mutilple location

I want to find the shortest location to the current location of the user.
i use distanceTo() and distanceBetween() but it's not working
The process of my android app is the location of the places is automatically initialized in the variable and i want to compare it to the multiple location and find the shortest location and print the location .
can anyone help me about my problem ? thanks in advance
Try this,
public class Nav extends Fragment {
GoogleMap map;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Commons.applyFont(getActivity(), getView().findViewById(R.id.frame),
"RobotoSlab-Light");
map = ((SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
LatLng latLng = new LatLng(nav.sAddLat, nav.sAddLong);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15.0f));
map.addMarker(new MarkerOptions().position(new LatLng(nav.sAddLat,
nav.sAddLong)));
map.getUiSettings().setCompassEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).tilt(60).zoom(15.0f).bearing(300).build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
LatLng origin = new LatLng(nav.sAddLat, nav.sAddLong);
LatLng dest = new LatLng(nav.dAddLat, nav.dAddLong);
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}
private String getDirectionsUrl(LatLng origin, LatLng dest) {
String str_origin = "origin=" + origin.latitude + ","
+ origin.longitude;
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
String sensor = "sensor=false";
String parameters = str_origin + "&" + str_dest + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + parameters;
return url;
}
#SuppressLint("LongLogTag")
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();
urlConnection.connect();
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 DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
String data = "";
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
private class ParserTask extends
AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
#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();
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;
Log.e("results", result + "");
if (result.size() < 1) {
Toast.makeText(getActivity(), "No Points", Toast.LENGTH_SHORT)
.show();
return;
}
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
List<HashMap<String, String>> path = result.get(i);
Log.e("points", path + "");
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
if (j == 0) {
tvDistance.setText("Distance : "
+ point.get("distance"));
} else if (j == 1) {
tvTime.setText("Duration : " + point.get("duration"));
} else if (j > 1) {
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
}
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
map.addPolyline(lineOptions);
}
}
}

Google Map crash on Android app

Someday the code crash...
My AndroidManifiest is correct even mi API credentials, my internet conecction works fine.
I am using Android Studio , the SDK are installed too.
Here is the Logcat
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at info.androidhive.slidingmenu.VanWhi$ParserTask.onPostExecute(VanWhi.java:139)
at info.androidhive.slidingmenu.VanWhi$ParserTask.onPostExecute(VanWhi.java:113)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
And this is the Fragment
public class VanWhi extends FragmentActivity {
private static final LatLng VANCOUVER = new LatLng( 49.281612, -123.115464);
private static final LatLng WHISLER = new LatLng( 50.116966, -122.956546);
GoogleMap googleMap;
final String TAG = "PathGoogleMapActivity";
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vanwhi);
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
googleMap = fm.getMap();
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.setMyLocationEnabled(true);
MarkerOptions options = new MarkerOptions();
options.position(VANCOUVER);
options.position(WHISLER);
googleMap.addMarker(options);
String url = getMapsApiDirectionsUrl();
ReadTask downloadTask = new ReadTask();
downloadTask.execute(url);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(VANCOUVER,
6));
addMarkers();
}
private String getMapsApiDirectionsUrl() {
String waypoints = "waypoints=optimize:true|"
+ "|" + "|" + VANCOUVER.latitude + ","
+ VANCOUVER.longitude + "|" + WHISLER.latitude + ","
+ WHISLER.longitude;
String sensor = "sensor=false";
String params = waypoints + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + params;
return url;
}
private void addMarkers() {
if (googleMap != null) {
googleMap.addMarker(new MarkerOptions().position(VANCOUVER)
.title("VANCOUVER"));
googleMap.addMarker(new MarkerOptions().position(WHISLER)
.title("WHISTLER"));
}
}
private class ReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
String data = "";
try {
HttpConnection http = new HttpConnection();
data = http.readUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(result);
}
}
private class ParserTask extends
AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
#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]);
PathJSONParser parser = new PathJSONParser();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> routes) {
ArrayList<LatLng> points = null;
PolylineOptions polyLineOptions = null;
// traversing through routes
for (int i = 0; i < routes.size(); i++) {
points = new ArrayList<LatLng>();
polyLineOptions = new PolylineOptions();
List<HashMap<String, String>> path = routes.get(i);
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);
}
polyLineOptions.addAll(points);
polyLineOptions.width(8);
polyLineOptions.color(Color.BLUE);
}
googleMap.addPolyline(polyLineOptions);
}
}
}
It is from info.androidhive.slidingmenu and not from the Fragment you sent.
It's a nullpointer exception from a null List<>
you don't check if routes != null and path != null before your loops, maybe the json deserialisation failed, so those lists are nul

Google map drow route between current location and point

I'm trying to draw a route between the current location and another point. I wrote code which can check the current location and also put the point on the map on a map click. At the moment, the program is working perfectly,
but I want to draw another route between the current location and a new point( point witch I added map on Map click listener).
My code is below, does anyone know how I can to add this logic on my code?
public class GPS extends Activity implements
OnMyLocationChangeListener,OnMapClickListener,
OnMapLongClickListener, OnMarkerDragListener {
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
Circle myCircle;
Location myLocation;
TextView tvLocInfo, GPSLocation;
LatLng latLng;
boolean markerClicked;
ArrayList<LatLng> markerPoints;
Polygon polygon;
public Button btnline;
double Clicklatitude, Clicklongitude, latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gps);
markerPoints=new ArrayList<LatLng>();
btnline = (Button) findViewById(R.id.button1);
tvLocInfo = (TextView) findViewById(R.id.GpsTxt);
GPSLocation = (TextView) findViewById(R.id.GPSLocation);
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment = (MapFragment) myFragmentManager
.findFragmentById(R.id.GpsMap);
myMap = myMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setOnMyLocationChangeListener(this);
myMap.setOnMapClickListener(this);
myMap.setOnMapLongClickListener(this);
myMap.setOnMarkerDragListener(this);
myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
myMap.setMyLocationEnabled(true);
myMap.setOnMyLocationChangeListener(this);
markerClicked = false;
btnline.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS) {
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS", Toast.LENGTH_LONG)
.show();
} else {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
RQS_GooglePlayServices);
}
}
#Override
public void onMyLocationChange(Location location) {
latitude = location.getLatitude();
// Getting longitude of the current location
longitude = location.getLongitude();
// Creating a LatLng object for the current location
latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
myMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
GPSLocation.setText(latitude + " " + longitude);
myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng locLatLng = new LatLng(location.getLatitude(),
location.getLongitude());
double accuracy = location.getAccuracy();
if (myCircle == null) {
CircleOptions circleOptions = new CircleOptions().center(locLatLng)
// set center
.radius(accuracy)
// set radius in meters
.fillColor(Color.RED).strokeColor(Color.BLACK)
.strokeWidth(5);
myCircle = myMap.addCircle(circleOptions);
} else {
myCircle.setCenter(locLatLng);
myCircle.setRadius(accuracy);
}
myMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// myMap.animateCamera(CameraUpdateFactory.newLatLng(locLatLng));
}
#Override
public void onMarkerDrag(Marker arg0) {
// TODO Auto-generated method stub
}
#Override
public void onMarkerDragEnd(Marker arg0) {
// TODO Auto-generated method stub
}
#Override
public void onMarkerDragStart(Marker arg0) {
// TODO Auto-generated method stub
}
#Override
public void onMapLongClick(LatLng point) {
}
#Override
public void onMapClick(LatLng point) {
Clicklatitude = point.latitude;
Clicklongitude = point.longitude;
tvLocInfo.setText(Clicklatitude + " " + Clicklongitude);
if (point != null)
myMap.clear();
myMap.addMarker(new MarkerOptions().position(point).draggable(true));
markerClicked = false;
}
}
I want to get a like this result enter link description here
I achieved same thing via this code. This will be some different Code from what you have tried.
First of all Implement your class with this two things
implements OnMapReadyCallback,LocationListener
When you implement OnMapReadyCallback you will get pre-define method called
"OnMapReady"
#Override
public void onMapReady(GoogleMap googleMap) {
destiLati = 40.728634;
destiLong = -73.974956;
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
// Add a marker in Destination/Desire point and move the camera
DestinationPoint = new LatLng(destiLati, destiLong);
mMap.addMarker(new MarkerOptions().position(DestinationPoint).title("Destination
Point")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
//To move camera to Desination Location.
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(DestinationPoint, 10));
//Permission To get Current Location
if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
To get current location I have made one method and when you implement LocationListener
it will give you pre-define method called "onLocationChanged"
private void getLocation() {
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 5, this);
}
catch(SecurityException e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
//This thing will get User's current location
originLati = location.getLatitude();
originLong = location.getLongitude();
exeTask();
//Log.d(originLati.toString(),"This is the value of orginalati" + originLati.toString() + " " + originLong.toString());
}
To get path between Your current location and destination..
you need to pass data to google API it will write one JSON result
you have to get this result and show it into Polyline(to display path)
private void exeTask(){
String originPl = "origin=" + originLati.toString() + "," + originLong.toString();
String destipl = "destination=" + destiLati.toString() + "," + destiLong.toString();
String sensor = "sensor-false";
String mode = "mode-driving";
String param = originPl + "&" + destipl + "&" + sensor + "&" + mode + "&key='Your_API_KEY'";
final_url = "https://maps.googleapis.com/maps/api/directions/json?" + param;
//Log.d(final_url,"This is the URL which was created");
TaskRequestDirections taskRequestDirections = new TaskRequestDirections();
taskRequestDirections.execute(final_url);
}
private String requestDirection(String reqUrl) throws IOException {
String responseString = "";
InputStream inputStream = null;
HttpURLConnection httpURLConnection = null;
try{
URL url = new URL(reqUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
//TO get the in String format response result
inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
responseString = stringBuffer.toString();
bufferedReader.close();
inputStreamReader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream.close();
}
httpURLConnection.disconnect();
}
return responseString;
}
public class TaskRequestDirections extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
String responseString = "";
try {
responseString = requestDirection(strings[0]);
} catch (IOException e) {
e.printStackTrace();
}
return responseString;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//Parse json/ Data will come from here..
TaskParser taskParser = new TaskParser();
taskParser.execute(s);
}
}
public class TaskParser extends AsyncTask<String, Void, List<List<HashMap<String, String>>> > {
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... strings) {
JSONObject jsonObject = null;
List<List<HashMap<String, String>>> routes = null;
try {
jsonObject = new JSONObject(strings[0]);
DirectionsParser directionsParser = new DirectionsParser();
routes = directionsParser.parse(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> lists) {
//To get list route and display it into the map
ArrayList points = null;
PolylineOptions polylineOptions = null;
for (List<HashMap<String, String>> path : lists) {
points = new ArrayList();
polylineOptions = new PolylineOptions();
for (HashMap<String, String> point : path) {
double lat = Double.parseDouble(point.get("lat"));
double lon = Double.parseDouble(point.get("lon"));
points.add(new LatLng(lat,lon));
}
polylineOptions.addAll(points);
polylineOptions.width(10);
polylineOptions.color(Color.BLUE);
polylineOptions.geodesic(true);
}
if (polylineOptions!=null) {
mMap.addPolyline(polylineOptions);
} else {
//Toast.makeText(getApplicationContext(), "Direction not found!", Toast.LENGTH_SHORT).show();
}
}
}
And finally call this pre-define Class as it show here to decode polylines and get json array result
public class DirectionsParser {
/**
* Returns a list of lists containing latitude and longitude from a JSONObject
*/
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");
// Loop for all routes
for (int i = 0; i < jRoutes.length(); i++) {
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
//Loop for all legs
for (int j = 0; j < jLegs.length(); j++) {
jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
//Loop for all steps
for (int k = 0; k < jSteps.length(); k++) {
String polyline = "";
polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
List list = decodePolyline(polyline);
//Loop for 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("lon", 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
* Source : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
*/
private List decodePolyline(String encoded) {
List poly = new ArrayList();
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;
}
}
Hope This help :)

Categories

Resources