Skip to content

Commit

Permalink
v3.1.2 'grpc failed' error on Android
Browse files Browse the repository at this point in the history
  • Loading branch information
Sebastian Baar committed Jul 10, 2018
1 parent 0159152 commit e6b78b3
Show file tree
Hide file tree
Showing 5 changed files with 120 additions and 71 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
# 3.1.2 (2018-07-10)

- Better handle 'grpc failed' error on Android (#21)
- add "No Internet Access" error if grpc failed because of no Internet connection
- add "android.permission.ACCESS_NETWORK_STATE" permission
- update README
- refactoring...

# 3.1.1 (2018-02-27)

refactoring...
Expand Down
114 changes: 65 additions & 49 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,82 +18,98 @@ You can also configure the following variable to customize the iOS location plis

## Supported Platforms
- iOS
- Android (works only on native devices)
- Android

## Methods
- nativegeocoder.reverseGeocode
- nativegeocoder.forwardGeocode
## API
- [.reverseGeocode(success, error, latitude, longitude, options)]()
- [.forwardGeocode(success, error, addressString, options)]()

## nativegeocoder.reverseGeocode
## .reverseGeocode(successCallback, errorCallback, latitude, longitude, options);
Reverse geocode a given latitude and longitude to find location address.

nativegeocoder.reverseGeocode(successCallback, errorCallback, latitude, longitude, options);

### Parameters
- __latitude__: The latitude. (Double)
- __longitude__: The longtitude. (Double)
- __options__: The Options

```
{
useLocale: boolean (default: true) (works only for Android and iOS 11.0+)
defaultLocale: string (e.g.: 'fa-IR' or 'de_DE'; works only for Android and iOS 11.0+)
maxResults: number (default: 1) (min-max: 1-5)
}
```

### Result Object (Array)
https://developer.apple.com/documentation/corelocation/clplacemark
https://developer.android.com/reference/android/location/Address.html

- countryCode
- postalCode
- administrativeArea
- subAdministrativeArea
- locality
- subLocality
- thoroughfare
- subThoroughfare
| Parameter | Type | Default | Description |
| ---------------- | ---------- | ------- | ------------------------------------------------------------- |
| `success` | `Function` | | Success callback (with Array<Result>) |
| `error` | `Function` | | Error callback. |
| `latitude` | `Number` | | The latitude. |
| `longitude` | `Number` | | The longtitude. |
| `options` | `Object` | | Optional. Is called when the api encounters an error while initializing the context. |

All available `options` attributes:

| Attribute | Type | Default | Comment |
| ------------------------------ | -------- | ------------------------------------------------------------ | -------------------------------------------------- |
| `useLocale` | `Boolean` | true | Optional. Only works for Android and iOS 11.0+. |
| `defaultLocale` | `String` | | Optional. E.g.: 'fa-IR' or 'de_DE'; works only for Android and iOS 11.0+. |
| `maxResults` | `Number` | 1 | Optional. Min value: 1, max value: 5. |

### Array<Result>
Conforms to [Apple's](https://developer.apple.com/documentation/corelocation/clplacemark) and [Android's](https://developer.android.com/reference/android/location/Address.html) reverse geocoder's result arrays.

| Value | Type |
|-------------|-----------
| `countryCode` | `String` |
| `postalCode` | `String` |
| `administrativeArea` | `String` |
| `subAdministrativeArea` | `String` |
| `locality` | `String` |
| `subLocality` | `String` |
| `thoroughfare` | `String` |
| `subThoroughfare` | `String` |

### Example
```js
nativegeocoder.reverseGeocode(success, failure, 52.5072095, 13.1452818, { useLocale: true, maxResults: 1 });

function success(result) {
alert("The address is: \n\n" + JSON.stringify(result[0]));
var firstResult = result[0];
console.log("First Result: " + JSON.stringify(firstResult));
}

function failure(err) {
alert(JSON.stringify(err));
console.log(err);
}
```

## nativegeocoder.forwardGeocode
## .forwardGeocode(success, error, addressString, options)
Forward geocode a given address to find coordinates.

nativegeocoder.forwardGeocode(successCallback, errorCallback, addressString, options);

### Parameters
- __addressString__: The address to be geocoded. (String)
- __options__: The Options.

```
{
useLocale: boolean (default: true) (works only for Android and iOS 11.0+)
defaultLocale: string (e.g.: 'fa-IR' or 'de_DE'; works only for Android and iOS 11.0+)
maxResults: number (default: 1) (min-max: 1-5)
}
```
| Parameter | Type | Default | Description |
| ---------------- | ---------- | ------- | ------------------------------------------------------------- |
| `success` | `Function` | | Success callback (with Array<Result>) |
| `error` | `Function` | | Error callback. |
| `addressString` | `String` | | The address to be geocoded. |
| `options` | `Object` | | Optional. Is called when the api encounters an error while initializing the context. |

All available `options` attributes:

| Attribute | Type | Default | Comment |
| ------------------------------ | -------- | ------------------------------------------------------------ | -------------------------------------------------- |
| `useLocale` | `Boolean` | true | Optional. Only works for Android and iOS 11.0+. |
| `defaultLocale` | `String` | | Optional. E.g.: 'fa-IR' or 'de_DE'; works only for Android and iOS 11.0+. |
| `maxResults` | `Number` | 1 | Optional. Min value: 1, max value: 5. |

### Array<Result>
| Value | Type |
|-------------|-----------
| `latitude` | `String` |
| `longitude` | `String` |

### Result Object (Array)
- latitude
- longitude

### Example
```js
nativegeocoder.forwardGeocode(success, failure, "Berlin", { useLocale: true, maxResults: 1 });

function success(coordinates) {
alert("The coordinates are latitude = " + coordinates[0].latitude + " and longitude = " + coordinates[0].longitude);
var firstResult = coordinates[0];
console.log("The coordinates are latitude = " + firstResult.latitude + " and longitude = " + firstResult.longitude);
}

function failure(err) {
alert(JSON.stringify(err));
console.log(err);
}
```
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "cordova-plugin-nativegeocoder",
"version": "3.1.1",
"version": "3.1.2",
"description": "Cordova plugin for native forward and reverse geocoding",
"cordova": {
"id": "cordova-plugin-nativegeocoder",
Expand All @@ -16,7 +16,10 @@
"keywords": [
"ecosystem:cordova",
"cordova-android",
"cordova-ios"
"cordova-ios",
"geocoder",
"geocoding",
"location"
],
"author": "Sebastian Baar",
"license": "MIT",
Expand Down
5 changes: 3 additions & 2 deletions plugin.xml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<plugin id="cordova-plugin-nativegeocoder" version="3.1.1" xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
<plugin id="cordova-plugin-nativegeocoder" version="3.1.2" xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
<name>NativeGeocoder</name>
<description>Cordova plugin for native forward and reverse geocoding</description>
<license>MIT</license>
<keywords>cordova,geocoding,reverse,forward</keywords>
<keywords>cordova,geocoder,geocoding,reverse,forward,location</keywords>

<js-module name="NativeGeocoder" src="www/NativeGeocoder.js">
<clobbers target="nativegeocoder" />
Expand All @@ -19,6 +19,7 @@

<config-file parent="/*" target="AndroidManifest.xml">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</config-file>

<source-file src="src/android/NativeGeocoder.java" target-dir="src/cordova/plugin/nativegeocoder" />
Expand Down
57 changes: 39 additions & 18 deletions src/android/NativeGeocoder.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package cordova.plugin.nativegeocoder;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
Expand All @@ -21,7 +24,6 @@ class NativeGeocoderOptions {
}

public class NativeGeocoder extends CordovaPlugin {
private static int MAX_RESULTS_COUNT = 5;
private Geocoder geocoder;

@Override
Expand Down Expand Up @@ -64,10 +66,10 @@ public boolean execute(String action, JSONArray args, CallbackContext callbackCo

/**
* Reverse geocode a given latitude and longitude to find location address
* @param latitude
* @param longitude
* @param options
* @param callbackContext
* @param latitude double
* @param longitude double
* @param options JSONObject
* @param callbackContext CallbackContext
*/
private void reverseGeocode(double latitude, double longitude, JSONObject options, CallbackContext callbackContext) throws JSONException{

Expand Down Expand Up @@ -117,17 +119,21 @@ private void reverseGeocode(double latitude, double longitude, JSONObject option
}
}
catch (Exception e) {
PluginResult r = new PluginResult(PluginResult.Status.ERROR, "Geocoder:getFromLocation Error: " + e.getMessage());
String errorMsg = e.getMessage();
if (e.getMessage().equals("grpc failed") && !isNetworkAvailable()) {
errorMsg = "No Internet Access";
}
PluginResult r = new PluginResult(PluginResult.Status.ERROR, "Geocoder:getFromLocationName Error: " + errorMsg);
callbackContext.sendPluginResult(r);
}
}


/**
* Forward geocode a given address to find coordinates
* @param addressString
* @param options
* @param callbackContext
* @param addressString String
* @param options JSONObject
* @param callbackContext CallbackContext
*/
private void forwardGeocode(String addressString, JSONObject options, CallbackContext callbackContext) throws JSONException {
if (addressString == null || addressString.length() == 0) {
Expand Down Expand Up @@ -184,25 +190,39 @@ private void forwardGeocode(String addressString, JSONObject options, CallbackCo
}
}
catch (Exception e) {
PluginResult r = new PluginResult(PluginResult.Status.ERROR, "Geocoder:getFromLocationName Error: " +e.getMessage());
String errorMsg = e.getMessage();
if (e.getMessage().equals("grpc failed") && !isNetworkAvailable()) {
errorMsg = "No Internet Access";
}
PluginResult r = new PluginResult(PluginResult.Status.ERROR, "Geocoder:getFromLocationName Error: " + errorMsg);
callbackContext.sendPluginResult(r);
}
}

/**
* Get network connection
* @return boolean
*/
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) cordova.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = null;
if (connectivityManager != null) {
activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
}
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

/**
* Get a valid NativeGeocoderOptions object
* @param options
* @param options JSONObject
* @return NativeGeocoderOptions
*/
private NativeGeocoderOptions getNativeGeocoderOptions(JSONObject options) throws JSONException {
NativeGeocoderOptions geocoderOptions = new NativeGeocoderOptions();

if (options != null) {
if (options.has("useLocale")) {
geocoderOptions.useLocale = options.getBoolean("useLocale");
} else {
geocoderOptions.useLocale = true;
}
geocoderOptions.useLocale = !options.has("useLocale") || options.getBoolean("useLocale");
if (options.has("defaultLocale")) {
geocoderOptions.defaultLocale = options.getString("defaultLocale");
} else {
Expand All @@ -212,6 +232,7 @@ private NativeGeocoderOptions getNativeGeocoderOptions(JSONObject options) throw
geocoderOptions.maxResults = options.getInt("maxResults");

if (geocoderOptions.maxResults > 0) {
int MAX_RESULTS_COUNT = 5;
geocoderOptions.maxResults = geocoderOptions.maxResults > MAX_RESULTS_COUNT ? MAX_RESULTS_COUNT : geocoderOptions.maxResults;
} else {
geocoderOptions.maxResults = 1;
Expand All @@ -231,7 +252,7 @@ private NativeGeocoderOptions getNativeGeocoderOptions(JSONObject options) throw

/**
* Create a Geocoder with NativeGeocoderOptions
* @param geocoderOptions
* @param geocoderOptions NativeGeocoderOptions
* @return Geocoder
*/
private Geocoder createGeocoderWithOptions(NativeGeocoderOptions geocoderOptions) {
Expand All @@ -241,7 +262,7 @@ private Geocoder createGeocoderWithOptions(NativeGeocoderOptions geocoderOptions
locale = Locale.forLanguageTag(geocoderOptions.defaultLocale);
} else {
locale = Locale.ENGLISH;
String parts[] = geocoderOptions.defaultLocale.split("-|_", -1);
String parts[] = geocoderOptions.defaultLocale.split("[-_]", -1);
if (parts.length == 1)
locale = new Locale(parts[0]);
else if (parts.length == 2 || (parts.length == 3 && parts[2].startsWith("#")))
Expand Down

0 comments on commit e6b78b3

Please sign in to comment.