-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathGooglePlaces.java
More file actions
409 lines (349 loc) · 15.3 KB
/
GooglePlaces.java
File metadata and controls
409 lines (349 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package se.walkercrou.places;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONObject;
import se.walkercrou.places.exception.GooglePlacesException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
/**
* Main class of API. Used for all entry web-api operations.
*/
public class GooglePlaces implements GooglePlacesInterface {
/*
* Argument #1: API Base URL
* Argument #2: API Method
* Argument #3: API Method arguments
*/
public static String API_URL_FORMAT_STRING = "%s%s/json?%s";
private String apiKey;
private RequestHandler requestHandler;
private boolean debugModeEnabled;
/**
* Creates a new GooglePlaces object using the specified API key and the specified {@link RequestHandler}.
*
* @param apiKey that has been registered on the Google Developer Console
* @param requestHandler to handle HTTP traffic
*/
public GooglePlaces(String apiKey, RequestHandler requestHandler) {
this.apiKey = apiKey;
this.requestHandler = requestHandler;
}
/**
* Creates a new GooglePlaces object using the specified API key.
*
* @param apiKey that has been registered on the Google Developer Console
*/
public GooglePlaces(String apiKey) {
this(apiKey, new DefaultRequestHandler());
}
/**
* Creates a new GooglePlaces object using the specified API key and character encoding. Using a character encoding
* other than UTF-8 is not advised.
*
* @param apiKey that has been registered on the Google Developer Console
* @param characterEncoding to parse data with
*/
public GooglePlaces(String apiKey, String characterEncoding) {
this(apiKey, new DefaultRequestHandler(characterEncoding));
}
private static String addExtraParams(String base, Param... extraParams) {
for (Param param : extraParams)
base += "&" + param.name + (param.value != null ? "=" + param.value : "");
return base;
}
private static String buildUrl(String method, String params, Param... extraParams) {
String url = String.format(Locale.ENGLISH, API_URL_FORMAT_STRING, API_URL, method, params);
url = addExtraParams(url, extraParams);
url = url.replace(' ', '+');
return url;
}
protected static void checkStatus(String statusCode, String errorMessage) {
GooglePlacesException e = GooglePlacesException.parse(statusCode, errorMessage);
if (e != null)
throw e;
}
/**
* Parses the specified raw json String into a list of places.
*
* @param places to parse into
* @param str raw json
* @param limit the maximum amount of places to return
* @return Next page token
*/
public static String parse(GooglePlaces client, List<Place> places, String str, int limit) {
// parse json
JSONObject json = new JSONObject(str);
// check root elements
String statusCode = json.getString(STRING_STATUS);
checkStatus(statusCode, json.optString(STRING_ERROR_MESSAGE));
if (statusCode.equals(STATUS_ZERO_RESULTS))
return null;
JSONArray results = json.getJSONArray(ARRAY_RESULTS);
parseResults(client, places, results, Math.min(limit, MAXIMUM_PAGE_RESULTS));
return json.optString(STRING_NEXT_PAGE_TOKEN, null);
}
private static void parseResults(GooglePlaces client, List<Place> places, JSONArray results, int limit) {
for (int i = 0; i < limit; i++) {
// reached the end of the page
if (i >= results.length())
return;
JSONObject result = results.getJSONObject(i);
// location
JSONObject location = result.getJSONObject(OBJECT_GEOMETRY).getJSONObject(OBJECT_LOCATION);
double lat = location.getDouble(DOUBLE_LATITUDE);
double lon = location.getDouble(DOUBLE_LONGITUDE);
String placeId = result.getString(STRING_PLACE_ID);
String iconUrl = result.optString(STRING_ICON, null);
String name = result.optString(STRING_NAME);
String addr = result.optString(STRING_ADDRESS, null);
double rating = result.optDouble(DOUBLE_RATING, -1);
String vicinity = result.optString(STRING_VICINITY, null);
// see if the place is open, fail-safe if opening_hours is not present
JSONObject hours = result.optJSONObject(OBJECT_HOURS);
boolean hoursDefined = hours != null && hours.has(BOOLEAN_OPENED);
Status status = Status.NONE;
if (hoursDefined) {
boolean opened = hours.getBoolean(BOOLEAN_OPENED);
status = opened ? Status.OPENED : Status.CLOSED;
}
// get the price level for the place, fail-safe if not defined
boolean priceDefined = result.has(INTEGER_PRICE_LEVEL);
Price price = Price.NONE;
if (priceDefined) {
price = Price.values()[result.getInt(INTEGER_PRICE_LEVEL)];
}
// the place "types"
List<String> types = new ArrayList<>();
JSONArray jsonTypes = result.optJSONArray(ARRAY_TYPES);
if (jsonTypes != null) {
for (int a = 0; a < jsonTypes.length(); a++) {
types.add(jsonTypes.getString(a));
}
}
Place place = new Place();
// build a place object
places.add(place.setClient(client).setPlaceId(placeId).setLatitude(lat).setLongitude(lon).setIconUrl(iconUrl).setName(name)
.setAddress(addr).setRating(rating).setStatus(status).setPrice(price)
.addTypes(types).setVicinity(vicinity).setJson(result));
}
}
@Override
public boolean isDebugModeEnabled() {
return debugModeEnabled;
}
@Override
public void setDebugModeEnabled(boolean debugModeEnabled) {
this.debugModeEnabled = debugModeEnabled;
}
private void debug(String msg) {
if (debugModeEnabled)
System.out.println(msg);
}
@Override
public String getApiKey() {
return apiKey;
}
@Override
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
@Override
public RequestHandler getRequestHandler() {
return requestHandler;
}
@Override
public void setRequestHandler(RequestHandler requestHandler) {
this.requestHandler = requestHandler;
}
@Override
public List<Place> getNearbyPlaces(double lat, double lng, double radius, int limit, Param... extraParams) {
try {
String uri = buildUrl(METHOD_NEARBY_SEARCH, String.format(Locale.ENGLISH, "key=%s&location=%s,%s&radius=%s",
apiKey, String.valueOf(lat), String.valueOf(lng), String.valueOf(radius)), extraParams);
return getPlaces(uri, METHOD_NEARBY_SEARCH, limit);
} catch (Exception e) {
throw new GooglePlacesException(e);
}
}
@Override
public List<Place> getNearbyPlaces(double lat, double lng, double radius, Param... extraParams) {
return getNearbyPlaces(lat, lng, radius, DEFAULT_RESULTS, extraParams);
}
@Override
public List<Place> getNearbyPlacesRankedByDistance(double lat, double lng, int limit, Param... params) {
try {
String uri = buildUrl(METHOD_NEARBY_SEARCH, String.format(Locale.ENGLISH, "key=%s&location=%s,%s&rankby=distance",
apiKey, String.valueOf(lat), String.valueOf(lng)), params);
return getPlaces(uri, METHOD_NEARBY_SEARCH, limit);
} catch (Exception e) {
throw new GooglePlacesException(e);
}
}
@Override
public List<Place> getNearbyPlacesRankedByDistance(double lat, double lng, Param... params) {
return getNearbyPlacesRankedByDistance(lat, lng, DEFAULT_RESULTS, params);
}
@Override
public List<Place> getPlacesByQuery(String query, int limit, Param... extraParams) {
try {
String uri = buildUrl(METHOD_TEXT_SEARCH, String.format("query=%s&key=%s", query, apiKey),
extraParams);
return getPlaces(uri, METHOD_TEXT_SEARCH, limit);
} catch (Exception e) {
throw new GooglePlacesException(e);
}
}
@Override
public List<Place> getPlacesByQuery(String query, Param... extraParams) {
return getPlacesByQuery(query, DEFAULT_RESULTS, extraParams);
}
@Override
public Place getPlaceById(String placeId, Param... extraParams) {
try {
String uri = buildUrl(METHOD_DETAILS, String.format("key=%s&placeid=%s", apiKey, placeId), extraParams);
return Place.parseDetails(this, requestHandler.get(uri));
} catch (Exception e) {
throw new GooglePlacesException(e);
}
}
@Override
public Place addPlace(PlaceBuilder builder, boolean returnPlace, Param... extraParams) {
try {
String uri = buildUrl(METHOD_ADD, String.format("key=%s", apiKey));
JSONObject input = builder.toJson();
HttpPost post = new HttpPost(uri);
post.setEntity(new StringEntity(input.toString()));
JSONObject response = new JSONObject(requestHandler.post(post));
String status = response.getString(STRING_STATUS);
checkStatus(status, response.optString(STRING_ERROR_MESSAGE));
return returnPlace ? getPlaceById(response.getString(STRING_PLACE_ID)) : null;
} catch (Exception e) {
throw new GooglePlacesException(e);
}
}
@Override
public void deletePlaceById(String placeId, Param... extraParams) {
try {
String uri = buildUrl(METHOD_DELETE, String.format("key=%s", apiKey), extraParams);
JSONObject input = new JSONObject().put(STRING_PLACE_ID, placeId);
HttpPost post = new HttpPost(uri);
post.setEntity(new StringEntity(input.toString()));
JSONObject response = new JSONObject(requestHandler.post(post));
String status = response.getString(STRING_STATUS);
checkStatus(status, response.optString(STRING_ERROR_MESSAGE));
} catch (Exception e) {
throw new GooglePlacesException(e);
}
}
@Override
public void deletePlace(Place place, Param... extraParams) {
deletePlaceById(place.getPlaceId(), extraParams);
}
protected InputStream download(String uri) {
try {
InputStream in = requestHandler.getInputStream(uri);
if (in == null)
throw new GooglePlacesException("Could not attain input stream at " + uri);
debug("Successfully attained InputStream at " + uri);
return in;
} catch (Exception e) {
throw new GooglePlacesException(e);
}
}
protected InputStream downloadPhoto(Photo photo, int maxWidth, int maxHeight, Param... extraParams) {
try {
String uri = String.format("%sphoto?photoreference=%s&key=%s", API_URL, photo.getReference(),
apiKey);
List<Param> params = new ArrayList<>(Arrays.asList(extraParams));
if (maxHeight != -1) params.add(Param.name("maxheight").value(maxHeight));
if (maxWidth != -1) params.add(Param.name("maxwidth").value(maxWidth));
extraParams = params.toArray(new Param[params.size()]);
uri = addExtraParams(uri, extraParams);
return download(uri);
} catch (Exception e) {
throw new GooglePlacesException(e);
}
}
private List<Prediction> getPredictions(String input, String method, Param... extraParams) {
try {
String uri = buildUrl(method, String.format("input=%s&key=%s", input, apiKey),
extraParams);
String response = requestHandler.get(uri);
return Prediction.parse(this, response);
} catch (Exception e) {
throw new GooglePlacesException(e);
}
}
@Override
public List<Prediction> getPlacePredictions(String input, int offset, int lat, int lng, int radius,
Param... extraParams) {
List<Param> params = new ArrayList<>();
if (offset != -1)
params.add(Param.name("offset").value(offset));
if (lat != -1 && lng != -1)
params.add(Param.name("location").value(lat + "," + lng));
params.addAll(new ArrayList<>(Arrays.asList(extraParams)));
return getPredictions(input, METHOD_AUTOCOMPLETE, params.toArray(new Param[params.size()]));
}
@Override
public List<Prediction> getPlacePredictions(String input, int offset, Param... extraParams) {
return getPlacePredictions(input, offset, -1, -1, -1, extraParams);
}
@Override
public List<Prediction> getPlacePredictions(String input, Param... extraParams) {
return getPlacePredictions(input, -1, extraParams);
}
@Override
public List<Prediction> getQueryPredictions(String input, int offset, int lat, int lng, int radius,
Param... extraParams) {
List<Param> params = new ArrayList<>();
if (offset != -1)
params.add(Param.name("offset").value(offset));
if (lat == -1 && lng == -1)
params.add(Param.name("location").value(lat + "," + lng));
params.addAll(new ArrayList<>(Arrays.asList(extraParams)));
return getPredictions(input, METHOD_QUERY_AUTOCOMPLETE, params.toArray(new Param[params.size()]));
}
@Override
public List<Prediction> getQueryPredictions(String input, int offset, Param... extraParams) {
return getQueryPredictions(input, offset, -1, -1, -1, extraParams);
}
@Override
public List<Prediction> getQueryPredictions(String input, Param... extraParams) {
return getQueryPredictions(input, -1, extraParams);
}
private List<Place> getPlaces(String uri, String method, int limit) throws IOException {
limit = Math.min(limit, MAXIMUM_RESULTS); // max of 60 results possible
int pages = (int) Math.ceil(limit / (double) MAXIMUM_PAGE_RESULTS);
List<Place> places = new ArrayList<>();
// new request for each page
for (int i = 0; i < pages; i++) {
debug("Page: " + (i + 1));
String raw = requestHandler.get(uri);
debug(raw);
String nextPage = parse(this, places, raw, limit);
// reduce the limit, update the uri and wait for token, but only if there are more pages to read
if (nextPage != null && i < pages - 1) {
limit -= MAXIMUM_PAGE_RESULTS;
uri = String.format("%s%s/json?pagetoken=%s&key=%s",
API_URL, method, nextPage, apiKey);
sleep(3000); // Page tokens have a delay before they are available
} else {
break;
}
}
return places;
}
private void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (Exception e) {
e.printStackTrace();
}
}
}