Невозможно создать объект HERE SDK до инициализации MapEngine. Смотрите MapEngine.init () - PullRequest
0 голосов
/ 04 апреля 2019

Я получаю ошибку com.here.android.mpa.common.UnintializedMapEngineException.Это означает:

Невозможно создать объект HERE SDK до инициализации MapEngine.См. MapEngine.init ()

Код был взят из собственного примера Here Maps на GitHub .

В моей MainActivity я звоню geoCodeAddress("some address"), чтокогда выдается ошибка.

Я использую HERE SDK Версия: 3.11.2.82

Может кто-нибудь увидеть, что я могу делать неправильно?

Манифест

    <meta-data
        android:name="com.here.android.maps.appid"
        android:value="MyAppIdHere" />
    <meta-data
        android:name="com.here.android.maps.apptoken"
        android:value="MyAppTokenHere" />
    <meta-data
        android:name="com.here.android.maps.license.key"
        android:value="MyKeyHere" />
    <meta-data
        android:name="INTENT_NAME"
        android:value="HereMappingIntent" />

    <service
        android:name="com.here.android.mpa.service.MapService"
        android:exported="false"
        android:label="HereMapping">
        <intent-filter>
            <action android:name="HereMappingIntent"></action>
        </intent-filter>
    </service>

HereGeocoder.java

public class HereGeoCoder {
    private String                TAG = getClass().getSimpleName();
    private IHereGeoCoderListener mListener;
    private AppCompatActivity     mActivity;

    public HereGeoCoder(AppCompatActivity activity, IHereGeoCoderListener listener) {
        this.mActivity = activity;
        this.mListener = listener;
        initMapEngine();
    }

    private void initMapEngine() {
        String diskCacheRoot = Environment.getExternalStorageDirectory().getPath() + File.separator + ".isolated-here-maps";
        String intentName = "";
        try {
            ApplicationInfo ai     = mActivity.getPackageManager().getApplicationInfo(mActivity.getPackageName(), PackageManager.GET_META_DATA);
            Bundle          bundle = ai.metaData;
            intentName = bundle.getString("INTENT_NAME");
        }
        catch (PackageManager.NameNotFoundException e) {
            Log.e(this.getClass().toString(), "Failed to find intent name, NameNotFound: " + e.getMessage());
        }

        boolean success = com.here.android.mpa.common.MapSettings.setIsolatedDiskCacheRootPath(diskCacheRoot, intentName);
        if (!success) {

        } else {

            MapEngine.getInstance().init(new ApplicationContext(mActivity), new OnEngineInitListener() {
                @Override
                public void onEngineInitializationCompleted(Error error) {
                //Here is 
                    Log.e(TAG, "Map Engine initialized with error code: " + error);
                    Toast.makeText(mActivity, "Map Engine initialized with error code:" + error, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    public void getCoordinatesForAddress(String address) {
        GeocodeRequest geocodeRequest = new GeocodeRequest(address);
        geocodeRequest.execute(new ResultListener<List<GeocodeResult>>() {
            @Override
            public void onCompleted(List<GeocodeResult> results, ErrorCode errorCode) {
                if (errorCode == ErrorCode.NONE) {
                    if (results.size() > 0) {
                        HashMap<String, Double> coords = new HashMap<>();
                        GeocodeResult           result = results.get(0);
                        coords.put("Latitude", result.getLocation().getCoordinate().getLatitude());
                        coords.put("Longitude", result.getLocation().getCoordinate().getLongitude());
                        if (mListener != null) {
                            mListener.onDidDecodeAddress(coords);
                        }
                    } 
                } 
            }
        });
    }
}

---- ОБНОВЛЕНО

IHereGeoCoderListener.java

public interface IHereGeoCoderListener {
    void onDidDecodeAddress(HashMap<String, Double> coordinates);

    void onDidDecodeCoordiantes(String address);
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private String   TAG = getClass().getSimpleName();

    private final static int      REQUEST_CODE_ASK_PERMISSIONS = 1;
    private static final String[] RUNTIME_PERMISSIONS          = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_NETWORK_STATE
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //PERMSSIONS
        if (!hasPermissions(this, RUNTIME_PERMISSIONS)) {
            ActivityCompat.requestPermissions(this, RUNTIME_PERMISSIONS, REQUEST_CODE_ASK_PERMISSIONS);
        }

        geoCodeAddress("1 Broad St, Chattanooga, TN 37402");

    }


    //PERMISSIONS
    private static boolean hasPermissions(Context context, String... permissions) {
        if (permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_PERMISSIONS: {
                for (int index = 0; index < permissions.length; index++) {
                    if (grantResults[index] != PackageManager.PERMISSION_GRANTED) {

                        /*
                         * If the user turned down the permission request in the past and chose the
                         * Don't ask again option in the permission request system dialog.
                         */
                        if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[index])) {
                            Toast.makeText(this, "Required permission " + permissions[index] + " not granted. Please go to settings and turn on for sample app",
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(this, "Required permission " + permissions[index] + " not granted", Toast.LENGTH_LONG).show();
                        }
                    }
                }
                break;
            }
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    // GEOCODER
    private void geoCodeAddress(String address) {
        if (hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            //GEOCODER
            HereGeoCoder geoCoder = new HereGeoCoder(this, new IHereGeoCoderListener() {
                @Override
                public void onDidDecodeAddress(HashMap<String, Double> coordinates) {
                    for (HashMap.Entry<String, Double> entry : coordinates.entrySet()) {
                         Log.i(TAG, String.format("%s,%s", entry.getKey(), entry.getValue()));
                    }
                }

                @Override
                public void onDidDecodeCoordiantes(String address) {
                    Log.i(TAG, "onDidDecodeCoordinates: " + address);
                }
            });

            geoCoder.getCoordinatesForAddress(address);
        } else {
            Toast.makeText(this, "You do not have the correct permissions set.", Toast.LENGTH_LONG).show();
        }
    }

}

1 Ответ

1 голос
/ 08 апреля 2019

Проблема в том, что вы пытаетесь выполнить запрос геокодирования до полной инициализации движка карты. Я адаптировал ваш код с исправлением: HereGeoCoder.java

    public class HereGeoCoder {
    private String                TAG = getClass().getSimpleName();
    private IHereGeoCoderListener mListener;
    private AppCompatActivity     mActivity;
    private String                mAddress;

    public HereGeoCoder(AppCompatActivity activity, String address, IHereGeoCoderListener listener) {
        this.mActivity = activity;
        this.mListener = listener;
        this.mAddress = address;
        initMapEngine();
    }

    private void initMapEngine() {
        String diskCacheRoot = Environment.getExternalStorageDirectory().getPath() + File.separator + ".isolated-here-maps";
        String intentName = "";
        try {
            ApplicationInfo ai     = mActivity.getPackageManager().getApplicationInfo(mActivity.getPackageName(), PackageManager.GET_META_DATA);
            Bundle          bundle = ai.metaData;
            intentName = bundle.getString("INTENT_NAME");
        }
        catch (PackageManager.NameNotFoundException e) {
            Log.e(this.getClass().toString(), "Failed to find intent name, NameNotFound: " + e.getMessage());
        }

        boolean success = com.here.android.mpa.common.MapSettings.setIsolatedDiskCacheRootPath(diskCacheRoot, intentName);
        if (!success) {

        } else {

            MapEngine.getInstance().init(new ApplicationContext(mActivity), new OnEngineInitListener() {
                @Override
                public void onEngineInitializationCompleted(Error error) {
                //Here is 
                    Log.e(TAG, "Map Engine initialized with error code: " + error);
                    Toast.makeText(mActivity, "Map Engine initialized with error code:" + error, Toast.LENGTH_SHORT).show();

                   if (error == Error.NONE) {
                      getCoordinatesForAddress(mAddress);
                   }
                }
            });
        }
    }

    private void getCoordinatesForAddress(String address) {
        GeocodeRequest geocodeRequest = new GeocodeRequest(address);
        geocodeRequest.execute(new ResultListener<List<GeocodeResult>>() {
            @Override
            public void onCompleted(List<GeocodeResult> results, ErrorCode errorCode) {
                if (errorCode == ErrorCode.NONE) {
                    if (results.size() > 0) {
                        HashMap<String, Double> coords = new HashMap<>();
                        GeocodeResult           result = results.get(0);
                        coords.put("Latitude", result.getLocation().getCoordinate().getLatitude());
                        coords.put("Longitude", result.getLocation().getCoordinate().getLongitude());
                        if (mListener != null) {
                            mListener.onDidDecodeAddress(coords);
                        }
                    } 
                } 
            }
        });
    }
}

Функция geoCodeAddress в MainActivity:

// GEOCODER
    private void geoCodeAddress(String address) {
        if (hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            //GEOCODER
            HereGeoCoder geoCoder = new HereGeoCoder(this, address, new IHereGeoCoderListener() {
                @Override
                public void onDidDecodeAddress(HashMap<String, Double> coordinates) {
                    for (HashMap.Entry<String, Double> entry : coordinates.entrySet()) {
                         Log.i(TAG, String.format("%s,%s", entry.getKey(), entry.getValue()));
                    }
                }

                @Override
                public void onDidDecodeCoordiantes(String address) {
                    Log.i(TAG, "onDidDecodeCoordinates: " + address);
                }
            });

            //geoCoder.getCoordinatesForAddress(address);
        } else {
            Toast.makeText(this, "You do not have the correct permissions set.", Toast.LENGTH_LONG).show();
        }
    }
...