How to get latitude and longitude bounds by city/country name android - android

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();
}

Related

Reading Latitude and longitude from CSV file and display in google map after applying filtering to a column

I managed to fetch long and lat values from CSV and loop them to display all values in google map .Now i need to filter column Fuel_Type = "Unleaded 91" how to add this to while loop ?
while( (line = reader.readLine()) != null)
here is my code to fetch data from CSV
private void readDataFromCSV() {
// Read the raw csv file
InputStream is = getResources().openRawResource(R.raw.data);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8"))
);
boolean header = true;
List<String> list = new ArrayList<>();
List<LatLng> latLngList = new ArrayList<LatLng>();
// Initialization
try {
reader.readLine();
while( (line = reader.readLine()) != null) // Read until end of file
{
double lat = Double.parseDouble(line.split(",")[7]);
double lon = Double.parseDouble(line.split(",")[8]);
latLngList.add(new LatLng(lat, lon));
}
// Add them to map
for(LatLng pos : latLngList)
{
mMap.addMarker(new MarkerOptions().position(pos).title("title").icon(bitmapDescriptorFromVector(getApplicationContext(), R.drawable.seveneleven)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(pos, 18f));
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(MapsActivity.this));
}
} catch (IOException e) {
Log.wtf("MapsActivity", "Error reading data file on line" + line, e);
e.printStackTrace();
}
}
my CSV file :
SiteId,Site_Name,Site_Brand,Sites_Address_Line_1,Site_Suburb,Site_State,Site_Post_Code,Site_Latitude,Site_Longitude,Fuel_Type,Price,TransactionDateutc
61291313,7-Eleven Runaway Bay,BP,20 Bayview Street,Mungindi,QLD,4497,-27.923529,153.403729,Unleaded 91,1840,1/3/2022 0:00
61291313,Caltex Labrador,BP,150 Brisbane Road,Mungindi,QLD,4497,-27.924007,153.403869,Diesel,1860,2/3/2022 21:49
61291313,Coles shell,BP,69 Frank Street,Mungindi,QLD,4497,-27.923863,153.403528,Diesel,1900,3/3/2022 22:21
61291313,BP Shop Helensvale,BP,2 Discovery Drive,Mungindi,QLD,4497,-27.923655,153.403608,Diesel,2150,9/3/2022 23:12
you can check if line contains your fuel type or not, like this:
while( (line = reader.readLine()) != null) // Read until end of file
{
if(line.contains("YOUR_FUEL_TYPE"){
double lat = Double.parseDouble(line.split(",")[7]);
double lon = Double.parseDouble(line.split(",")[8]);
latLngList.add(new LatLng(lat, long));
}
}

Fetching Location Distance issue sending 0.0

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)

Google Maps API calls failing on Android, "automated queries" error

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();
}
}

Exception in finding driving distance between two geopiont

I want to find out driving distance between two latitude and longitude.
this is my code
private String GetDistance(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 urlString = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + parameters;
// get the JSON And parse it to get the directions data.
HttpURLConnection urlConnection = null;
URL url = null;
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
InputStream inStream = urlConnection.getInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(
inStream));
String temp,response = "";
while ((temp = bReader.readLine()) != null) {
// Parse data
response += temp;
}
// Close the reader, stream & connection
bReader.close();
inStream.close();
urlConnection.disconnect();
// Sort out JSONresponse
// JSONObject object = (JSONObject) new JSONTokener(response)
// .nextValue();
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("routes");
// Log.d("JSON","array: "+array.toString());
// Routes is a combination of objects and arrays
JSONObject routes = array.getJSONObject(0);
// Log.d("JSON","routes: "+routes.toString());
String summary = routes.getString("summary");
Log.d("JSON","summary: "+summary);
JSONArray legs = routes.getJSONArray("legs");
// Log.d("JSON","legs: "+legs.toString());
JSONObject steps = legs.getJSONObject(0);
// Log.d("JSON","steps: "+steps.toString());
JSONObject distance = steps.getJSONObject("distance");
// Log.d("JSON","distance: "+distance.toString());
sDistance = distance.getString("text");
iDistance = distance.getInt("value");
} catch (Exception e) {
// TODO: handle exception
return e.toString();
}
return sDistance;
}
and i am getting a exception
org.json.JSONException:Index 0 out of range [0..0)
this is my stacktrace
Ljava.lang.StackTraceElement;#41019be8
please help me out what is the problem.
First of all, don't hardcode any position(like 0) to get from array. Bcs, the array may be empty.
That's what happened in your case. One of your array or legs JSONArray is empty but you are trying to get the 0th position of them. So,it is throwing index out of range exception.
To get the values from an array better use for loop. An example code snippet is:
Log.v("array-length--", ""+array.length());
for(int i=0; i < array.length();i++)
{
// Routes is a combination of objects and arrays
JSONObject routes = array.getJSONObject(i);
// Log.d("JSON","routes: "+routes.toString());
String summary = routes.getString("summary");
Log.d("JSON","summary: "+summary);
JSONArray legs = routes.getJSONArray("legs");
// Log.d("JSON","legs: "+legs.toString());
Log.v("legs-length--", ""+legs.length());
for(int j=0; j < legs.length(); j++)
{
JSONObject steps = legs.getJSONObject(j);
// Log.d("JSON","steps: "+steps.toString());
JSONObject distance = steps.getJSONObject("distance");
// Log.d("JSON","distance: "+distance.toString());
sDistance = distance.getString("text");
iDistance = distance.getInt("value");
}
}

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

Categories

Resources