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
Related
I am searching Latitude and longitude bounds in google map for a specific city. I got the example to implement for country name India.
private static final LatLngBounds BOUNDS_INDIA = new LatLngBounds(new LatLng(23.63936, 68.14712), new LatLng(28.20453, 97.34466));
Now, I want to set it for my chosen country. Where to find those two point Latitude and Longitude for specific area.
Check the below code
String location=cityName;
String inputLine = "";
String result = ""
location=location.replaceAll(" ", "%20");
String myUrl="http://maps.google.com/maps/geo?q="+location+"&output=csv";
try{
URL url=new URL(myUrl);
URLConnection urlConnection=url.openConnection();
BufferedReader in = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
while ((inputLine = in.readLine()) != null) {
result=inputLine;
}
String lat = result.substring(6, result.lastIndexOf(","));
String longi = result.substring(result.lastIndexOf(",") + 1);
}
catch(Exception e){
e.printStackTrace();
}
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.
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)
I'm retrieving addresses from cooridnates using the Google API with the following method:
public static String[] getFromLocation(double lat, double lng, int retries) {
String address = String.format(Locale.getDefault(),
"https://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=false&language="
+ Locale.getDefault(), lat, lng);
String[] res = new String[3];
String addressLine = "";
String locality = "";
String country = "";
String json = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
URL url = new URL(address);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
json = jsonResults.toString();
JSONObject jsonObject = new JSONObject(json);
if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) {
JSONArray results = jsonObject.getJSONArray("results");
if (results.length() > 0) {
JSONObject result = results.getJSONObject(0);
//Address addr = new Address(Locale.getDefault());
JSONArray components = result.getJSONArray("address_components");
String streetNumber = "";
String route = "";
for (int a = 0; a < components.length(); a++) {
JSONObject component = components.getJSONObject(a);
JSONArray types = component.getJSONArray("types");
for (int j = 0; j < types.length(); j++) {
String type = types.getString(j);
if (type.equals("locality")) {
locality = component.getString("long_name");
} else if (type.equals("street_number")) {
streetNumber = component.getString("long_name");
} else if (type.equals("route")) {
route = component.getString("long_name");
} else if (type.equals("country")) {
country = component.getString("long_name");
}
}
}
addressLine = route + " " + streetNumber;
}
}
} catch (Exception e) {
Log.e(LOG_TAG, "Exception:", e);
LogsToServer.send(my_id, e);
if (json != null) LogsToServer.send(my_id, json);
System.out.println("retries: " + retries);
if (retries > 0){
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
return getFromLocation(lat, lng, retries-1);
}
}
res[0] = addressLine;
res[1] = locality;
res[2] = country;
return res;
}
The problem is that I very often get the exception:
03-12 23:54:01.387: E/GetAddressDetails(25248): java.io.FileNotFoundException: https://maps.googleapis.com/maps/api/geocode/json?latlng=48,2&sensor=false&language=en_GB
03-12 23:54:01.387: E/GetAddressDetails(25248): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:197)
03-12 23:54:01.387: E/GetAddressDetails(25248): at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
03-12 23:54:01.387: E/GetAddressDetails(25248): at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25)
If I launch the method with 4 retries, they may all fail, or sometimes after 2 or 3 I get the address. Do you know why it fails so often? When I access the same site in my browser I always get the page without errors!
EDIT: I checked the error message returned by Google and it goes like this:
We're sorry... but your computer or network may be sending automated queries. To protect our users, we can't process your request right now.
Is it a joke? Automated queries? Isn't it the whole purpose of APIs to be called by automatic processes?
Also, this happens from many phones and started yesterday. How does google know that all the requests come from the same app?
If you want to get address from cooridnates, you can use Geocoder api.
I used following code in my app to get the city name:
private double mLongitude; // current longitude
private double mLatitude; // current latitude
private String mCityName; // output cityName
private void getCityName() {
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(mLatitude, mLongitude, 1);
if (addresses.size() != 0) {
mCityName = addresses.get(0).getAddressLine(1);
mCityName = mCityName.replaceAll("[\\d.]", "");
Log.d(TAG + "!!!!!!!!!!!", mCityName);
}
} catch (IOException e) {
e.printStackTrace();
}
}
If you want get whole address, as I changed a little bit, just do this way:
private double mLongitude; // current longitude
private double mLatitude; // current latitude
private String mAddress; // output address
private void getAddress() {
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(mLatitude, mLongitude, 1);
if (addresses.size() != 0) {
mAddress = addresses.get(0).getAddressLine(0) + " " +
addresses.get(0).getAddressLine(1) + " " +
addresses.get(0).getAddressLine(2);
//mAddress = mAddress.replaceAll("[\\d.]", "");
Log.d(TAG + "!!!!!!!!!!!", mAddress);
}
} catch (IOException e) {
e.printStackTrace();
}
}
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).