Fetching Location Distance issue sending 0.0 - android

I am using the following code the fetching the distance between difference latitude and longitude.Some time it works fine but some time it return the 0.0. I can't understand the reason why it happen. I have enable both GPS and Network
My code is..
public static String getDistanceOnRoad(String latitude, String longitude,
String prelatitute, String prelongitude) {
String result_in_kms = "";
float num_in_Km=0;
String url = "http://maps.google.com/maps/api/directions/xml?origin="
+ latitude + "," + longitude + "&destination=" + prelatitute
+ "," + prelongitude + "&sensor=false&units=metric";
String tag[] = { "text" };
HttpResponse response = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
response = httpClient.execute(httpPost, localContext);
InputStream is = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(is);
if (doc != null) {
NodeList nl;
ArrayList args = new ArrayList();
for (String s : tag) {
nl = doc.getElementsByTagName(s);
if (nl.getLength() > 0) {
Node node = nl.item(nl.getLength() - 1);
args.add(node.getTextContent());
} else {
args.add(" - ");
}
}
result_in_kms = String.format("%s", args.get(0));
//result come with 'm' and 'km' tag so remove this tag
String num=stripNonDigits(result_in_kms);
//if result in KM then does not devide by 1000
if(!isdisIn_M_or_KM(result_in_kms)){
num_in_Km=Float.valueOf(num)/1000;
}
else num_in_Km=Float.valueOf(num);
Log.i("", "");
}
} catch (Exception e) {
e.printStackTrace();
}
return String.valueOf(num_in_Km);
}

For Finding the distance using GPS, There is no Need of Network Connection. GPS will provide the Latitude and Longitude based on the the time interval you apply.
kindly refer the below link
Calculate distance between two latitude-longitude points? (Haversine formula)

Related

"How to get the actual road distance between two places both the points are fixed"

We are creating an Android application and we need to calculate exact road distance between two fixed points. We require road distance not the Arial distance(Bird flying distance). We need to calculate the estimate trip cost before the trip starts.
Thanks in Advance.
All the answers and helps will be appreciated.
use goolge api
public float getDistance(double lat1, double lon1, double lat2, double lon2) {
String result_in_kms = "";
String url = "http://maps.google.com/maps/api/directions/xml?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric";
String tag[] = {"text"};
HttpResponse response = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
response = httpClient.execute(httpPost, localContext);
InputStream is = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(is);
if (doc != null) {
NodeList nl;
ArrayList args = new ArrayList();
for (String s : tag) {
nl = doc.getElementsByTagName(s);
if (nl.getLength() > 0) {
Node node = nl.item(nl.getLength() - 1);
args.add(node.getTextContent());
} else {
args.add(" - ");
}
}
result_in_kms =String.valueOf( args.get(0));
}
} catch (Exception e) {
e.printStackTrace();
}
Float f=Float.valueOf(result_in_kms);
return f*1000;
}
Here is a variation of the first answer. First call getDocument with start and end location, mode (driving, transit, cycling, walking), language. Then pass that document to getTurnByTurn(). This will return an array of 'steps' or legs of a trip, with a distance between the previous step's end point and the new step's end point. Might be in kilometers, need to convert to miles if necessary.
public Document getDocument(String start, String dest, String mode, String language) {
try {
start = URLEncoder.encode(start, "utf-8");
dest = URLEncoder.encode(dest, "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
long milliseconds = System.currentTimeMillis();
long seconds = milliseconds/1000;
String url = "https://maps.googleapis.com/maps/api/directions/xml?departure_time="
+ seconds
+ "&origin=" + start
+ "&destination=" + dest
+ "&language=" + language
+ "&sensor=false&mode=" + mode;
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();
Document doc = builder.parse(in);
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public ArrayList<SearchItem> getTurnByTurn (Document doc) {
NodeList nl1, nl2, nl3;
ArrayList<SearchItem> listDirections = new ArrayList<SearchItem>();
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 distanceNode = nl2.item(getNodeIndex(nl2, "distance"));
nl3 = distanceNode.getChildNodes();
Node textNode = nl3.item(getNodeIndex(nl3, "text"));
String distance = textNode.getTextContent();
Node durationNode = nl2.item(getNodeIndex(nl2, "duration"));
nl3 = durationNode.getChildNodes();
textNode = nl3.item(getNodeIndex(nl3, "text"));
String duration = textNode.getTextContent();
Node instructionsNode = nl2.item(getNodeIndex(nl2, "html_instructions"));
String instructions = instructionsNode.getTextContent();
String details = distance + " -- " + duration;
listDirections.add(new SearchItem(instructions, details, "", false));
}
}
return listDirections;
}

Distance between 2 places on Android Map

I need to calculate distance between current location and the destination. I have the latitude and longitude of current and destination locations. I found the below code from SO and internet while searching. But the calculation give 1366 km while the google maps gives 1675 km between 2 locations. Can someone help how can I calculate accurate distance. The destinations are world wide including my current city locations.
//Distance in Kilometers
fun distanceInKms ( lat1: Double, long1: Double, lat2: Double, long2: Double) : Double
{
val degToRad= Math.PI / 180.0;
val phi1 = lat1 * degToRad;
val phi2 = lat2 * degToRad;
val lam1 = long1 * degToRad;
val lam2 = long2 * degToRad;
return 6371.01 * Math.acos( Math.sin(phi1) * Math.sin(phi2) + Math.cos(phi1) * Math.cos(phi2) * Math.cos(lam2 - lam1) );
}
Can someone help me out with this please?
Use the android.location.Location class, available since API level 1 in Android. It has a static distanceBetween method doing it all for you.
See:
http://developer.android.com/reference/android/location/Location.html
float[] results = new float[1];
android.location.Location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude, results);
//distance in meters now in results[0]
Divide by 1000 to get it in kilometers (km).
you can use it , it get like google don't forgot to add internet permission
String getDistanceOnRoad(double latitude, double longitude,
double prelatitute, double prelongitude) {
String result_in_kms = "";
String url = "http://maps.google.com/maps/api/directions/xml? origin="
+ latitude + "," + longitude + "&destination=" + prelatitute
+ "," + prelongitude + "&mode=driving&sensor=false&units=metric";
String tag[] = { "text" };
HttpResponse response = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
response = httpClient.execute(httpPost, localContext);
InputStream is = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(is);
if (doc != null) {
NodeList nl;
ArrayList<String> args = new ArrayList<String>();
for (String s : tag) {
nl = doc.getElementsByTagName(s);
if (nl.getLength() > 0) {
Node node = nl.item(nl.getLength() - 1);
args.add(node.getTextContent());
} else {
args.add(" - ");
}
}
result_in_kms = String.format("%s", args.get(0));
}
} catch (Exception e) {
e.printStackTrace();
}
return result_in_kms;
}
this library have class to get time, distance and draw polyline between 2 places it work like google map
https://github.com/memo1231014/MUT-master
Example for the library
RouteInformations rInformation = new RouteInformations(new AsyncResponse() {
#Override
public void processFinish(RouteDetails arg0) {
// TODO Auto-generated method stub
try
{
map.addPolyline(arg0.getLineOptions()); //you can add the return line and add it to the map
//here you can get distance , duration it will return like you drive a car
MUT.fastDialog(Map.this,"Time and Distance","Distance : "+arg0.getDistance()+"\nDuration : "+arg0.getDuration());
}
catch(Exception e)
{
MUT.lToast(Map.this,"Can't draw line Try Again");
}
}
});
//you should pass the 2 lat and lang which you want to draw a aline or get distance or duration between them
RouteDetails routeDetails=new RouteDetails();
routeDetails.setLatLong1(from.getPosition());
routeDetails.setLatLong2(to.getPosition());
rInformation.execute(routeDetails);

google direction gives 0 values

hey I have used google direction to get duration it's working but sometime it return 0 value to json array routs. when I tested a day after return a value. is there any limitation for google direction request per day ?
and here is my function to get duration
public String getDistanceInfo(LatLng origin, LatLng dest) {
StringBuilder stringBuilder = new StringBuilder();
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
String dura = "";
try {
String sensor = "sensor=false";
String output = "json";
String mode = "mode=walking";
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;
// Output format
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
//String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + str_origin + "," + str_dest + "&destination=" + destinationAddress + "&mode=driving&sensor=false";
HttpPost httppost = new HttpPost(url);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
JSONArray array = jsonObject.getJSONArray("routes");
JSONObject routes = array.getJSONObject(0);
JSONArray legs = routes.getJSONArray("legs");
JSONObject steps = legs.getJSONObject(0);
JSONObject duration = steps.getJSONObject("duration");
dura = duration.getString("text");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dura;
}
org.json.JSONException: Index 0 out of range [0..0)
org.json.JSONArray.get(JSONArray.java:282)
org.json.JSONArray.getJSONObject(JSONArray.java:510)
Check to see if you are also getting something like this too in your JSON response apart from 0 for the duration.
{"status":"OVER_QUERY_LIMIT","routes":[]}.
This means that you are exceeding the limits of the Direction API usage. Please note that for standard version there are only 2,500 free directions requests per day available. If you need to request more, their are additional charges associated.
Check the official documentation on Google Maps Directions API Usage Limits more details.

Require altitude from latitude and longitude [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Android - Get Altitude By Longitude and Latitude?
I require altitude for particular location from latitude and longitude.Any help would be highly appreciated.
I have tried the Below Way in my application for getting Altitude from Lat/Long. you can try it out if it helps you.
private double getAltitudeFromLatLong(Double lat, Double long) {
double result = 0.0;
HttpClient httpClient = new DefaultHttpClient();
HttpContext Context = new BasicHttpContext();
String URL = "http://gisdata.usgs.gov/"
+ "xmlwebservices2/elevation_service.asmx/"
+ "getElevation?X_Value=" + String.valueOf(long)
+ "&Y_Value=" + String.valueOf(lat)
+ "&Elevation_Units=METERS&Source_Layer=-1&Elevation_Only=true";
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet, Context);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
int r = -1;
StringBuffer respStr = new StringBuffer();
while ((r = instream.read()) != -1)
respStr.append((char) r);
String tag1 = "<double>";
String tag2 = "</double>";
if (respStr.indexOf(tag1) != -1) {
int start = respStr.indexOf(tag1) + tag1.length();
int end = respStr.indexOf(tag2);
String value = respStr.substring(start, end);
result = Double.parseDouble(value);
}
instream.close();
}
}
catch (Exception e) {}
return result;
}
If u are using android device which has GPS Recever then there is a method getAltitude() by using that u can get the altitude by elevation.you can see this answer
Thanks

High Building using android

I need to develop app to calculate elevation building ,,, i use this code but it calculate elevation ground from sea floor
private double getElevationFromGoogleMaps(double longitude, double latitude) {
double result = Double.NaN;
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
String url = "http://maps.googleapis.com/maps/api/elevation/"
+ "xml?locations=" + String.valueOf(latitude)
+ "," + String.valueOf(longitude)
+ "&sensor=true";
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
int r = -1;
StringBuffer respStr = new StringBuffer();
while ((r = instream.read()) != -1)
respStr.append((char) r);
String tagOpen = "<elevation>";
String tagClose = "</elevation>";
if (respStr.indexOf(tagOpen) != -1) {
int start = respStr.indexOf(tagOpen) + tagOpen.length();
int end = respStr.indexOf(tagClose);
String value = respStr.substring(start, end);
result = (double)(Double.parseDouble(value)*3.2808399); // convert from meters to feet
// result = (double)(Double.parseDouble(value));
}
instream.close();
}
} catch (ClientProtocolException e) {}
catch (IOException e) {}
return result;
}
Can any one help me how to calculate elevation building from ground ... ??
Google and other such services only can provide you with a height above sea-level. If you want to calculate the height of the building you'd have to use a device with a barometer sensor, which measures the atmospheric pressure. See http://developer.android.com/reference/android/hardware/SensorEvent.html and Sensor.TYPE_PRESSURE. I'm not aware of devices actually having such a sensor though...
Alternatively you could use an altimeter or perhaps look up the building's plan (if it's a specific building).

Categories

Resources