I'm making an app that shows the user the nearest gyms. After I put in a request to the Google Places Api, it returns me some json. I get the latitude from that json using regex. However, I cannot get the longitude. My code is below. Can someone help please?
for (int i = 0; i < jsonArray.length(); i++){
String latitude = "\"lat\":";
String longitude = "lng\":";
Pattern p = Pattern.compile(latitude +"(.*?),");
Pattern pattern = Pattern.compile(longitude + "(.*?)"+ ",");
JSONObject jsonPart = jsonArray.getJSONObject(i);
String latLong = jsonPart.getString("geometry");
Matcher m = p.matcher(jsonPart.getString("geometry"));
Matcher matcher = pattern.matcher(jsonPart.getString("geometry"));
while( matcher.find()) {
Log.i("longitude", matcher.group(1));
}
while (m.find()){
Log.i("latitude", m.group(1));
}
}
This is the line I need to get the latitude and longitude from. I can get the latitude, but longitude doesn't work.
gymlocation: {"location":{"lat":40.4434584,"lng":-79.964227}}
String longitude = "\"lng\":";
You are missing \"
Alternatively, isn't this better?
Geting json response from Google places API in android
If you still want to use regex, your second expression "lng"(.*?), isn't finding anything because of the ? lazy operator. It will try to match at least characters as possible , and as the string you're searching on has no , but your expression tries to match one at the end, it will just not match anything.
Related
this is the request format
https://roads.googleapis.com/v1/nearestRoads?parameters&key=YOUR_API_KEY
here i need to pass latitude and longitude as parameter points, something like this
https://roads.googleapis.com/v1/nearestRoads?points=60.170880,24.942795|60.170879,24.942796|60.170877,24.942796&key=YOUR_API_KEY
i tried to pass it like
#POST("nearestRoads?points&key=my_api_key")
Call<SnappedPoints> getNearestRoad(#FieldMap Double map);
by calling
Call<SnappedPoints> call = retrofitClientMap.getNearestRoad(stringStringMap.put(latLng3.latitude,latLng3.longitude));
but it shows an illegal exception , can any one help have an idea to solve it
Have you tried something like this
#POST("nearestRoads?key=my_api_key")
Call<SnappedPoints> getNearestRoad(#Field("points") String points);
then pass your points as String to this method
i got it by calling api service like
#POST("nearestRoads?key=my_api_key")
// Call<MySnappedPoints> getNearestRoad();
Call<MySnappedPoints> getNearestRoad(#Query("points") String points);
calling it by
String test = Double.toString(mGoogleMap.getCameraPosition().target.latitude) + "," + Double.toString(mGoogleMap.getCameraPosition().target.longitude);
Call<MySnappedPoints> call = retrofitClientMap.getNearestRoad(test);
The API returns either a whole number like = 129
or A decimal for example 0.28
Here is the response from API:
"ETH":{"USD":730.06}"
I'm trying to parse the JSON
with the following:
Double ethPrice = (double) arr.get("USD");
Which works if the data returned is a number with a decimal but if it is a whole number then I'm getting:
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double
I'm not doing any mathematical function with the response, therefore, a string type would work too.
I feel like it is a small problem I should have solved already. But spent a bit of time on it now and don't want to waste anymore.
Any help would be great.
Edit :
Request code snippet of parsing:
JSONObject obj = new JSONObject(result);
JSONObject arr = obj.getJSONObject("ETH");
Double ethPrice = (double) arr.get("USD");
Where result is a string (inside async task - onPostExecute(String result))
If you sure that you will get Double, you can use arr.getDouble("USD") instead of arr.get("USD").
Your code will be the next:
JSONObject obj = new JSONObject(result);
JSONObject arr = obj.getJSONObject("ETH");
Double ethPrice = arr.getDouble("USD");
Example JSON Page
http://maps.googleapis.com/maps/api/geocode/json?latlng=51.155455,-0.165058&sensor=true
#SuppressLint("NewApi")
public void readAndParseJSON(String in) {
try {
JSONObject reader = new JSONObject(in);
// This works and returns address
JSONArray resultArry = reader.getJSONArray("results");
String Address = resultArry.getJSONObject(1).getString("formatted_address").toString();
Log.e("Address", Address);
// Trying to get PostCode on code below - this is not working (log says no value at address components)
JSONArray postCodeArray = reader.getJSONArray("address_components");
String postCode = postCodeArray.getJSONObject(1).getString("long_name").toString();
Log.e("PostCode", postCode );
This code returns the address correctly. How can I get the post code long_name which is inside address_components?
Solution
I had to get each array, and then get the post code value.
I am using the value 7, as that is the JSONObject that has the postcode stored in the "long_name" field.
JSONObject readerJsonObject = new JSONObject(in);
readerJsonObject.getJSONArray("results");
JSONArray resultsJsonArray = readerJsonObject.getJSONArray("results");
JSONArray postCodeJsonArray = resultsJsonArray.getJSONObject(0).getJSONArray("address_components");
String postCodeString = postCodeJsonArray.getJSONObject(7).getString("long_name").toString();
Log.e("TAG", postCodeString);
Hope that helps.
reader.getJSONObject(1).getJSONArray("address_components");
Your problem is that results is a JSONArray that contains a child JSONObject composed of several children: "address_components", "formatted_address", "geometry", and "types". The result array actually contains many of these such objects, but let's focus on just the first child for now.
Look carefully at your code. With this line:
JSONArray resultArry = reader.getJSONArray("results");
You are getting the entire results. Later on, you then call the same method again:
JSONArray postCodeArray = reader.getJSONArray("address_components");
But you're asking for an "address_components" from the reader, where I do not expect you'll find anything (having already read the entire result before.) You should instead be working with the JSONArray you already got before, since it already contains the entire result.
Try something like:
JSONObject addressComponents = resultArry.getJSONObject(1).getJSONObject("address_components");
String postCode = addressComponents.getString("long_name");
Note: I don't know why you're singling out JSONObject #1 (as opposed to 0, which is the first, or any other one of them) and I also am not sure why you named the String postCode. So if I've misunderstood your intention, I apologize.
Is difficult to find the error... because all looks well. The problem maybe can exist when you make the json.put("address_components", something);
So my advice is put a breakpoint at this line
JSONArray postCodeArray = reader.getJSONArray("address_components");
o display the json in logcat
Log.d("Simple", reader.toString());
Then Paste your json in this web page to view more pretty
http://jsonviewer.stack.hu/
and check if all keys are stored well.
Solution
Need to get each array, and then get the post code value. The value 7 is used, as that is the JSONObject that has the postcode stored in the "long_name" field.
JSONObject readerJsonObject = new JSONObject(in);
readerJsonObject.getJSONArray("results");
JSONArray resultsJsonArray = readerJsonObject.getJSONArray("results");
JSONArray postCodeJsonArray = resultsJsonArray.getJSONObject(0).getJSONArray("address_components");
String postCodeString = postCodeJsonArray.getJSONObject(7).getString("long_name").toString();
Log.e("TAG", postCodeString);
Hope that helps.
I'm working on finding nearby places in my Android app. I can find the current latitude and longitude as a double and then converting the double into a string to display in a textview (just to prove to myself that it's working). The problem I'm having is passing the lat. & long. strings into the Places URL. The URL displays the JSON data when I use a fixed value string for the lat. and long., but it returns INVALID_REQUEST when I try to pass the obtained doubles converted into strings into the URL. Here's what it looks like:
Location currentLocation;
double currLatitude;
double currLongitude;
String latString;
String longiString;
String latString2 = "30.4335320";
String longiString2 = "-97.9822360";
towers = locMan.getBestProvider(criteria, true);
currentLocation = locMan.getLastKnownLocation(towers);
currLatitude = currentLocation.getLatitude();
currLongitude = currentLocation.getLongitude();
latString = String.valueOf(currLatitude);
longiString = String.valueOf(currLongitude);
latiText.setText(latString);
longiText.setText(longiString);
I think maybe I'm not parsing the doubles into strings correctly here?
latString = String.valueOf(currLatitude);
longiString = String.valueOf(currLongitude);
because in the below URL when I use the parsed values latString, longiString that's when I get INVALID_REQUEST, but if I pass latString2, longiString2, which are given values, the URL displays the JSON data. Here's the URL:
String tURL="https://maps.googleapis.com/maps/api/place/search/json?"
+ "location=" + latString + "," + longiString
+ "&radius=25000&"
+ "types=church&name=baptist&sensor=false&key="
+ myPlaceKey;
I fugured it out. My problem was that the activity that returned the URL was a separate Activity from the URL string builder. And the URL returning Activity did not call the method where I obtained the latitude and longitude, so I think the URL the returning Activity obtained basically had "null" for the coordinates. So I combined the two Activities so now the coordinates are obtained, then the URL is built, then the URL result is displayed in a textview, all in one Activity - and it WORKS! I'm such an idiot!
In my application am setting a default value to latitude and longitude.
When i type the cityname in edittext i need to move that point to that place where i need
Use the below code to get the lat and long of city name
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();
}
My suggestion is to use Google GeoCoding REST API , not Geocoder.
Because I once used it in my country,China,I have a error below:
"java.io.IOException: Service not Available"
after search , It`s seems that
"The Geocoder class requires a backend service that is not included in the core android framework. The Geocoder query methods will return an empty list if there no backend service in the platform. Use the isPresent() method to determine whether a Geocoder implementation exists."
So I turn to Google GeoCoding REST API , It`s easy , just request like this:
http://maps.googleapis.com/maps/api/geocode/json?address=NewYork&sensor=false
You will get a json that has geo location in it.
And You can also get Address from locaiton through it:
http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false
If you can read Chinese , I have a blog about this,check this out:
http://wangchao.de/android%E5%88%A9%E7%94%A8google-geocoding-api%E6%9B%BF%E4%BB%A3geocoder-%E8%A7%A3%E5%86%B3%E5%9C%B0%E5%9D%80%E8%AF%AD%E8%A8%80%E9%97%AE%E9%A2%98
Use the Geocoder class.
Geocode gc = new Geocoder();
List<Address> ads = gc.getFromLocationName(cityName,maxResults);
From the docs :
A class for handling geocoding and reverse geocoding. Geocoding is the process of transforming a street address or other description of a location into a (latitude, longitude) coordinate. Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a (partial) address. The amount of detail in a reverse geocoded location description may vary, for example one might contain the full street address of the closest building, while another might contain only a city name and postal code. The Geocoder class requires a backend service that is not included in the core android framework. The Geocoder query methods will return an empty list if there no backend service in the platform. Use the isPresent() method to determine whether a Geocoder implementation exists.
Try to get the GeoPoint of cityname
GeoPoint startGP = new GeoPoint(
(int) (Double.parseDouble(cityname.getText()) * 1E6));
Then u can able to get the latitude and longitude from GeoPoint by using below code.
Double.toString((double)startGP.getLatitudeE6() / 1E6),
Double.toString((double)dest.getLongitudeE6() / 1E6)