-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGooglePlacesAPI.java
More file actions
49 lines (39 loc) · 1.76 KB
/
GooglePlacesAPI.java
File metadata and controls
49 lines (39 loc) · 1.76 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
package Rent_Rover;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public class GooglePlacesAPI {
private static final String API_KEY = "AIzaSyDT3s6SpAPFBAt48Ve03YjUIhmdr9NGd5E"; // put your key in quotes
public static List<String> getSuggestions(String input) {
List<String> suggestions = new ArrayList<>();
try {
String encodedInput = URLEncoder.encode(input, "UTF-8");
String urlStr = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input="
+ encodedInput + "&key=" + API_KEY;
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = in.readLine()) != null) response.append(line);
in.close();
JSONObject json = new JSONObject(response.toString());
// Check if API returned error
if (!json.getString("status").equals("OK")) return suggestions;
JSONArray predictions = json.getJSONArray("predictions");
for (int i = 0; i < predictions.length(); i++) {
suggestions.add(predictions.getJSONObject(i).getString("description"));
}
} catch (Exception e) {
e.printStackTrace();
}
return suggestions;
}
}