AVEbrahimi
AVEbrahimi

Reputation: 19164

First run of android app having Google Maps, without internet

When my users run my app having google maps and they don't have internet, OnMapReady is called, but I can't put markers or load overlays. How can I detect if GoogleMaps confirmed my APIKEY and it's ready for putting overlays and markers before user reaches internet? Currently it displays a blank screen which is not a good experience for new users. I want to detect that map tiles can't be loaded right now and alert user about connecting to internet.

Upvotes: 2

Views: 175

Answers (1)

Andrii Omelchenko
Andrii Omelchenko

Reputation: 13343

At first, it's impossible to use API_KEY-protected parts of Google Maps before user reaches Internet because API_KEY need to be checked on Google side. But you can use that for your task: try (before your actions with map) to execute Google Maps API URL which requires API_KEY (e.g. Directions API URL):

https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key=YOUR_API_KEY

...
URL url = new URL(buildDirectionsUrl("https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key=YOUR_API_KEY");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

int responseCode = connection.getResponseCode();
InputStream stream = connection.getInputStream();

reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder jsonStringBuilder = new StringBuilder();

StringBuffer buffer = new StringBuffer();
String line = "";

while ((line = reader.readLine()) != null) {
    buffer.append(line+"\n");
    jsonStringBuilder.append(line);
    jsonStringBuilder.append("\n");
}

JSONObject jsonRoot = new JSONObject(jsonStringBuilder.toString());
...

than get and analyze response (jsonRoot): if there is no response at certain time - there is no Internet connection or Google URL not reachable; if Google returns error, you can parse "error_message" (e.g. "Keyless access to Google Maps Platform is deprecated...") etc.

Upvotes: 1

Related Questions