Merge remote-tracking branch 'origin/master'

This commit is contained in:
Vitaliy 2021-01-11 11:43:39 +02:00
commit 10711788df
14 changed files with 394 additions and 270 deletions

View file

@ -14,10 +14,11 @@
android:orientation="horizontal"> android:orientation="horizontal">
<LinearLayout <LinearLayout
android:id="@+id/main_item_part" android:id="@+id/basic_item_body"
android:layout_width="0dp" android:layout_width="0dp"
android:layout_height="match_parent" android:layout_height="match_parent"
android:layout_gravity="center_vertical" android:layout_gravity="center_vertical"
android:background="?attr/selectableItemBackground"
android:paddingLeft="@dimen/content_padding" android:paddingLeft="@dimen/content_padding"
android:paddingStart="@dimen/content_padding" android:paddingStart="@dimen/content_padding"
android:paddingRight="0dp" android:paddingRight="0dp"
@ -79,22 +80,24 @@
<View <View
android:layout_width="1dp" android:layout_width="1dp"
android:layout_height="36dp" android:layout_height="wrap_content"
android:layout_marginTop="@dimen/content_padding"
android:layout_marginBottom="@dimen/content_padding"
android:background="?attr/divider_color_basic"/> android:background="?attr/divider_color_basic"/>
<LinearLayout <LinearLayout
android:id="@+id/eng_button" android:id="@+id/end_button"
android:paddingLeft="@dimen/content_padding" android:paddingLeft="@dimen/content_padding"
android:paddingRight="@dimen/content_padding" android:paddingRight="@dimen/content_padding"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="match_parent"> android:layout_height="match_parent">
<androidx.appcompat.widget.AppCompatImageView <androidx.appcompat.widget.AppCompatImageView
android:id="@+id/end_button_icon"
android:layout_width="@dimen/standard_icon_size" android:layout_width="@dimen/standard_icon_size"
android:layout_height="@dimen/standard_icon_size" android:layout_height="@dimen/standard_icon_size"
android:layout_gravity="center_vertical" android:layout_gravity="center_vertical"
app:srcCompat="@drawable/ic_action_settings" app:srcCompat="@drawable/ic_action_settings" />
android:tint="?attr/default_icon_color" />
</LinearLayout> </LinearLayout>

View file

@ -63,8 +63,8 @@ import net.osmand.plus.measurementtool.MeasurementToolFragment;
import net.osmand.plus.measurementtool.StartPlanRouteBottomSheet; import net.osmand.plus.measurementtool.StartPlanRouteBottomSheet;
import net.osmand.plus.monitoring.OsmandMonitoringPlugin; import net.osmand.plus.monitoring.OsmandMonitoringPlugin;
import net.osmand.plus.osmedit.dialogs.DismissRouteBottomSheetFragment; import net.osmand.plus.osmedit.dialogs.DismissRouteBottomSheetFragment;
import net.osmand.plus.profiles.ProfileDataObject;
import net.osmand.plus.profiles.ProfileDataUtils; import net.osmand.plus.profiles.ProfileDataUtils;
import net.osmand.plus.profiles.RoutingProfileDataObject;
import net.osmand.plus.routepreparationmenu.MapRouteInfoMenu; import net.osmand.plus.routepreparationmenu.MapRouteInfoMenu;
import net.osmand.plus.routepreparationmenu.WaypointsFragment; import net.osmand.plus.routepreparationmenu.WaypointsFragment;
import net.osmand.plus.routing.RouteProvider.GPXRouteParamsBuilder; import net.osmand.plus.routing.RouteProvider.GPXRouteParamsBuilder;
@ -737,7 +737,7 @@ public class MapActivityActions implements DialogProvider {
String modeDescription; String modeDescription;
Map<String, RoutingProfileDataObject> profilesObjects = ProfileDataUtils.getRoutingProfiles(app); Map<String, ProfileDataObject> profilesObjects = ProfileDataUtils.getRoutingProfiles(app);
for (final ApplicationMode appMode : activeModes) { for (final ApplicationMode appMode : activeModes) {
if (appMode.isCustomProfile()) { if (appMode.isCustomProfile()) {
modeDescription = getProfileDescription(app, appMode, profilesObjects, getString(R.string.profile_type_user_string)); modeDescription = getProfileDescription(app, appMode, profilesObjects, getString(R.string.profile_type_user_string));
@ -1046,7 +1046,7 @@ public class MapActivityActions implements DialogProvider {
//switch profile button //switch profile button
ApplicationMode currentMode = app.getSettings().APPLICATION_MODE.get(); ApplicationMode currentMode = app.getSettings().APPLICATION_MODE.get();
String modeDescription; String modeDescription;
Map<String, RoutingProfileDataObject> profilesObjects = ProfileDataUtils.getRoutingProfiles(app); Map<String, ProfileDataObject> profilesObjects = ProfileDataUtils.getRoutingProfiles(app);
if (currentMode.isCustomProfile()) { if (currentMode.isCustomProfile()) {
modeDescription = getProfileDescription(app, currentMode, profilesObjects, getString(R.string.profile_type_user_string)); modeDescription = getProfileDescription(app, currentMode, profilesObjects, getString(R.string.profile_type_user_string));
} else { } else {
@ -1087,12 +1087,12 @@ public class MapActivityActions implements DialogProvider {
} }
private String getProfileDescription(OsmandApplication app, ApplicationMode mode, private String getProfileDescription(OsmandApplication app, ApplicationMode mode,
Map<String, RoutingProfileDataObject> profilesObjects, String defaultDescription) { Map<String, ProfileDataObject> profilesObjects, String defaultDescription) {
String description = defaultDescription; String description = defaultDescription;
String routingProfileKey = mode.getRoutingProfile(); String routingProfileKey = mode.getRoutingProfile();
if (!Algorithms.isEmpty(routingProfileKey)) { if (!Algorithms.isEmpty(routingProfileKey)) {
RoutingProfileDataObject profileDataObject = profilesObjects.get(routingProfileKey); ProfileDataObject profileDataObject = profilesObjects.get(routingProfileKey);
if (profileDataObject != null) { if (profileDataObject != null) {
description = String.format(app.getString(R.string.profile_type_descr_string), description = String.format(app.getString(R.string.profile_type_descr_string),
Algorithms.capitalizeFirstLetterAndLowercase(profileDataObject.getName())); Algorithms.capitalizeFirstLetterAndLowercase(profileDataObject.getName()));

View file

@ -0,0 +1,24 @@
package net.osmand.plus.onlinerouting;
public enum EngineType {
GRAPHHOPER("Graphhoper", "https://graphhopper.com/api/1/route"),
OSRM("OSRM", "https://router.project-osrm.org/route/v1/"),
ORS("Openroute Service", "https://api.openrouteservice.org/v2/directions/");
private String title;
private String standardUrl;
EngineType(String title, String standardUrl) {
this.title = title;
this.standardUrl = standardUrl;
}
public String getTitle() {
return title;
}
public String getStandardUrl() {
return standardUrl;
}
}

View file

@ -15,32 +15,32 @@ public class OnlineRoutingEngine {
public final static String ONLINE_ROUTING_ENGINE_PREFIX = "online_routing_engine_"; public final static String ONLINE_ROUTING_ENGINE_PREFIX = "online_routing_engine_";
public enum EngineParameterType { public enum EngineParameter {
CUSTOM_SERVER_URL,
CUSTOM_NAME, CUSTOM_NAME,
CUSTOM_URL,
API_KEY API_KEY
} }
private String stringKey; private String stringKey;
private ServerType serverType; private EngineType type;
private String vehicleKey; private String vehicleKey;
private Map<String, String> params = new HashMap<>(); private Map<String, String> params = new HashMap<>();
public OnlineRoutingEngine(@NonNull String stringKey, public OnlineRoutingEngine(@NonNull String stringKey,
@NonNull ServerType serverType, @NonNull EngineType type,
@NonNull String vehicleKey, @NonNull String vehicleKey,
@Nullable Map<String, String> params) { @Nullable Map<String, String> params) {
this(stringKey, serverType, vehicleKey); this(stringKey, type, vehicleKey);
if (!Algorithms.isEmpty(params)) { if (!Algorithms.isEmpty(params)) {
this.params.putAll(params); this.params.putAll(params);
} }
} }
public OnlineRoutingEngine(@NonNull String stringKey, public OnlineRoutingEngine(@NonNull String stringKey,
@NonNull ServerType serverType, @NonNull EngineType type,
@NonNull String vehicleKey) { @NonNull String vehicleKey) {
this.stringKey = stringKey; this.stringKey = stringKey;
this.serverType = serverType; this.type = type;
this.vehicleKey = vehicleKey; this.vehicleKey = vehicleKey;
} }
@ -48,8 +48,16 @@ public class OnlineRoutingEngine {
return stringKey; return stringKey;
} }
public ServerType getServerType() { public EngineType getType() {
return serverType; return type;
}
public String getBaseUrl() {
String customUrl = getParameter(EngineParameter.CUSTOM_URL);
if (Algorithms.isEmpty(customUrl)) {
return type.getStandardUrl();
}
return customUrl;
} }
public String getVehicleKey() { public String getVehicleKey() {
@ -60,25 +68,16 @@ public class OnlineRoutingEngine {
return params; return params;
} }
public String getBaseUrl() { public String getParameter(EngineParameter paramKey) {
String customServerUrl = getParameter(EngineParameterType.CUSTOM_SERVER_URL); return params.get(paramKey.name());
if (!Algorithms.isEmpty(customServerUrl)) {
return customServerUrl;
} else {
return serverType.getBaseUrl();
}
} }
public String getParameter(EngineParameterType paramType) { public void putParameter(EngineParameter paramKey, String paramValue) {
return params.get(paramType.name()); params.put(paramKey.name(), paramValue);
}
public void putParameter(EngineParameterType paramType, String paramValue) {
params.put(paramType.name(), paramValue);
} }
public String getName(@NonNull Context ctx) { public String getName(@NonNull Context ctx) {
String customName = getParameter(EngineParameterType.CUSTOM_NAME); String customName = getParameter(EngineParameter.CUSTOM_NAME);
if (customName != null) { if (customName != null) {
return customName; return customName;
} else { } else {
@ -87,21 +86,21 @@ public class OnlineRoutingEngine {
} }
private String getStandardName(@NonNull Context ctx) { private String getStandardName(@NonNull Context ctx) {
return getStandardName(ctx, serverType, vehicleKey); return getStandardName(ctx, type, vehicleKey);
} }
public static String getStandardName(@NonNull Context ctx, public static String getStandardName(@NonNull Context ctx,
@NonNull ServerType serverType, @NonNull EngineType type,
@NonNull String vehicleKey) { @NonNull String vehicleKey) {
String vehicleTitle = VehicleType.toHumanString(ctx, vehicleKey); String vehicleTitle = VehicleType.toHumanString(ctx, vehicleKey);
String pattern = ctx.getString(R.string.ltr_or_rtl_combine_via_dash); String pattern = ctx.getString(R.string.ltr_or_rtl_combine_via_dash);
return String.format(pattern, serverType.getTitle(), vehicleTitle); return String.format(pattern, type.getTitle(), vehicleTitle);
} }
public static OnlineRoutingEngine createNewEngine(@NonNull ServerType serverType, public static OnlineRoutingEngine createNewEngine(@NonNull EngineType type,
@NonNull String vehicleKey, @NonNull String vehicleKey,
@Nullable Map<String, String> params) { @Nullable Map<String, String> params) {
return new OnlineRoutingEngine(generateKey(), serverType, vehicleKey, params); return new OnlineRoutingEngine(generateKey(), type, vehicleKey, params);
} }
private static String generateKey() { private static String generateKey() {

View file

@ -30,7 +30,7 @@ import net.osmand.plus.activities.MapActivity;
import net.osmand.plus.base.BaseOsmAndFragment; import net.osmand.plus.base.BaseOsmAndFragment;
import net.osmand.plus.mapcontextmenu.other.HorizontalSelectionAdapter.HorizontalSelectionItem; import net.osmand.plus.mapcontextmenu.other.HorizontalSelectionAdapter.HorizontalSelectionItem;
import net.osmand.plus.onlinerouting.OnlineRoutingCard.OnTextChangedListener; import net.osmand.plus.onlinerouting.OnlineRoutingCard.OnTextChangedListener;
import net.osmand.plus.onlinerouting.OnlineRoutingEngine.EngineParameterType; import net.osmand.plus.onlinerouting.OnlineRoutingEngine.EngineParameter;
import net.osmand.plus.routepreparationmenu.cards.BaseCard; import net.osmand.plus.routepreparationmenu.cards.BaseCard;
import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.settings.backend.ApplicationMode;
import net.osmand.util.Algorithms; import net.osmand.util.Algorithms;
@ -62,7 +62,7 @@ public class OnlineRoutingEngineFragment extends BaseOsmAndFragment {
private View view; private View view;
private ViewGroup segmentsContainer; private ViewGroup segmentsContainer;
private OnlineRoutingCard nameCard; private OnlineRoutingCard nameCard;
private OnlineRoutingCard serverCard; private OnlineRoutingCard typeCard;
private OnlineRoutingCard vehicleCard; private OnlineRoutingCard vehicleCard;
private OnlineRoutingCard apiKeyCard; private OnlineRoutingCard apiKeyCard;
private OnlineRoutingCard exampleCard; private OnlineRoutingCard exampleCard;
@ -143,7 +143,7 @@ public class OnlineRoutingEngineFragment extends BaseOsmAndFragment {
setupToolbar((Toolbar) view.findViewById(R.id.toolbar)); setupToolbar((Toolbar) view.findViewById(R.id.toolbar));
setupNameCard(); setupNameCard();
setupServerCard(); setupTypeCard();
setupVehicleCard(); setupVehicleCard();
setupApiKeyCard(); setupApiKeyCard();
setupExampleCard(); setupExampleCard();
@ -152,7 +152,7 @@ public class OnlineRoutingEngineFragment extends BaseOsmAndFragment {
setupButtons(); setupButtons();
updateCardViews(nameCard, serverCard, vehicleCard, exampleCard); updateCardViews(nameCard, typeCard, vehicleCard, exampleCard);
return view; return view;
} }
@ -174,38 +174,39 @@ public class OnlineRoutingEngineFragment extends BaseOsmAndFragment {
segmentsContainer.addView(nameCard.getView()); segmentsContainer.addView(nameCard.getView());
} }
private void setupServerCard() { private void setupTypeCard() {
serverCard = new OnlineRoutingCard(mapActivity, isNightMode()); typeCard = new OnlineRoutingCard(mapActivity, isNightMode());
serverCard.build(mapActivity); typeCard.build(mapActivity);
serverCard.setHeaderTitle(getString(R.string.shared_string_type)); typeCard.setHeaderTitle(getString(R.string.shared_string_type));
List<HorizontalSelectionItem> serverItems = new ArrayList<>(); List<HorizontalSelectionItem> serverItems = new ArrayList<>();
for (ServerType server : ServerType.values()) { for (EngineType server : EngineType.values()) {
serverItems.add(new HorizontalSelectionItem(server.getTitle(), server)); serverItems.add(new HorizontalSelectionItem(server.getTitle(), server));
} }
serverCard.setSelectionMenu(serverItems, engine.serverType.getTitle(), typeCard.setSelectionMenu(serverItems, engine.type.getTitle(),
new CallbackWithObject<HorizontalSelectionItem>() { new CallbackWithObject<HorizontalSelectionItem>() {
@Override @Override
public boolean processResult(HorizontalSelectionItem result) { public boolean processResult(HorizontalSelectionItem result) {
ServerType server = (ServerType) result.getObject(); EngineType type = (EngineType) result.getObject();
if (engine.serverType != server) { if (engine.type != type) {
engine.serverType = server; engine.type = type;
updateCardViews(nameCard, serverCard, exampleCard); updateCardViews(nameCard, typeCard, exampleCard);
return true; return true;
} }
return false; return false;
} }
}); });
serverCard.setOnTextChangedListener(new OnTextChangedListener() { typeCard.setOnTextChangedListener(new OnTextChangedListener() {
@Override @Override
public void onTextChanged(boolean editedByUser, String text) { public void onTextChanged(boolean editedByUser, String text) {
if (editedByUser) { if (editedByUser) {
engine.customServerUrl = text; engine.customServerUrl = text;
updateCardViews(exampleCard);
} }
} }
}); });
serverCard.setFieldBoxLabelText(getString(R.string.shared_string_server_url)); typeCard.setFieldBoxLabelText(getString(R.string.shared_string_server_url));
serverCard.showDivider(); typeCard.showDivider();
segmentsContainer.addView(serverCard.getView()); segmentsContainer.addView(typeCard.getView());
} }
private void setupVehicleCard() { private void setupVehicleCard() {
@ -342,22 +343,28 @@ public class OnlineRoutingEngineFragment extends BaseOsmAndFragment {
for (BaseCard card : cardsToUpdate) { for (BaseCard card : cardsToUpdate) {
if (nameCard.equals(card)) { if (nameCard.equals(card)) {
if (Algorithms.isEmpty(engine.customName)) { if (Algorithms.isEmpty(engine.customName)) {
String name = OnlineRoutingEngine.getStandardName(app, engine.serverType, engine.getVehicleKey()); String name;
if (Algorithms.isEmpty(engine.getVehicleKey())) {
name = engine.type.getTitle();
} else {
name = OnlineRoutingEngine.getStandardName(app, engine.type, engine.getVehicleKey());
}
nameCard.setEditedText(name); nameCard.setEditedText(name);
} }
} else if (serverCard.equals(card)) { } else if (typeCard.equals(card)) {
serverCard.setHeaderSubtitle(engine.serverType.getTitle()); typeCard.setHeaderSubtitle(engine.type.getTitle());
serverCard.setEditedText(engine.getBaseUrl()); typeCard.setEditedText(engine.getBaseUrl());
if (engine.serverType == ServerType.GRAPHHOPER) { if (engine.type == EngineType.GRAPHHOPER || engine.type == EngineType.ORS) {
apiKeyCard.show(); apiKeyCard.show();
} else { } else {
apiKeyCard.hide(); apiKeyCard.hide();
} }
} else if (vehicleCard.equals(card)) { } else if (vehicleCard.equals(card)) {
vehicleCard.setHeaderSubtitle(engine.vehicleType.getTitle(app)); VehicleType vt = VehicleType.getVehicleByKey(engine.getVehicleKey());
if (engine.vehicleType == VehicleType.CUSTOM) { vehicleCard.setHeaderSubtitle(vt.getTitle(app));
if (vt == VehicleType.CUSTOM) {
vehicleCard.showFieldBox(); vehicleCard.showFieldBox();
vehicleCard.setEditedText(engine.getVehicleKey()); vehicleCard.setEditedText(engine.getVehicleKey());
} else { } else {
@ -400,15 +407,15 @@ public class OnlineRoutingEngineFragment extends BaseOsmAndFragment {
private void saveChanges() { private void saveChanges() {
OnlineRoutingEngine engineToSave; OnlineRoutingEngine engineToSave;
if (isEditingMode()) { if (isEditingMode()) {
engineToSave = new OnlineRoutingEngine(editedEngineKey, engine.serverType, engine.getVehicleKey()); engineToSave = new OnlineRoutingEngine(editedEngineKey, engine.type, engine.getVehicleKey());
} else { } else {
engineToSave = OnlineRoutingEngine.createNewEngine(engine.serverType, engine.getVehicleKey(), null); engineToSave = OnlineRoutingEngine.createNewEngine(engine.type, engine.getVehicleKey(), null);
} }
engineToSave.putParameter(EngineParameterType.CUSTOM_SERVER_URL, engine.customServerUrl); engineToSave.putParameter(EngineParameter.CUSTOM_NAME, engine.customName);
engineToSave.putParameter(EngineParameterType.CUSTOM_NAME, engine.customName); engineToSave.putParameter(EngineParameter.CUSTOM_URL, engine.customServerUrl);
if (engine.serverType == ServerType.GRAPHHOPER) { if (engine.type == EngineType.GRAPHHOPER || engine.type == EngineType.ORS) {
engineToSave.putParameter(EngineParameterType.API_KEY, engine.apiKey); engineToSave.putParameter(EngineParameter.API_KEY, engine.apiKey);
} }
helper.saveEngine(engineToSave); helper.saveEngine(engineToSave);
@ -419,30 +426,18 @@ public class OnlineRoutingEngineFragment extends BaseOsmAndFragment {
} }
private String getTestUrl() { private String getTestUrl() {
String baseUrl = engine.serverType.getBaseUrl(); List<LatLon> path = new ArrayList<>();
String vehicle = engine.getVehicleKey(); path.add(selectedLocation.getCityCenterLatLon());
path.add(selectedLocation.getCityAirportLatLon());
LatLon startPoint = selectedLocation.getCityCenterLatLon(); OnlineRoutingEngine tmpEngine =
LatLon endPoint = selectedLocation.getCityAirportLatLon(); OnlineRoutingEngine.createNewEngine(engine.type, engine.getVehicleKey(), null);
tmpEngine.putParameter(EngineParameter.CUSTOM_URL, engine.customServerUrl);
if (engine.serverType == ServerType.GRAPHHOPER) { tmpEngine.putParameter(EngineParameter.API_KEY, engine.apiKey);
return baseUrl + "?" + "point=" + startPoint.getLatitude() return helper.createFullUrl(tmpEngine, path);
+ "," + startPoint.getLongitude()
+ "&" + "point=" + endPoint.getLatitude()
+ "," + endPoint.getLongitude()
+ "&" + "vehicle=" + vehicle
+ (!Algorithms.isEmpty(engine.apiKey) ? ("&" + "key=" + engine.apiKey) : "");
} else {
return baseUrl + vehicle + "/" + startPoint.getLatitude()
+ "," + startPoint.getLongitude()
+ ";" + endPoint.getLatitude()
+ "," + endPoint.getLongitude()
+ "?" + "geometries=geojson";
}
} }
private void testEngineWork() { private void testEngineWork() {
final ServerType server = engine.serverType; final EngineType type = engine.type;
final ExampleLocation location = selectedLocation; final ExampleLocation location = selectedLocation;
AndroidNetworkUtils.sendRequestAsync(app, exampleCard.getEditedText(), null, AndroidNetworkUtils.sendRequestAsync(app, exampleCard.getEditedText(), null,
null, false, false, new OnRequestResultListener() { null, false, false, new OnRequestResultListener() {
@ -453,10 +448,12 @@ public class OnlineRoutingEngineFragment extends BaseOsmAndFragment {
try { try {
JSONObject obj = new JSONObject(response); JSONObject obj = new JSONObject(response);
if (server == ServerType.GRAPHHOPER) { if (type == EngineType.GRAPHHOPER) {
resultOk = obj.has("paths"); resultOk = obj.has("paths");
} else if (server == ServerType.OSRM) { } else if (type == EngineType.OSRM) {
resultOk = obj.has("routes"); resultOk = obj.has("routes");
} else if (type == EngineType.ORS) {
resultOk = obj.has("features");
} }
} catch (JSONException e) { } catch (JSONException e) {
@ -494,7 +491,7 @@ public class OnlineRoutingEngineFragment extends BaseOsmAndFragment {
private void saveState(Bundle outState) { private void saveState(Bundle outState) {
outState.putString(ENGINE_NAME_KEY, engine.customName); outState.putString(ENGINE_NAME_KEY, engine.customName);
outState.putString(ENGINE_SERVER_KEY, engine.serverType.name()); outState.putString(ENGINE_SERVER_KEY, engine.type.name());
outState.putString(ENGINE_SERVER_URL_KEY, engine.customServerUrl); outState.putString(ENGINE_SERVER_URL_KEY, engine.customServerUrl);
outState.putString(ENGINE_VEHICLE_TYPE_KEY, engine.vehicleType.name()); outState.putString(ENGINE_VEHICLE_TYPE_KEY, engine.vehicleType.name());
outState.putString(ENGINE_CUSTOM_VEHICLE_KEY, engine.customVehicleKey); outState.putString(ENGINE_CUSTOM_VEHICLE_KEY, engine.customVehicleKey);
@ -508,7 +505,7 @@ public class OnlineRoutingEngineFragment extends BaseOsmAndFragment {
private void restoreState(Bundle savedState) { private void restoreState(Bundle savedState) {
engine.customName = savedState.getString(ENGINE_NAME_KEY); engine.customName = savedState.getString(ENGINE_NAME_KEY);
engine.serverType = ServerType.valueOf(savedState.getString(ENGINE_SERVER_KEY)); engine.type = EngineType.valueOf(savedState.getString(ENGINE_SERVER_KEY));
engine.customServerUrl = savedState.getString(ENGINE_SERVER_URL_KEY); engine.customServerUrl = savedState.getString(ENGINE_SERVER_URL_KEY);
engine.vehicleType = VehicleType.valueOf(savedState.getString(ENGINE_VEHICLE_TYPE_KEY)); engine.vehicleType = VehicleType.valueOf(savedState.getString(ENGINE_VEHICLE_TYPE_KEY));
engine.customVehicleKey = savedState.getString(ENGINE_CUSTOM_VEHICLE_KEY); engine.customVehicleKey = savedState.getString(ENGINE_CUSTOM_VEHICLE_KEY);
@ -519,16 +516,15 @@ public class OnlineRoutingEngineFragment extends BaseOsmAndFragment {
} }
private void initState() { private void initState() {
engine.serverType = ServerType.values()[0]; engine.type = EngineType.values()[0];
engine.vehicleType = VehicleType.values()[0]; engine.vehicleType = VehicleType.values()[0];
selectedLocation = ExampleLocation.values()[0]; selectedLocation = ExampleLocation.values()[0];
if (isEditingMode()) { if (isEditingMode()) {
OnlineRoutingEngine editedEngine = helper.getEngineByKey(editedEngineKey); OnlineRoutingEngine editedEngine = helper.getEngineByKey(editedEngineKey);
if (editedEngine != null) { if (editedEngine != null) {
engine.customName = editedEngine.getParameter(EngineParameterType.CUSTOM_NAME); engine.customName = editedEngine.getParameter(EngineParameter.CUSTOM_NAME);
engine.serverType = editedEngine.getServerType(); engine.type = editedEngine.getType();
engine.customServerUrl = editedEngine.getParameter(EngineParameterType.CUSTOM_SERVER_URL);
String vehicleKey = editedEngine.getVehicleKey(); String vehicleKey = editedEngine.getVehicleKey();
if (vehicleKey != null) { if (vehicleKey != null) {
VehicleType vehicleType = VehicleType.getVehicleByKey(vehicleKey); VehicleType vehicleType = VehicleType.getVehicleByKey(vehicleKey);
@ -537,7 +533,7 @@ public class OnlineRoutingEngineFragment extends BaseOsmAndFragment {
} }
engine.vehicleType = vehicleType; engine.vehicleType = vehicleType;
} }
engine.apiKey = editedEngine.getParameter(EngineParameterType.API_KEY); engine.apiKey = editedEngine.getParameter(EngineParameter.API_KEY);
} }
} }
} }
@ -583,7 +579,7 @@ public class OnlineRoutingEngineFragment extends BaseOsmAndFragment {
private static class OnlineRoutingEngineObject { private static class OnlineRoutingEngineObject {
private String customName; private String customName;
private ServerType serverType; private EngineType type;
private String customServerUrl; private String customServerUrl;
private VehicleType vehicleType; private VehicleType vehicleType;
private String customVehicleKey; private String customVehicleKey;
@ -596,15 +592,18 @@ public class OnlineRoutingEngineFragment extends BaseOsmAndFragment {
return vehicleType.getKey(); return vehicleType.getKey();
} }
public String getBaseUrl() {
return customServerUrl != null ? customServerUrl : serverType.getBaseUrl();
}
public String getName(Context ctx) { public String getName(Context ctx) {
if (customName != null) { if (customName != null) {
return customName; return customName;
} }
return OnlineRoutingEngine.getStandardName(ctx, serverType, getVehicleKey()); return OnlineRoutingEngine.getStandardName(ctx, type, getVehicleKey());
}
public String getBaseUrl() {
if (Algorithms.isEmpty(customServerUrl)) {
return type.getStandardUrl();
}
return customServerUrl;
} }
} }
} }

View file

@ -6,18 +6,28 @@ import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import net.osmand.PlatformUtil; import net.osmand.PlatformUtil;
import net.osmand.data.LatLon;
import net.osmand.osm.io.NetworkUtils;
import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandApplication;
import net.osmand.plus.Version;
import net.osmand.plus.onlinerouting.OnlineRoutingEngine.EngineParameter;
import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.settings.backend.OsmandSettings;
import net.osmand.util.Algorithms; import net.osmand.util.Algorithms;
import net.osmand.util.GeoPolylineParserUtil;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.net.URLConnection;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -27,8 +37,7 @@ public class OnlineRoutingHelper {
private OsmandApplication app; private OsmandApplication app;
private OsmandSettings settings; private OsmandSettings settings;
private List<OnlineRoutingEngine> cachedEngines; private Map<String, OnlineRoutingEngine> cachedEngines;
private Map<String, OnlineRoutingEngine> cachedEnginesMap;
public OnlineRoutingHelper(OsmandApplication app) { public OnlineRoutingHelper(OsmandApplication app) {
this.app = app; this.app = app;
@ -38,23 +47,121 @@ public class OnlineRoutingHelper {
@NonNull @NonNull
public List<OnlineRoutingEngine> getEngines() { public List<OnlineRoutingEngine> getEngines() {
return cachedEngines; return new ArrayList<>(cachedEngines.values());
} }
public OnlineRoutingEngine getEngineByKey(String stringKey) { public OnlineRoutingEngine getEngineByKey(String stringKey) {
return cachedEnginesMap.get(stringKey); return cachedEngines.get(stringKey);
}
public List<LatLon> calculateRouteOnline(@NonNull OnlineRoutingEngine engine,
@NonNull List<LatLon> path) throws IOException, JSONException {
String fullUrl = createFullUrl(engine, path);
String content = makeRequest(fullUrl);
return parseResponse(engine, content);
}
public String createFullUrl(OnlineRoutingEngine engine, List<LatLon> path) {
StringBuilder sb = new StringBuilder(engine.getBaseUrl());
String vehicle = engine.getVehicleKey();
String apiKey = engine.getParameter(EngineParameter.API_KEY);
switch (engine.getType()) {
case GRAPHHOPER:
sb.append("?");
for (LatLon point : path) {
sb.append("point=")
.append(point.getLatitude())
.append(',')
.append(point.getLongitude())
.append('&');
}
sb.append("vehicle=").append(vehicle);
if (!Algorithms.isEmpty(apiKey)) {
sb.append('&').append("key=").append(apiKey);
}
break;
case OSRM:
sb.append(vehicle).append('/');
for (int i = 0; i < path.size(); i++) {
LatLon point = path.get(i);
sb.append(point.getLongitude()).append(',').append(point.getLatitude());
if (i < path.size() - 1) {
sb.append(';');
}
}
break;
case ORS:
if (path.size() > 1) {
sb.append("driving-car").append('?'); // todo only for testing
if (!Algorithms.isEmpty(apiKey)) {
sb.append("api_key=").append(apiKey);
}
LatLon start = path.get(0);
LatLon end = path.get(path.size() - 1);
sb.append('&').append("start=")
.append(start.getLatitude()).append(',').append(start.getLongitude());
sb.append('&').append("end=")
.append(end.getLatitude()).append(',').append(end.getLongitude());
}
break;
}
return sb.toString();
}
private List<LatLon> parseResponse(OnlineRoutingEngine engine, String content) throws JSONException {
JSONObject obj = new JSONObject(content);
switch (engine.getType()) {
case GRAPHHOPER:
return GeoPolylineParserUtil.parse(
obj.getJSONArray("paths").getJSONObject(0).getString("points"),
GeoPolylineParserUtil.PRECISION_5);
case OSRM:
return GeoPolylineParserUtil.parse(
obj.getJSONArray("routes").getJSONObject(0).getString("geometry"),
GeoPolylineParserUtil.PRECISION_5);
case ORS:
JSONArray array = obj.getJSONArray("features").getJSONObject(0)
.getJSONObject("geometry").getJSONArray("coordinates");
List<LatLon> track = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
JSONArray point = array.getJSONArray(i);
double lat = Double.parseDouble(point.getString(0));
double lon = Double.parseDouble(point.getString(1));
track.add(new LatLon(lat, lon));
}
return track;
}
return new ArrayList<>();
}
private String makeRequest(String url) throws IOException {
URLConnection connection = NetworkUtils.getHttpURLConnection(url);
connection.setRequestProperty("User-Agent", Version.getFullVersion(app));
StringBuilder content = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String s;
while ((s = reader.readLine()) != null) {
content.append(s);
}
try {
reader.close();
} catch (IOException ignored) {
}
return content.toString();
} }
public void saveEngine(@NonNull OnlineRoutingEngine engine) { public void saveEngine(@NonNull OnlineRoutingEngine engine) {
String stringKey = engine.getStringKey(); String stringKey = engine.getStringKey();
OnlineRoutingEngine existedEngine = cachedEnginesMap.get(stringKey); cachedEngines.put(stringKey, engine);
if (existedEngine != null) {
int index = cachedEngines.indexOf(existedEngine);
cachedEngines.set(index, engine);
} else {
cachedEngines.add(engine);
}
cachedEnginesMap.put(stringKey, engine);
saveToSettings(); saveToSettings();
} }
@ -67,19 +174,18 @@ public class OnlineRoutingHelper {
public void deleteEngine(@NonNull OnlineRoutingEngine engine) { public void deleteEngine(@NonNull OnlineRoutingEngine engine) {
String stringKey = engine.getStringKey(); String stringKey = engine.getStringKey();
if (cachedEnginesMap.containsKey(stringKey)) { if (cachedEngines.containsKey(stringKey)) {
OnlineRoutingEngine existedEngine = cachedEnginesMap.remove(stringKey); cachedEngines.remove(stringKey);
cachedEngines.remove(existedEngine);
saveToSettings(); saveToSettings();
} }
} }
private void loadFromSettings() { private void loadFromSettings() {
cachedEngines = readFromSettings(); Map<String, OnlineRoutingEngine> cachedEngines = new LinkedHashMap<>();
cachedEnginesMap = new HashMap<>(); for (OnlineRoutingEngine engine : readFromSettings()) {
for (OnlineRoutingEngine engine : cachedEngines) { cachedEngines.put(engine.getStringKey(), engine);
cachedEnginesMap.put(engine.getStringKey(), engine);
} }
this.cachedEngines = cachedEngines;
} }
@NonNull @NonNull
@ -101,7 +207,7 @@ public class OnlineRoutingHelper {
if (!Algorithms.isEmpty(cachedEngines)) { if (!Algorithms.isEmpty(cachedEngines)) {
try { try {
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();
writeToJson(json, cachedEngines); writeToJson(json, getEngines());
settings.ONLINE_ROUTING_ENGINES.set(json.toString()); settings.ONLINE_ROUTING_ENGINES.set(json.toString());
} catch (JSONException e) { } catch (JSONException e) {
LOG.debug("Error when writing engines to JSON ", e); LOG.debug("Error when writing engines to JSON ", e);
@ -123,10 +229,10 @@ public class OnlineRoutingHelper {
JSONObject object = itemsJson.getJSONObject(i); JSONObject object = itemsJson.getJSONObject(i);
String key = object.getString("key"); String key = object.getString("key");
String vehicleKey = object.getString("vehicle"); String vehicleKey = object.getString("vehicle");
ServerType serverType = ServerType.valueOf(object.getString("serverType")); EngineType engineType = EngineType.valueOf(object.getString("type"));
String paramsString = object.getString("params"); String paramsString = object.getString("params");
HashMap<String, String> params = gson.fromJson(paramsString, type); HashMap<String, String> params = gson.fromJson(paramsString, type);
engines.add(new OnlineRoutingEngine(key, serverType, vehicleKey, params)); engines.add(new OnlineRoutingEngine(key, engineType, vehicleKey, params));
} }
} }
@ -138,7 +244,7 @@ public class OnlineRoutingHelper {
for (OnlineRoutingEngine engine : engines) { for (OnlineRoutingEngine engine : engines) {
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put("key", engine.getStringKey()); jsonObject.put("key", engine.getStringKey());
jsonObject.put("serverType", engine.getServerType().name()); jsonObject.put("type", engine.getType().name());
jsonObject.put("vehicle", engine.getVehicleKey()); jsonObject.put("vehicle", engine.getVehicleKey());
jsonObject.put("params", gson.toJson(engine.getParams(), type)); jsonObject.put("params", gson.toJson(engine.getParams(), type));
jsonArray.put(jsonObject); jsonArray.put(jsonObject);

View file

@ -1,22 +0,0 @@
package net.osmand.plus.onlinerouting;
public enum ServerType {
GRAPHHOPER("Graphhoper", "https://graphhopper.com/api/1/route"),
OSRM("OSRM", "https://zlzk.biz/route/v1/");
ServerType(String title, String baseUrl) {
this.title = title;
this.baseUrl = baseUrl;
}
private String title;
private String baseUrl;
public String getTitle() {
return title;
}
public String getBaseUrl() {
return baseUrl;
}
}

View file

@ -22,6 +22,7 @@ import java.util.Map;
public class ProfileDataUtils { public class ProfileDataUtils {
public static final String OSMAND_NAVIGATION = "osmand_navigation"; public static final String OSMAND_NAVIGATION = "osmand_navigation";
public static final String ONLINE_NAVIGATION = "online_navigation";
public static List<ProfileDataObject> getDataObjects(OsmandApplication app, public static List<ProfileDataObject> getDataObjects(OsmandApplication app,
List<ApplicationMode> appModes) { List<ApplicationMode> appModes) {
@ -48,9 +49,9 @@ public class ProfileDataUtils {
return description; return description;
} }
public static List<RoutingProfileDataObject> getSortedRoutingProfiles(OsmandApplication app) { public static List<ProfileDataObject> getSortedRoutingProfiles(OsmandApplication app) {
List<RoutingProfileDataObject> result = new ArrayList<>(); List<ProfileDataObject> result = new ArrayList<>();
Map<String, List<RoutingProfileDataObject>> routingProfilesByFileNames = getRoutingProfilesByFileNames(app); Map<String, List<ProfileDataObject>> routingProfilesByFileNames = getRoutingProfilesByFileNames(app);
List<String> fileNames = new ArrayList<>(routingProfilesByFileNames.keySet()); List<String> fileNames = new ArrayList<>(routingProfilesByFileNames.keySet());
Collections.sort(fileNames, new Comparator<String>() { Collections.sort(fileNames, new Comparator<String>() {
@Override @Override
@ -59,7 +60,7 @@ public class ProfileDataUtils {
} }
}); });
for (String fileName : fileNames) { for (String fileName : fileNames) {
List<RoutingProfileDataObject> routingProfilesFromFile = routingProfilesByFileNames.get(fileName); List<ProfileDataObject> routingProfilesFromFile = routingProfilesByFileNames.get(fileName);
if (routingProfilesFromFile != null) { if (routingProfilesFromFile != null) {
Collections.sort(routingProfilesFromFile); Collections.sort(routingProfilesFromFile);
result.addAll(routingProfilesFromFile); result.addAll(routingProfilesFromFile);
@ -77,14 +78,20 @@ public class ProfileDataUtils {
return objects; return objects;
} }
public static Map<String, List<RoutingProfileDataObject>> getRoutingProfilesByFileNames(OsmandApplication app) { public static Map<String, List<ProfileDataObject>> getRoutingProfilesByFileNames(OsmandApplication app) {
Map<String, List<RoutingProfileDataObject>> result = new HashMap<>(); Map<String, List<ProfileDataObject>> result = new HashMap<>();
for (final RoutingProfileDataObject profile : getRoutingProfiles(app).values()) { for (final ProfileDataObject profile : getRoutingProfiles(app).values()) {
String fileName = profile.getFileName() != null ? profile.getFileName() : OSMAND_NAVIGATION; String fileName = null;
if (profile instanceof RoutingProfileDataObject) {
fileName = ((RoutingProfileDataObject) profile).getFileName();
} else if (profile instanceof OnlineRoutingEngineDataObject) {
fileName = ONLINE_NAVIGATION;
}
fileName = fileName != null ? fileName : OSMAND_NAVIGATION;
if (result.containsKey(fileName)) { if (result.containsKey(fileName)) {
result.get(fileName).add(profile); result.get(fileName).add(profile);
} else { } else {
result.put(fileName, new ArrayList<RoutingProfileDataObject>() { result.put(fileName, new ArrayList<ProfileDataObject>() {
{ add(profile); } { add(profile); }
}); });
} }
@ -92,8 +99,8 @@ public class ProfileDataUtils {
return result; return result;
} }
public static Map<String, RoutingProfileDataObject> getRoutingProfiles(OsmandApplication context) { public static Map<String, ProfileDataObject> getRoutingProfiles(OsmandApplication context) {
Map<String, RoutingProfileDataObject> profilesObjects = new HashMap<>(); Map<String, ProfileDataObject> profilesObjects = new HashMap<>();
profilesObjects.put(RoutingProfilesResources.STRAIGHT_LINE_MODE.name(), new RoutingProfileDataObject( profilesObjects.put(RoutingProfilesResources.STRAIGHT_LINE_MODE.name(), new RoutingProfileDataObject(
RoutingProfilesResources.STRAIGHT_LINE_MODE.name(), RoutingProfilesResources.STRAIGHT_LINE_MODE.name(),
context.getString(RoutingProfilesResources.STRAIGHT_LINE_MODE.getStringRes()), context.getString(RoutingProfilesResources.STRAIGHT_LINE_MODE.getStringRes()),
@ -119,11 +126,14 @@ public class ProfileDataUtils {
for (RoutingConfiguration.Builder builder : context.getAllRoutingConfigs()) { for (RoutingConfiguration.Builder builder : context.getAllRoutingConfigs()) {
collectRoutingProfilesFromConfig(context, builder, profilesObjects, disabledRouterNames); collectRoutingProfilesFromConfig(context, builder, profilesObjects, disabledRouterNames);
} }
for (OnlineRoutingEngineDataObject onlineEngine : getOnlineRoutingProfiles(context)) {
profilesObjects.put(onlineEngine.getStringKey(), onlineEngine);
}
return profilesObjects; return profilesObjects;
} }
private static void collectRoutingProfilesFromConfig(OsmandApplication app, RoutingConfiguration.Builder builder, private static void collectRoutingProfilesFromConfig(OsmandApplication app, RoutingConfiguration.Builder builder,
Map<String, RoutingProfileDataObject> profilesObjects, List<String> disabledRouterNames) { Map<String, ProfileDataObject> profilesObjects, List<String> disabledRouterNames) {
for (Map.Entry<String, GeneralRouter> entry : builder.getAllRouters().entrySet()) { for (Map.Entry<String, GeneralRouter> entry : builder.getAllRouters().entrySet()) {
String routerKey = entry.getKey(); String routerKey = entry.getKey();
GeneralRouter router = entry.getValue(); GeneralRouter router = entry.getValue();

View file

@ -4,6 +4,7 @@ import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.text.SpannableString; import android.text.SpannableString;
import android.text.Spanned; import android.text.Spanned;
@ -58,7 +59,7 @@ public class SelectProfileBottomSheet extends BasePreferenceBottomSheet {
public final static String PROFILE_KEY_ARG = "profile_key_arg"; public final static String PROFILE_KEY_ARG = "profile_key_arg";
public final static String USE_LAST_PROFILE_ARG = "use_last_profile_arg"; public final static String USE_LAST_PROFILE_ARG = "use_last_profile_arg";
public final static String IS_PROFILE_IMPORTED_ARG = "is_profile_imported_arg"; public final static String PROFILES_LIST_UPDATED_ARG = "is_profiles_list_updated";
private DialogMode dialogMode; private DialogMode dialogMode;
private final List<ProfileDataObject> profiles = new ArrayList<>(); private final List<ProfileDataObject> profiles = new ArrayList<>();
@ -130,7 +131,7 @@ public class SelectProfileBottomSheet extends BasePreferenceBottomSheet {
} }
Bundle args = new Bundle(); Bundle args = new Bundle();
args.putString(PROFILE_KEY_ARG, item.getName()); args.putString(PROFILE_KEY_ARG, item.getName());
args.putBoolean(IS_PROFILE_IMPORTED_ARG, true); args.putBoolean(PROFILES_LIST_UPDATED_ARG, true);
listener.onSelectedType(args); listener.onSelectedType(args);
dismiss(); dismiss();
break; break;
@ -234,9 +235,10 @@ public class SelectProfileBottomSheet extends BasePreferenceBottomSheet {
int activeColorResId = nightMode ? R.color.active_color_primary_dark : R.color.active_color_primary_light; int activeColorResId = nightMode ? R.color.active_color_primary_dark : R.color.active_color_primary_light;
int iconDefaultColorResId = nightMode ? R.color.icon_color_default_dark : R.color.icon_color_default_light; int iconDefaultColorResId = nightMode ? R.color.icon_color_default_dark : R.color.icon_color_default_light;
final boolean onlineRoutingProfile = profile instanceof OnlineRoutingEngineDataObject;
View itemView = UiUtilities.getInflater(getContext(), nightMode).inflate( View itemView = UiUtilities.getInflater(getContext(), nightMode).inflate(
profile instanceof OnlineRoutingEngineDataObject ? onlineRoutingProfile ?
R.layout.bottom_sheet_item_with_descr_radio_and_icon_btn : R.layout.bottom_sheet_item_with_descr_radio_and_icon_btn :
R.layout.bottom_sheet_item_with_descr_and_radio_btn, null); R.layout.bottom_sheet_item_with_descr_and_radio_btn, null);
TextView tvTitle = itemView.findViewById(R.id.title); TextView tvTitle = itemView.findViewById(R.id.title);
@ -262,28 +264,52 @@ public class SelectProfileBottomSheet extends BasePreferenceBottomSheet {
UiUtilities.setupCompoundButton(compoundButton, nightMode, UiUtilities.CompoundButtonType.GLOBAL); UiUtilities.setupCompoundButton(compoundButton, nightMode, UiUtilities.CompoundButtonType.GLOBAL);
bottomDivider.setVisibility(showBottomDivider ? View.VISIBLE : View.INVISIBLE); bottomDivider.setVisibility(showBottomDivider ? View.VISIBLE : View.INVISIBLE);
items.add(new BaseBottomSheetItem.Builder() BaseBottomSheetItem.Builder builder =
.setCustomView(itemView) new BaseBottomSheetItem.Builder().setCustomView(itemView);
.setOnClickListener(new OnClickListener() {
OnClickListener listener = new OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
Bundle args = new Bundle(); Bundle args = new Bundle();
args.putString(PROFILE_KEY_ARG, profile.getStringKey()); args.putString(PROFILE_KEY_ARG, profile.getStringKey());
args.putBoolean(PROFILES_LIST_UPDATED_ARG, onlineRoutingProfile);
Fragment target = getTargetFragment(); Fragment target = getTargetFragment();
if (target instanceof OnSelectProfileCallback) { if (target instanceof OnSelectProfileCallback) {
if (profile instanceof OnlineRoutingEngineDataObject) { ((OnSelectProfileCallback) target).onProfileSelected(args);
}
dismiss();
}
};
if (onlineRoutingProfile) {
View basePart = itemView.findViewById(R.id.basic_item_body);
View endBtn = itemView.findViewById(R.id.end_button);
ImageView ivEndBtnIcon = itemView.findViewById(R.id.end_button_icon);
Drawable drawable = getIcon(R.drawable.ic_action_settings,
nightMode ?
R.color.route_info_control_icon_color_dark :
R.color.route_info_control_icon_color_light);
if (Build.VERSION.SDK_INT >= 21) {
Drawable activeDrawable = getIcon(R.drawable.ic_action_settings, activeColorResId);
drawable = AndroidUtils.createPressedStateListDrawable(drawable, activeDrawable);
}
ivEndBtnIcon.setImageDrawable(drawable);
basePart.setOnClickListener(listener);
endBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (getActivity() != null) { if (getActivity() != null) {
OnlineRoutingEngineFragment.showInstance(getActivity(), getAppMode(), profile.getStringKey()); OnlineRoutingEngineFragment.showInstance(getActivity(), getAppMode(), profile.getStringKey());
} }
dismiss(); dismiss();
}
});
} else { } else {
((OnSelectProfileCallback) target).onProfileSelected(args); builder.setOnClickListener(listener);
} }
} items.add(builder.create());
dismiss();
}
})
.create());
} }
private void addCheckableItem(int titleId, private void addCheckableItem(int titleId,
@ -363,7 +389,6 @@ public class SelectProfileBottomSheet extends BasePreferenceBottomSheet {
case NAVIGATION_PROFILE: case NAVIGATION_PROFILE:
profiles.addAll(ProfileDataUtils.getSortedRoutingProfiles(app)); profiles.addAll(ProfileDataUtils.getSortedRoutingProfiles(app));
profiles.addAll(ProfileDataUtils.getOnlineRoutingProfiles(app));
break; break;
case DEFAULT_PROFILE: case DEFAULT_PROFILE:

View file

@ -22,6 +22,8 @@ import net.osmand.data.LocationPoint;
import net.osmand.data.WptLocationPoint; import net.osmand.data.WptLocationPoint;
import net.osmand.osm.io.NetworkUtils; import net.osmand.osm.io.NetworkUtils;
import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandApplication;
import net.osmand.plus.onlinerouting.OnlineRoutingEngine;
import net.osmand.plus.onlinerouting.OnlineRoutingHelper;
import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.settings.backend.OsmandSettings;
import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.CommonPreference;
import net.osmand.plus.R; import net.osmand.plus.R;
@ -91,7 +93,8 @@ public class RouteProvider {
OSMAND("OsmAnd (offline)"), OSMAND("OsmAnd (offline)"),
BROUTER("BRouter (offline)"), BROUTER("BRouter (offline)"),
STRAIGHT("Straight line"), STRAIGHT("Straight line"),
DIRECT_TO("Direct To"); DIRECT_TO("Direct To"),
ONLINE("Online engine");
private final String name; private final String name;
@ -363,10 +366,8 @@ public class RouteProvider {
res = findVectorMapsRoute(params, calcGPXRoute); res = findVectorMapsRoute(params, calcGPXRoute);
} else if (params.mode.getRouteService() == RouteService.BROUTER) { } else if (params.mode.getRouteService() == RouteService.BROUTER) {
res = findBROUTERRoute(params); res = findBROUTERRoute(params);
// } else if (params.type == RouteService.ORS) { } else if (params.mode.getRouteService() == RouteService.ONLINE) {
// res = findORSRoute(params); res = findOnlineRoute(params);
// } else if (params.type == RouteService.OSRM) {
// res = findOSRMRoute(params);
} else if (params.mode.getRouteService() == RouteService.STRAIGHT || } else if (params.mode.getRouteService() == RouteService.STRAIGHT ||
params.mode.getRouteService() == RouteService.DIRECT_TO) { params.mode.getRouteService() == RouteService.DIRECT_TO) {
res = findStraightRoute(params); res = findStraightRoute(params);
@ -383,6 +384,8 @@ public class RouteProvider {
log.error("Failed to find route ", e); //$NON-NLS-1$ log.error("Failed to find route ", e); //$NON-NLS-1$
} catch (SAXException e) { } catch (SAXException e) {
log.error("Failed to find route ", e); //$NON-NLS-1$ log.error("Failed to find route ", e); //$NON-NLS-1$
} catch (JSONException e) {
log.error("Failed to find route ", e); //$NON-NLS-1$
} }
} }
return new RouteCalculationResult(null); return new RouteCalculationResult(null);
@ -1204,56 +1207,12 @@ public class RouteProvider {
return exporter.exportRoute(); return exporter.exportRoute();
} }
private void appendOSRMLoc(StringBuilder uri, LatLon il) { private RouteCalculationResult findOnlineRoute(RouteCalculationParams params) throws IOException, JSONException {
uri.append(";").append(il.getLongitude()); OnlineRoutingHelper helper = params.ctx.getOnlineRoutingHelper();
uri.append(",").append(il.getLatitude()); String stringKey = params.mode.getRoutingProfile();
} List<LatLon> route = helper.calculateRouteOnline(helper.getEngineByKey(stringKey), getFullPathFromParams(params));
if (!route.isEmpty()) {
protected RouteCalculationResult findOSRMRoute(RouteCalculationParams params) List<Location> res = new ArrayList<>();
throws MalformedURLException, IOException, JSONException {
// http://router.project-osrm.org/route/v1/driving/4.83,52.28;4.95,52.28
List<Location> res = new ArrayList<Location>();
StringBuilder uri = new StringBuilder();
// possibly hide that API key because it is privacy of osmand
// A6421860EBB04234AB5EF2D049F2CD8F key is compromised
String scheme = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
scheme = "https";
} else {
scheme = "http";
}
uri.append(scheme + "://router.project-osrm.org/route/v1/driving/"); //$NON-NLS-1$
uri.append(String.valueOf(params.start.getLongitude()));
uri.append(",").append(String.valueOf(params.start.getLatitude()));
if(params.intermediates != null && params.intermediates.size() > 0) {
for(LatLon il : params.intermediates) {
appendOSRMLoc(uri, il);
}
}
appendOSRMLoc(uri, params.end);
// to get more waypoints, add overview=full option
// uri.append("?overview=full")
log.info("URL route " + uri);
URLConnection connection = NetworkUtils.getHttpURLConnection(uri.toString());
connection.setRequestProperty("User-Agent", Version.getFullVersion(params.ctx));
StringBuilder content = new StringBuilder();
BufferedReader rs = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String s;
while((s = rs.readLine()) != null) {
content.append(s);
}
JSONObject obj = new JSONObject(content.toString());
try {
rs.close();
} catch(IOException e){
}
List<LatLon> route = GeoPolylineParserUtil.parse(obj.getJSONArray("routes").getJSONObject(0).getString("geometry"),
GeoPolylineParserUtil.PRECISION_5);
if (route.isEmpty()) {
return new RouteCalculationResult("Route is empty");
}
for (LatLon pt : route) { for (LatLon pt : route) {
WptPt wpt = new WptPt(); WptPt wpt = new WptPt();
wpt.lat = pt.getLatitude(); wpt.lat = pt.getLatitude();
@ -1262,6 +1221,19 @@ public class RouteProvider {
} }
params.intermediates = null; params.intermediates = null;
return new RouteCalculationResult(res, null, params, null, true); return new RouteCalculationResult(res, null, params, null, true);
} else {
return new RouteCalculationResult("Route is empty");
}
}
private static List<LatLon> getFullPathFromParams(RouteCalculationParams params) {
List<LatLon> points = new ArrayList<>();
points.add(new LatLon(params.start.getLatitude(), params.start.getLongitude()));
if (Algorithms.isEmpty(params.intermediates)) {
points.addAll(params.intermediates);
}
points.add(params.end);
return points;
} }
protected RouteCalculationResult findBROUTERRoute(RouteCalculationParams params) throws MalformedURLException, protected RouteCalculationResult findBROUTERRoute(RouteCalculationParams params) throws MalformedURLException,

View file

@ -8,7 +8,7 @@ import androidx.annotation.Nullable;
import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R; import net.osmand.plus.R;
import net.osmand.plus.onlinerouting.OnlineRoutingEngine; import net.osmand.plus.onlinerouting.OnlineRoutingEngine;
import net.osmand.plus.onlinerouting.OnlineRoutingEngine.EngineParameterType; import net.osmand.plus.onlinerouting.OnlineRoutingEngine.EngineParameter;
import net.osmand.plus.onlinerouting.OnlineRoutingHelper; import net.osmand.plus.onlinerouting.OnlineRoutingHelper;
import org.json.JSONException; import org.json.JSONException;
@ -93,8 +93,8 @@ public class OnlineRoutingSettingsItem extends CollectionSettingsItem<OnlineRout
int number = 0; int number = 0;
while (true) { while (true) {
number++; number++;
OnlineRoutingEngine renamedItem = OnlineRoutingEngine.createNewEngine(item.getServerType(), item.getVehicleKey(), item.getParams()); OnlineRoutingEngine renamedItem = OnlineRoutingEngine.createNewEngine(item.getType(), item.getVehicleKey(), item.getParams());
renamedItem.putParameter(EngineParameterType.CUSTOM_NAME, renamedItem.getName(app) + "_" + number); renamedItem.putParameter(EngineParameter.CUSTOM_NAME, renamedItem.getName(app) + "_" + number);
if (!isDuplicate(renamedItem)) { if (!isDuplicate(renamedItem)) {
return renamedItem; return renamedItem;
} }

View file

@ -35,7 +35,7 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import static net.osmand.plus.importfiles.ImportHelper.ImportType.SETTINGS; import static net.osmand.plus.importfiles.ImportHelper.ImportType.SETTINGS;
import static net.osmand.plus.profiles.SelectProfileBottomSheet.IS_PROFILE_IMPORTED_ARG; import static net.osmand.plus.profiles.SelectProfileBottomSheet.PROFILES_LIST_UPDATED_ARG;
import static net.osmand.plus.profiles.SelectProfileBottomSheet.PROFILE_KEY_ARG; import static net.osmand.plus.profiles.SelectProfileBottomSheet.PROFILE_KEY_ARG;
public class MainSettingsFragment extends BaseSettingsFragment implements OnSelectProfileCallback{ public class MainSettingsFragment extends BaseSettingsFragment implements OnSelectProfileCallback{
@ -229,7 +229,7 @@ public class MainSettingsFragment extends BaseSettingsFragment implements OnSele
FragmentManager fragmentManager = activity.getSupportFragmentManager(); FragmentManager fragmentManager = activity.getSupportFragmentManager();
if (fragmentManager != null) { if (fragmentManager != null) {
String profileKey = args.getString(PROFILE_KEY_ARG); String profileKey = args.getString(PROFILE_KEY_ARG);
boolean imported = args.getBoolean(IS_PROFILE_IMPORTED_ARG); boolean imported = args.getBoolean(PROFILES_LIST_UPDATED_ARG);
ProfileAppearanceFragment.showInstance(activity, SettingsScreenType.PROFILE_APPEARANCE, ProfileAppearanceFragment.showInstance(activity, SettingsScreenType.PROFILE_APPEARANCE,
profileKey, imported); profileKey, imported);
} }

View file

@ -10,13 +10,14 @@ import androidx.preference.Preference;
import androidx.preference.SwitchPreferenceCompat; import androidx.preference.SwitchPreferenceCompat;
import net.osmand.plus.measurementtool.MeasurementToolFragment; import net.osmand.plus.measurementtool.MeasurementToolFragment;
import net.osmand.plus.profiles.ProfileDataObject;
import net.osmand.plus.profiles.ProfileDataUtils; import net.osmand.plus.profiles.ProfileDataUtils;
import net.osmand.plus.routepreparationmenu.RouteOptionsBottomSheet; import net.osmand.plus.routepreparationmenu.RouteOptionsBottomSheet;
import net.osmand.plus.routepreparationmenu.RouteOptionsBottomSheet.DialogMode; import net.osmand.plus.routepreparationmenu.RouteOptionsBottomSheet.DialogMode;
import net.osmand.plus.routing.RouteProvider.RouteService;
import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.settings.backend.ApplicationMode;
import net.osmand.plus.R; import net.osmand.plus.R;
import net.osmand.plus.activities.MapActivity; import net.osmand.plus.activities.MapActivity;
import net.osmand.plus.profiles.RoutingProfileDataObject;
import net.osmand.plus.profiles.RoutingProfileDataObject.RoutingProfilesResources; import net.osmand.plus.profiles.RoutingProfileDataObject.RoutingProfilesResources;
import net.osmand.plus.profiles.SelectProfileBottomSheet; import net.osmand.plus.profiles.SelectProfileBottomSheet;
import net.osmand.plus.profiles.SelectProfileBottomSheet.OnSelectProfileCallback; import net.osmand.plus.profiles.SelectProfileBottomSheet.OnSelectProfileCallback;
@ -26,7 +27,8 @@ import net.osmand.util.Algorithms;
import java.util.Map; import java.util.Map;
import static net.osmand.plus.profiles.SelectProfileBottomSheet.IS_PROFILE_IMPORTED_ARG; import static net.osmand.plus.onlinerouting.OnlineRoutingEngine.ONLINE_ROUTING_ENGINE_PREFIX;
import static net.osmand.plus.profiles.SelectProfileBottomSheet.PROFILES_LIST_UPDATED_ARG;
import static net.osmand.plus.profiles.SelectProfileBottomSheet.PROFILE_KEY_ARG; import static net.osmand.plus.profiles.SelectProfileBottomSheet.PROFILE_KEY_ARG;
import static net.osmand.plus.routepreparationmenu.RouteOptionsBottomSheet.DIALOG_MODE_KEY; import static net.osmand.plus.routepreparationmenu.RouteOptionsBottomSheet.DIALOG_MODE_KEY;
@ -35,13 +37,13 @@ public class NavigationFragment extends BaseSettingsFragment implements OnSelect
public static final String TAG = NavigationFragment.class.getSimpleName(); public static final String TAG = NavigationFragment.class.getSimpleName();
public static final String NAVIGATION_TYPE = "navigation_type"; public static final String NAVIGATION_TYPE = "navigation_type";
private Map<String, RoutingProfileDataObject> routingProfileDataObjects; private Map<String, ProfileDataObject> routingProfileDataObjects;
private Preference navigationType; private Preference navigationType;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
routingProfileDataObjects = ProfileDataUtils.getRoutingProfiles(app); updateRoutingProfilesDataObjects();
setupOnBackPressedCallback(); setupOnBackPressedCallback();
} }
@ -90,7 +92,7 @@ public class NavigationFragment extends BaseSettingsFragment implements OnSelect
private void setupNavigationTypePref() { private void setupNavigationTypePref() {
String routingProfileKey = getSelectedAppMode().getRoutingProfile(); String routingProfileKey = getSelectedAppMode().getRoutingProfile();
if (!Algorithms.isEmpty(routingProfileKey)) { if (!Algorithms.isEmpty(routingProfileKey)) {
RoutingProfileDataObject routingProfileDataObject = routingProfileDataObjects.get(routingProfileKey); ProfileDataObject routingProfileDataObject = routingProfileDataObjects.get(routingProfileKey);
if (routingProfileDataObject != null) { if (routingProfileDataObject != null) {
navigationType.setSummary(routingProfileDataObject.getName()); navigationType.setSummary(routingProfileDataObject.getName());
navigationType.setIcon(getActiveIcon(routingProfileDataObject.getIconRes())); navigationType.setIcon(getActiveIcon(routingProfileDataObject.getIconRes()));
@ -132,12 +134,16 @@ public class NavigationFragment extends BaseSettingsFragment implements OnSelect
return false; return false;
} }
private void updateRoutingProfilesDataObjects() {
routingProfileDataObjects = ProfileDataUtils.getRoutingProfiles(app);
}
void updateRoutingProfile(String profileKey) { void updateRoutingProfile(String profileKey) {
RoutingProfileDataObject selectedRoutingProfileDataObject = routingProfileDataObjects.get(profileKey); ProfileDataObject selectedRoutingProfileDataObject = routingProfileDataObjects.get(profileKey);
if (profileKey == null || selectedRoutingProfileDataObject == null) { if (profileKey == null || selectedRoutingProfileDataObject == null) {
return; return;
} }
for (Map.Entry<String, RoutingProfileDataObject> rp : routingProfileDataObjects.entrySet()) { for (Map.Entry<String, ProfileDataObject> rp : routingProfileDataObjects.entrySet()) {
boolean selected = profileKey.equals(rp.getKey()); boolean selected = profileKey.equals(rp.getKey());
rp.getValue().setSelected(selected); rp.getValue().setSelected(selected);
} }
@ -152,6 +158,8 @@ public class NavigationFragment extends BaseSettingsFragment implements OnSelect
routeService = RouteProvider.RouteService.DIRECT_TO; routeService = RouteProvider.RouteService.DIRECT_TO;
} else if (profileKey.equals(RoutingProfilesResources.BROUTER_MODE.name())) { } else if (profileKey.equals(RoutingProfilesResources.BROUTER_MODE.name())) {
routeService = RouteProvider.RouteService.BROUTER; routeService = RouteProvider.RouteService.BROUTER;
} else if (profileKey.startsWith(ONLINE_ROUTING_ENGINE_PREFIX)) {
routeService = RouteService.ONLINE;
} else { } else {
routeService = RouteProvider.RouteService.OSMAND; routeService = RouteProvider.RouteService.OSMAND;
} }
@ -174,8 +182,8 @@ public class NavigationFragment extends BaseSettingsFragment implements OnSelect
@Override @Override
public void onProfileSelected(Bundle args) { public void onProfileSelected(Bundle args) {
if (args.getBoolean(IS_PROFILE_IMPORTED_ARG)) { if (args.getBoolean(PROFILES_LIST_UPDATED_ARG)) {
routingProfileDataObjects = ProfileDataUtils.getRoutingProfiles(app); updateRoutingProfilesDataObjects();
} }
updateRoutingProfile(args.getString(PROFILE_KEY_ARG)); updateRoutingProfile(args.getString(PROFILE_KEY_ARG));
} }

View file

@ -66,7 +66,7 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import static net.osmand.aidlapi.OsmAndCustomizationConstants.DRAWER_SETTINGS_ID; import static net.osmand.aidlapi.OsmAndCustomizationConstants.DRAWER_SETTINGS_ID;
import static net.osmand.plus.profiles.SelectProfileBottomSheet.IS_PROFILE_IMPORTED_ARG; import static net.osmand.plus.profiles.SelectProfileBottomSheet.PROFILES_LIST_UPDATED_ARG;
import static net.osmand.plus.profiles.SelectProfileBottomSheet.PROFILE_KEY_ARG; import static net.osmand.plus.profiles.SelectProfileBottomSheet.PROFILE_KEY_ARG;
public class ProfileAppearanceFragment extends BaseSettingsFragment implements OnSelectProfileCallback { public class ProfileAppearanceFragment extends BaseSettingsFragment implements OnSelectProfileCallback {
@ -934,7 +934,7 @@ public class ProfileAppearanceFragment extends BaseSettingsFragment implements O
@Override @Override
public void onProfileSelected(Bundle args) { public void onProfileSelected(Bundle args) {
String profileKey = args.getString(PROFILE_KEY_ARG); String profileKey = args.getString(PROFILE_KEY_ARG);
boolean imported = args.getBoolean(IS_PROFILE_IMPORTED_ARG); boolean imported = args.getBoolean(PROFILES_LIST_UPDATED_ARG);
updateParentProfile(profileKey, imported); updateParentProfile(profileKey, imported);
} }