# Advance Android Google Map 2 Tutorial with Example - Part 2

If you are new to Android Google Map 2 than must read first part of android Google map 2 tutorial. In previous post, I covered all basic things related to Google map object, marker, shapes, my location, camera movement, map types, etc.

In this post, we will learn:-

1. How to find bearing between two latitude and longitude?
2. How to find direction between two latitude and longitude?
3. How to find distance between two latitude and longitude?
4. How to draw line between two latitude and longitude according to walking & driving direction?

At the end of post, I will share my project which will have more functionality than this post.

Calculate bearing between two locations:-

private float getBearing(LatLng begin, LatLng end) {
double lat = Math.abs(begin.latitude - end.latitude);
double lng = Math.abs(begin.longitude - end.longitude);

if(begin.latitude < end.latitude && begin.longitude < end.longitude)
return (float)(Math.toDegrees(Math.atan(lng / lat)));
else if(begin.latitude >= end.latitude && begin.longitude < end.longitude)
return (float)((90 - Math.toDegrees(Math.atan(lng / lat))) + 90);
else if(begin.latitude >= end.latitude && begin.longitude >= end.longitude)
return  (float)(Math.toDegrees(Math.atan(lng / lat)) + 180);
else if(begin.latitude < end.latitude && begin.longitude >= end.longitude)
return (float)((90 - Math.toDegrees(Math.atan(lng / lat))) + 270);

return -1;
}

Calculate distance between two locations:-

private String getDistance(LatLng my_latlong,LatLng frnd_latlong){
Location l1=new Location("One");
l1.setLatitude(my_latlong.latitude);
l1.setLongitude(my_latlong.longitude);

Location l2=new Location("Two");
l2.setLatitude(frnd_latlong.latitude);
l2.setLongitude(frnd_latlong.longitude);

float distance=l1.distanceTo(l2);
String dist=distance+" M";

if(distance>1000.0f)
{
distance=distance/1000.0f;
dist=distance+" KM";
}
return dist;
}

Get direction between two locations:-

private String getDirection(LatLng my_latlong,LatLng frnd_latlong) {
// TODO Auto-generated method stub
double my_lat=my_latlong.latitude;
double my_long=my_latlong.longitude;

double frnd_lat=frnd_latlong.latitude;
double frnd_long=frnd_latlong.longitude;

String[] coordNames = {"North", "North-East", "East", "South-East", "South", "South-West", "West", "North-West", "North"};
int coordIndex = (int) Math.round(compassReading / 45);

if (coordIndex < 0) {
coordIndex = coordIndex + 8;
};

return coordNames[coordIndex]; // returns the coordinate value
}

private double getAtan2(double longi,double lat) {
return Math.atan2(longi, lat);
}

I used  AsyncTask to Draw line between two locations after getting latitude and longitude of my location and friend location:-

public class Request_Update extends AsyncTask<Location, Void, Location>{
@Override
protected void onPreExecute()
{
//Toast.makeText(getApplicationContext(), "onPreExecute()!", Toast.LENGTH_SHORT).show();
}
@Override
protected Location doInBackground(Location... location) {
// TODO Auto-generated method stub

+ "origin=" + location[0].getLatitude() + "," + location[0].getLongitude()
+ "&destination=" + frnd_lat + "," + frnd_longi
+ "&sensor=false&units=metric&mode="+direction; //direction="walking" or "driving"

try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost, localContext);
InputStream in = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
doc = builder.parse(in);
} catch (Exception e) {
}

return location[0];
}

@Override
protected void onPostExecute(Location location)
{
if(doc!=null)
{
directionPoint=getDirection(doc);
int ii = 0;
size_of_latlong=directionPoint.size();
for( ; ii <size_of_latlong ; ii++) {
if(ii==0)
{
PolylineOptions rectLine = new PolylineOptions().width(8).color(Color.RED);
}
else
{
PolylineOptions rectLine = new PolylineOptions().width(8).color(Color.RED);
}
}
PolylineOptions rectLine = new PolylineOptions().width(8).color(Color.RED);
}
}
}

public ArrayList<LatLng> getDirection(Document doc) {
NodeList nl1, nl2, nl3;
ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
nl1 = doc.getElementsByTagName("step");
if (nl1.getLength() > 0) {
for (int i = 0; i < nl1.getLength(); i++) {
Node node1 = nl1.item(i);
nl2 = node1.getChildNodes();

Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
nl3 = locationNode.getChildNodes();
Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
double lat = Double.parseDouble(latNode.getTextContent());
Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
double lng = Double.parseDouble(lngNode.getTextContent());

locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
nl3 = locationNode.getChildNodes();
latNode = nl3.item(getNodeIndex(nl3, "points"));
ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
for(int j = 0 ; j < arr.size() ; j++) {
}

locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
nl3 = locationNode.getChildNodes();
latNode = nl3.item(getNodeIndex(nl3, "lat"));
lat = Double.parseDouble(latNode.getTextContent());
lngNode = nl3.item(getNodeIndex(nl3, "lng"));
lng = Double.parseDouble(lngNode.getTextContent());
}
}
return listGeopoints;
}

private int getNodeIndex(NodeList nl, String nodename) {
for(int i = 0 ; i < nl.getLength() ; i++) {
if(nl.item(i).getNodeName().equals(nodename))
return i;
}
return -1;
}

private ArrayList<LatLng> decodePoly(String encoded) {
ArrayList<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 position = new LatLng((double)lat / 1E5, (double)lng / 1E5);
}
return poly;
}

I have given some code examples in previous and this post to understand Google map 2 deeply and working on it easily. Some user wants voice as well in android map, so I added voice code in comment to help all developers. Project contains Login, Registration and searching Friends functionality as well. Download complete project from Github: Android Google Map 2 or download and check APK file in your android device.

Related Tutorials:-

Get Latitude, Longitude and Address of current Location

Android Login,Register page with MySQL and PHP Project

Create List and perform Actions on it

Convert Text to Speech

1. May i know how to add a search bar to search the location 2, then calculate the distance between the current location and the location 2?

1. check official site and get lat and long of other place and calculate distance easily.

2. do you mean the google developer page?

3. how can we share current location (similar to whatsapp) to selected people?

4. i got an error in signin.java.when i click on button continue "Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject"

5. thank you for tutorial. may i know finally code for direction from current location to other location. not in your source code Friend Location. because in source code Friend Location is difficult for me.
thank you

6. I want to open this project in android studio .Please anyone tell me the process.

7. sir please send this project source code on my gmail id
shivani335@gmail.com

8. This comment has been removed by the author.

9. This comment has been removed by the author.

10. i find a lot of errors when i try to copy it in android studio
any help plz

1. Sir please update this exmaple for latest android.

11. Dear Sir this example is very useful so please update it with latest android version for us. please sir,thanks in advance.

12. This comment has been removed by the author.

13. Hello sir,
How can I get location as input from gmap and store and retrieve it in PHP MYSQL database..