Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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;

double radians=getAtan2((frnd_long-my_long),(frnd_lat-my_lat));
double compassReading = radians * (180 / Math.PI);

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

String url = "http://maps.googleapis.com/maps/api/directions/xml?"
+ "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);
rectLine.add(my_latlong,directionPoint.get(ii));
Polyline polyline=map.addPolyline(rectLine);
polylines.add(polyline);
}
else
{
PolylineOptions rectLine = new PolylineOptions().width(8).color(Color.RED);
rectLine.add(directionPoint.get(ii-1),directionPoint.get(ii));
Polyline polyline=map.addPolyline(rectLine);
polylines.add(polyline);
}
}
PolylineOptions rectLine = new PolylineOptions().width(8).color(Color.RED);
rectLine.add(frnd_latlong,directionPoint.get(ii-1));
Polyline polyline=map.addPolyline(rectLine);
polylines.add(polyline);
//map.addPolyline(rectLine);
}
}
}

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());
listGeopoints.add(new LatLng(lat, lng));

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++) {
listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude));
}

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());
listGeopoints.add(new LatLng(lat, lng));
}
}
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);
poly.add(position);
}
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:-

★ Advance Android Google Map 2 Tutorial with Examples - Part 1

★ 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


This post first appeared on Coders Hub: Android Code Examples And Programming Tutorials, please read the originial post: here

Share the post

Advance Android Google Map 2 Tutorial with Example - Part 2

×

Subscribe to Coders Hub: Android Code Examples And Programming Tutorials

Get updates delivered right to your inbox!

Thank you for your subscription

×