Google Places Api sort by distance - android

Currently developing an Android application that returns the closest 20 location to the users current location.
Google Places API is returning ~20 places close to the users location but not the closest 20 sorted by distance.
Looking at the Google Places API Documentation does not show anything that I can see to be incorrect.
GetPlaces.java
String types = "accounting|airport|amusement_park|aquarium|art_gallery|atm|bakery|bank|bar|beauty_salon|bicycle_store|book_store|bowling_alley|bus_station|cafe|campground|car_dealer|car_rental|car_repair|car_wash|casino|cemetery|church|city_hall|clothing_store|convenience_store|courthouse|dentist|department_store|doctor|electrician|electronics_store|embassy|establishment|finance|fire_station|florist|food|funeral_home|furniture_store|gas_station|general_contractor|grocery_or_supermarket|gym|hair_care|hardware_store|health|hindu_temple|home_goods_store|hospital|insurance_agency|jewelry_store|laundry|lawyer|library|liquor_store|local_government_office|locksmith|lodging|meal_delivery|meal_takeaway|mosque|movie_rental|movie_theater|moving_company|museum|night_club|painter|park|parking|pet_store|pharmacy|physiotherapist|place_of_worship|plumber|police|post_office|real_estate_agency|restaurant|roofing_contractor|rv_park|school|shoe_store|shopping_mall|spa|stadium|storage|store|subway_station|synagogue|taxi_stand|train_station|travel_agency|university|veterinary_care|zoo";
resourceURI = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+myLocation.latitude+","+myLocation.longitude+"&radius=500&rankBy=distance&types="+ URLEncoder.encode(types, "UTF-8")+"&sensor=true&key=GOOGLE_MAPS_KEY";
try {
String url =resourceURI; //getURL(myLocation.latitude,myLocation.longitude);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
HttpConnectionParams.setSoTimeout(httpParams, 30000);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Content-type", "application/json");
ResponseHandler responseHandler = new BasicResponseHandler();
String response = (String) httpClient.execute(httpGet, responseHandler);
if (response != null) {
mResult = new JSONObject(response);
results = mResult.getJSONArray("results");
}
}
catch (ClientProtocolException e) {
e.printStackTrace();
return null;
}
catch (IOException e) {
e.printStackTrace();
return null;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
return results;
}
This returns valid JSON, but not the closest places to the passed in distance. I know for a fact that there are closer places than what the request is returning.
For example, I make a request at a known google place, but it is not showing the place I am currently at- but others that are farther.

Maybe you've already solved your problem, but I hope this can help (Focus on what is in bold):
radius - Defines the distance (in meters) Within Which to return Place results. The maximum allowed is 50 000 meters radius. Note That radius must not be included if rankby = distance (Described below under Optional parameters) is specified.
rankby — Specifies the order in which results are listed. Possible values are:
prominence (default). This option sorts results based on their importance. Ranking will favor prominent places within the specified area. Prominence can be affected by a Place's ranking in Google's index, the number of check-ins from your application, global popularity, and other factors.
distance. This option sorts results in ascending order by their distance from the specified location. When distance is specified, one or more of keyword, name, or types is required.
according: https://developers.google.com/places/documentation/search?hl=en
I have understood according to google documentation that you can not simultaneously send arguments "rankby" and "radius", you must use only one of them at the same time, this way you will get the results sorted by distance.
test the request doing this:
resourceURI = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?
location="+myLocation.latitude+","+myLocation.longitude+"&rankBy=distance
&types="+ URLEncoder.encode (types, "UTF-8") + "&sensor = true&
key = GOOGLE_MAPS_KEY";
to see how you do, good luck!

Hope this code will work..
private ArrayList<CLPlaceDTO> sortLocation(LatLng currentLatLng, ArrayList<?> alLocationDTO)
{
ArrayList<CLPlaceDTO> clPlaceDTOArrayList;
ArrayList<CLPlaceDTO> clPlaceDTOArrayList1 = new ArrayList<>();
double dCurrentLat = currentLatLng.latitude;
double dCurrentLong = currentLatLng.longitude;
Iterator<?> clIterator = alLocationDTO.iterator();
while (clIterator.hasNext())
{
clIterator.next();
clPlaceDTOArrayList = new ArrayList<>();
for (int j = 0; j < alLocationDTO.size(); j++)
{
CLLocationDTO clLocationDTO = (CLLocationDTO) alLocationDTO.get(j);
double dLat = clLocationDTO.getLatitude().doubleValue();
double dLng = clLocationDTO.getLongitude().doubleValue();
LatLng clNewLatLng = new LatLng(dLat, dLng);
double dDistance = getDistance(dCurrentLat, dCurrentLong, dLat, dLng);
CLPlaceDTO clPlaceDTO = new CLPlaceDTO(clLocationDTO.getAccountName(), clNewLatLng, dDistance);
clPlaceDTOArrayList.add(clPlaceDTO);
}
Collections.sort(clPlaceDTOArrayList, new CLSortPlaces(currentLatLng));
dCurrentLat = clPlaceDTOArrayList.get(0).getLatlng().latitude;
dCurrentLong = clPlaceDTOArrayList.get(0).getLatlng().longitude;
clPlaceDTOArrayList1.add(clPlaceDTOArrayList.get(0));
clIterator.remove();
}
return clPlaceDTOArrayList1;
}
public static double getDistance(double dbFromLatitude,double dbFromLongitude,double dbToLatitude,double dbToLongitude)
{
double dbRadiusMeters = EARTH_RADIUS * 1000 ; // Earth’s mean radius in meter
double dbLatitudeDiff = Math.toRadians(dbToLatitude - dbFromLatitude);
double dbLongitudeDiff = Math.toRadians(dbToLongitude - dbFromLongitude);
double a = Math.sin(dbLatitudeDiff / 2) * Math.sin(dbLatitudeDiff / 2) +
Math.cos(Math.toRadians(dbFromLatitude)) * Math.cos(Math.toRadians(dbToLatitude)) *
Math.sin(dbLongitudeDiff / 2) * Math.sin(dbLongitudeDiff / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double d = dbRadiusMeters * c;
return d; // returns the distance in meter
}
public class CLSortPlaces implements Comparator<CLPlaceDTO>
{
private LatLng currentLoc;
CLSortPlaces(LatLng current)
{
currentLoc = current;
}
#Override
public int compare(final CLPlaceDTO place1, final CLPlaceDTO place2)
{
return (int) (place1.dDistance - place2.dDistance);
}
}
public class CLPlaceDTO
{
public LatLng latlng;
public String sNameOfLocation;
public double dDistance;
public CLPlaceDTO(String sNameOfLocation, LatLng latlng,double dDistance)
{
this.sNameOfLocation = sNameOfLocation;
this.latlng = latlng;
this.dDistance=dDistance;
}
public CLPlaceDTO(String sNameOfLocation, LatLng latlng)
{
this.sNameOfLocation = sNameOfLocation;
this.latlng = latlng;
this.dDistance=dDistance;
}}

It's quite possible that the places that you're thinking are closer than the places that are being returned are not true Google places.
Check out this FAQ for getting your business on Google maps: https://support.google.com/places/answer/145585?hl=en .
A test for this could be to attempt to register the business you think is closer with Google places https://www.google.com/local/business/add?hl=en&migratedId=04614545856067425787 and see if it allows you. If you can, this would mean that they are not a true Google place and would not show up in this result set.

Related

Cannot create route from one point to another ArcGIS Android

I've been trying very hard to create a route between two points(startPoint, endPoint). But i am getting the following error:
Location "Location 1" in "Stops" is unlocated. Location "Location 2" in "Stops" is unlocated. Need at least 2 valid stops. "Stops" does not contain valid input for any route.
I've posted this question on gis.stackexchange.com and geonet.esri.com and didn't get a reply except one which was not helpful.
My Code:
private final String routeTaskURL = "http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Network/USA/NAServer/Route";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMapView = (MapView) findViewById(R.id.map);
mMapView.enableWrapAround(true);
new Thread(new Runnable() {
#Override
public void run() {
try {
UserCredentials userCredentials = new UserCredentials();
userCredentials.setUserToken(token, clientID);
RouteTask routeTask = RouteTask.createOnlineRouteTask(routeTaskURL, userCredentials);
RouteParameters routeParameters = routeTask.retrieveDefaultRouteTaskParameters();
NAFeaturesAsFeature naFeatures = new NAFeaturesAsFeature();
Point startPoint = new Point(36.793653, -119.866896);
Point stopPoint = new Point(36.795488, -119.853345);
StopGraphic startPnt = new StopGraphic(startPoint);
StopGraphic stopPnt = new StopGraphic(stopPoint);
naFeatures.setFeatures(new Graphic[] {startPnt, stopPnt});
routeParameters.setStops(naFeatures);
RouteResult mResults = routeTask.solve(routeParameters);
List<Route> routes = mResults.getRoutes();
System.out.println(mResults.getRoutes());
Route mRoute = routes.get(0);
Geometry geometry = mRoute.getRouteGraphic().getGeometry();
Graphic symbolGraphic = new Graphic(geometry, new SimpleLineSymbol(Color.BLUE, 3));
mGraphicsLayer.addGraphic(symbolGraphic);
System.out.println(mResults.getStops());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
I've searched the internet. Many developers were/are facing this problem. I've tried all the solutions but none of them worked. I got routeTaskURL from the ArcGIS Routing Sample app. The link which is given in the documentation of ArcGIS maps gives me the 403 error if i open it in the browser.
Note: "token" and "clientID" is declared in the first step and they both are taken from the ArcGIS developers console where i registered my application.
Any Suggestions?
Your X and Y values are switched. Change to this:
Point startPoint = new Point(-119.866896, 36.793653);
Point stopPoint = new Point(-119.853345, 36.795488);
See the Point class documentation to learn that the constructor parameters are (x, y), not (y, x). The route service you're using has a default spatial reference of 4326, which is unprojected longitude and latitude. -119.866896 and -119.853345 are not valid latitude (y) values, but they are valid longitude (x) values.

Android: Am I doing client-side or server-side Geocoding?

So in my app I am making use of google map apis and I'm using Geocoding to determine the Address based on the user's current location. I was using the Geocoder Android Class but I've found that it truly works terribly. It's just not reliable. So I used a post I saw here at SO to create my own Geocoder. Problem is, I now don't know if I'm using server side or client side geocoding. This is kind of important because one has a limit and the other really doesn't. All of my code is in Android though.
Here's some code, this is within my "MyGeocoder" Class:
public List<Address> getFromLocation(double latitude, double longitude,
int maxResults) throws IOException, LimitExceededException {
if (latitude < -90.0 || latitude > 90.0) {
throw new IllegalArgumentException("latitude == " + latitude);
}
if (longitude < -180.0 || longitude > 180.0) {
throw new IllegalArgumentException("longitude == " + longitude);
}
if (isLimitExceeded(context)) {
throw new LimitExceededException();
}
final List<Address> results = new ArrayList<Address>();
final StringBuilder url = new StringBuilder(
"http://maps.googleapis.com/maps/api/geocode/json?sensor=true&latlng=");
url.append(latitude);
url.append(',');
url.append(longitude);
url.append("&language=");
url.append(Locale.getDefault().getLanguage());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url.toString());
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
Gson gson = new Gson();
MyGeocodeResponse geocodeResponse = gson.fromJson(jsonResult, MyGeocodeResponse.class);
final Address current = new Address(Locale.getDefault());
if(geocodeResponse.getStatus().equals(STATUS_OK)) {
MyGeocode locGeocode= geocodeResponse.getResults().get(0);
String streetAddress = "";
for(MyAddressComponent component : locGeocode.getAddress_components()) {
for(String type : component.getTypes()) {
if(type.equals("locality")) {
current.setLocality(component.getLong_name());
}
if(type.equals("administrative_area_level_1")) {
current.setAdminArea(component.getLong_name());
}
if(type.equals("street_number")) {
if(streetAddress.length() != 0) {
current.setAddressLine(0, component.getLong_name() + " " + streetAddress);
} else {
streetAddress = component.getLong_name();
}
}
if(type.equals("route")) {
if(streetAddress.length() != 0) {
current.setAddressLine(0, streetAddress + " " + component.getShort_name());
} else {
streetAddress = component.getShort_name();
}
}
}
}
current.setLatitude(latitude);
current.setLongitude(longitude);
results.add(current);
}
Log.i("TEST", "Got it");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return results;
}
Edit:
And I guess a further questions is, if this is server-side Geocoding, then can this code only be run 2,500 times per day period, or can it be run 2,500 times daily per user of the app? If it's the first option I'm still ok, but if it's the 2nd option I don't see how any app that wants to have a half-way big user base can use server-side geocoding without hitting that limit.
I now don't know if I'm using server side or client side geocoding
after looking to your code you wrote http://maps.googleapis.com/maps/api/geocode/json?sensor=true&latlng=,so it is server side reverse geocoding as you are calling geocoding api by making an extra External http call.
if this is server-side Geocoding, then can this code only be run 2,500 times per day period, or can it be run 2,500 times daily per user of the app?
2,500 request limit is per IP address(basically it is mentioning 2500 request per day),yah this code only be run 2,500 times per day for all of your user.One thing you should keep in mind you are making http call to geocoder api so it doesn't matter from where you are making this call from server or from client.
you should have a look on this google link where they have mention "When to Use Client-Side Geocoding" and "When to Use Server-Side Geocoding".

Android convert CID location to Coordinates

I built an android app which can handle a share intent from Google Maps and show it's coordinates.
The problem is that they send a short url which I decode with Google's url shortner api and in some cases, the result long link is of this type: http://maps.google.com/?cid=3635533832900933072&hl=en&gl=us.
Can anyone help me on how to get the coresponding coordinates to "cid=3635533832900933072"
As far as I know there is no public API to get the location from a cid.
However, a possible workaround would be to parse the Google Maps output to obtain the latitude and longitude (though it may be brittle, if they change the result format).
(Although the url contains output=json, it's not actually json -- that's why I parse it with substring() and such instead of using JSONObject).
Try this code:
public static LatLng getCidCoordinates(String cid)
{
final String URL_FORMAT = "http://maps.google.com/maps?cid=%s&q=a&output=json";
final String LATLNG_BEFORE = "viewport:{center:{";
final String LATLNG_AFTER = "}";
final String LATLNG_SEPARATOR = ",";
final String LAT_PREFIX = "lat:";
final String LNG_PREFIX = "lng:";
try
{
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(String.format(URL_FORMAT, cid));
HttpResponse response = client.execute(get);
String text = EntityUtils.toString(response.getEntity(), "UTF-8");
int startIndex = text.indexOf(LATLNG_BEFORE);
if (startIndex == -1)
return null;
startIndex += LATLNG_BEFORE.length();
int endIndex = text.indexOf(LATLNG_AFTER, startIndex);
// Should be "lat:<number>,lng:<number>"
String[] parts = text.substring(startIndex, endIndex).split(LATLNG_SEPARATOR);
if (parts.length != 2)
return null;
if (parts[0].startsWith(LAT_PREFIX))
parts[0] = parts[0].substring(LAT_PREFIX.length());
else
return null;
if (parts[1].startsWith(LNG_PREFIX))
parts[1] = parts[1].substring(LNG_PREFIX.length());
else
return null;
return new LatLng(Double.parseDouble(parts[0]), Double.parseDouble(parts[1]));
}
catch (NumberFormatException e)
{
e.printStackTrace();
return null;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
After reading this post yesterday, I found a new method to do it. I hope Google do not close this new API and hidden parameter. :)
You can use this API hidden parameter to get the coordinater. Usage: https://maps.googleapis.com/maps/api/place/details/json?cid=YOUR_CID&key=YOUR_KEY
It returns a result contains formatted address, place_id, name of the address and GPS coordinater.
Please see my blog to see more detail: https://leonbbs.blogspot.com/2018/03/google-map-cid-to-placeid-or-get.html
In latest Google Maps update, the share intent contains the address name in the body which can be decoded with Geocoder into coordinates.

How to use Google maps search functionality api in my application?

Is it possible to use it as library project for my application,i want to use Android Google Maps real app search-ability functionality. How can i do it,is it possible?
Thanks in advance..
EDIT:
I have shown Google Map in my app successfully, I want to include Google Map search functionality means that I can able to search any location in the world in auto suggested field and by selecting a particular location and move marker to that location. so how can I?
I tried this and this but not getting auto suggested text why I don't know..
I want like:
step1: show map with search box
step2: while entering text it should auto suggest.
step3: when click on particular name move map to that location
You can easily provide that kind of search functionality by using Places API and Geocode API (Both will help you according to your usecase).
Read the below Documentation for your assistance.
GeoCode API
Places API
I would recommend to use Places API for your need ( As per my observation on your usecase). But you could also use geocode, If you needed.
Many working reference and examples are there.
For startup, below are my reference :
PlacesAPI AutoComplete feature, Hotel Finder with Autocomplete
GeocodeAPI Simple GeoCoding
NOTE :
I have suggested javascript API. But not sure whether it will help you in Android environment (I dont know anything about android environment).
No single Api can help you have to use multiple google api's
Step1. Implement Google Place autocomplete Read this
Step2. You have to geocode means you have to convert address to latitude and longitude check this
Step3. Now You can plot these lat-long on the map.
This works for me.
I think you should take a look at the Google Maps API for Android at https://developers.google.com/maps/documentation/android/
The Google Search Appliance doesn't have any mapping or geo search features right now.
This is how I did it ---
Android Manifest file should contain the following lines:
<uses-library
android:name="com.google.android.maps"
android:required="true" >
</uses-library>
<!-- You must insert your own Google Maps for Android API v2 key in here. -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="<put your api key value here>" />
Location XML file should have the following apart from anything extra:
<fragment
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Location java file should have something like this:
View mapView = null;
private GoogleMap mMap;
mMap = supportMapFragment.getMap();
mapView = (View) view.findViewById(R.id.map);
SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager
.findFragmentById(R.id.map);
if(mMap != null){
mMap.setMyLocationEnabled(true);
}
if(mMap != null)
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
new EditMap().execute("", String.valueOf(latLng.latitude), String.valueOf(latLng.longitude));
}
});
class EditMap extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
String address = args[0];
double latitude = Double.parseDouble(args[1]);
double longitude = Double.parseDouble(args[2]);
return editMap(address, latitude, longitude);
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
if(!result.equals(""))
ToastUtil.ToastShort(getActivity(), result);
else {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title(attvalue));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 11));
}
}
}
NOTE:
These are the minimal requirements for the setting of location as you choose from Map that fills the location in your text.
There is a background thread that runs as you long press the location in a map.
The listener defined for that is setOnMapLongClickListener as you see above.
The execution will place the marker to the exact location you chose to mark as set.
There will be a done button after you have chosen the location by a marker. This done button will confirm what you have chosen and will set that on a textfield for you.
The above code uses the method editMap to edit the map location.
The implementation is as done here:
private String editMap(String address, double latitude, double longitude ) {
String keyword = null;
try {
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
if(!address.equals("")){
keyword = address;
java.util.List<android.location.Address> result = geocoder
.getFromLocationName(keyword, 1);
if (result.size() > 0) {
lat = (double) result.get(0).getLatitude();
lng = (double) result.get(0).getLongitude();
attvalue = address;
} else {
return "Record not found";
}
} else {
String sUrl = "http://google.com/maps/api/geocode/json?latlng="+latitude+","+longitude+"&sensor=true";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(sUrl);
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if(status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
try{
JSONObject jsonObject = new JSONObject(data);
JSONArray results = jsonObject.getJSONArray("results");
JSONObject addressObject = results.getJSONObject(0);
JSONArray addressComp = addressObject.getJSONArray("address_components");
String city = "", state = "";
for(int i=0; i < addressComp.length(); i++){
JSONArray types = addressComp.getJSONObject(i).getJSONArray("types");
if(city.equals("") && types.getString(0).equals("locality"))
city = addressComp.getJSONObject(i).getString("long_name");
if(state.equals("") && types.getString(0).equals("administrative_area_level_1"))
state = addressComp.getJSONObject(i).getString("long_name");
if(!city.equals("") && !state.equals(""))
break;
}
attvalue = city + ", " + state;
} catch (JSONException e1) {
e1.printStackTrace();
}
lat = latitude;
lng = longitude;
}else{
return "Location Not Found";
}
}
} catch (IOException io) {
return "Connection Error";
}
return "";
}
I hope this is enough to help you out.

Google Places API - android

I am making an android application that needs to search in my local area within 10km and display the results onto a map using pins, For example: "Starbucks", "Wallmart", Shopping mall, etc. The search word that i specify in my activity class. And to be clear: I do NOT want to open the search in Google maps, i want it to display the results inside MY own application. But i get an error at the code that executes the search. The error comes up on the following things:
Url: url cannot be resolved or is not a field
Execute: The method execute() is undefined for the type HttpRequest
Response: response cannot be resolved or is not a field
I am using three packages:
com.mycompany.applicationname = Default package, containing main code, including the search code
com.mycompany.applicationname.Model = Containing PlaceAutoComplete, PlacesList, Place, etc.
com.mycompany.applicationname.PlacesRequests = Containing PlaceRequest.java
Please help me, i really need help and thanks SO much in advance
This is the code that i am using to execute the search:
private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?";
private static final boolean PRINT_AS_STRING = false;
public void performSearch() throws Exception {
try {
System.out.println("Perform Search ....");
System.out.println("-------------------");
HttpRequestFactory httpRequestFactory = createRequestFactory(transport);
HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_SEARCH_URL));
request.url.put("key", API_KEY);
request.url.put("location", lat + "," + lng);
request.url.put("radius", 500);
request.url.put("sensor", "false");
if (PRINT_AS_STRING) {
System.out.println(request.execute().parseAsString());
} else {
PlacesList places = request.execute().parseAs(PlacesList.class);
System.out.println("STATUS = " + places.status);
for (Place place : places.results) {
System.out.println(place);
}
}
} catch (HttpResponseException e) {
System.err.println(e.response.parseAsString());
throw e;
}
}
As far as the HTTP interface goes, your code LGTM assuming API_KEY holds a valid API key. That is, one created in the API console. Try printing out the whole request.url and see if it looks like this:
https://maps.googleapis.com/maps/api/place/search/json?key=AIzaSyDoTeTuPXXXXXXXXXMHPVYM5VTg&location=37.994682,-87.6045923&radius=500&sensor=false
Also see this thread because e.response isn't valid, maybe just remove that call to println and see what e looks like when it's thrown.
You can do this by using Google API JAVA Client - Here is an example using the java client for getting all the 60 results.
public PlacesList search(double latitude, double longitude, double radius, String types)
throws Exception {
try {
HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
HttpRequest request = httpRequestFactory
.buildGetRequest(new GenericUrl("https://maps.googleapis.com/maps/api/place/search/json?"));
request.getUrl().put("key", YOUR_API_KEY);
request.getUrl().put("location", latitude + "," + longitude);
request.getUrl().put("radius", radius);
request.getUrl().put("sensor", "false");
request.getUrl().put("types", types);
PlacesList list = request.execute().parseAs(PlacesList.class);
if(list.next_page_token!=null || list.next_page_token!=""){
Thread.sleep(4000);
/*Since the token can be used after a short time it has been generated*/
request.getUrl().put("pagetoken",list.next_page_token);
PlacesList temp = request.execute().parseAs(PlacesList.class);
list.results.addAll(temp.results);
if(temp.next_page_token!=null||temp.next_page_token!=""){
Thread.sleep(4000);
request.getUrl().put("pagetoken",temp.next_page_token);
PlacesList tempList = request.execute().parseAs(PlacesList.class);
list.results.addAll(tempList.results);
}
}
return list;
} catch (HttpResponseException e) {
return null;
}
}

Categories

Resources