Adds checkstyle to CI (#7442)

* adds checkstyle to CI

* fixed gradlew path

* resolved testapp checkstyle violations

* added back mapboxMap variable for test

* checkstyle annotations

* checkstyle SDK round 1

* maps package checkstyle

* rest of SDK checkstyle

* checkstyle gesture library

* checkstyle test

* finished rest of test checkstyle

* resolved all checkstyle errors

* fixed class name

* removed old test file

* fixed camera postion test

* fixed native crash
This commit is contained in:
Cameron Mace
2016-12-16 16:19:15 -05:00
committed by GitHub
parent f95b4838ea
commit 20b958301e
266 changed files with 40182 additions and 39049 deletions

View File

@@ -90,5 +90,6 @@ apply from: 'gradle-make.gradle'
apply from: 'gradle-config.gradle'
apply from: 'gradle-device-farm.gradle'
apply from: 'gradle-spoon.gradle'
apply from: 'gradle-checkstyle.gradle'

View File

@@ -0,0 +1,17 @@
apply plugin: 'checkstyle'
checkstyle {
toolVersion = "7.1.1" // 7.3
configFile = "../checkstyle.xml" as File
}
task checkstyle(type: Checkstyle) {
description 'Checks if the code adheres to coding standards'
group 'verification'
configFile file("../checkstyle.xml")
source 'src'
include '**/*.java'
exclude '**/gen/**'
classpath = files()
ignoreFailures = false
}

View File

@@ -7,27 +7,27 @@ import com.mapbox.mapboxsdk.geometry.LatLng;
*/
public class MapViewUtils {
public static void setDirection(MapboxMap mapboxMap, float direction) {
mapboxMap.getTransform().setBearing(direction);
}
public static void setDirection(MapboxMap mapboxMap, float direction) {
mapboxMap.getTransform().setBearing(direction);
}
public static float getDirection(MapboxMap mapboxMap) {
return (float) mapboxMap.getTransform().getBearing();
}
public static float getDirection(MapboxMap mapboxMap) {
return (float) mapboxMap.getTransform().getBearing();
}
public static void setTilt(MapboxMap mapboxMap, float tilt) {
mapboxMap.getTransform().setTilt((double) tilt);
}
public static void setTilt(MapboxMap mapboxMap, float tilt) {
mapboxMap.getTransform().setTilt((double) tilt);
}
public static float getTilt(MapboxMap mapboxMap) {
return (float) mapboxMap.getTransform().getTilt();
}
public static float getTilt(MapboxMap mapboxMap) {
return (float) mapboxMap.getTransform().getTilt();
}
public static void setLatLng(MapboxMap mapboxMap, LatLng latLng) {
mapboxMap.getTransform().setCenterCoordinate(latLng);
}
public static void setLatLng(MapboxMap mapboxMap, LatLng latLng) {
mapboxMap.getTransform().setCenterCoordinate(latLng);
}
public static LatLng getLatLng(MapboxMap mapboxMap) {
return mapboxMap.getTransform().getCenterCoordinate();
}
public static LatLng getLatLng(MapboxMap mapboxMap) {
return mapboxMap.getTransform().getCenterCoordinate();
}
}

View File

@@ -4,6 +4,7 @@ import android.app.Activity;
import android.support.test.espresso.Espresso;
import android.support.test.espresso.IdlingResourceTimeoutException;
import android.support.test.rule.ActivityTestRule;
import timber.log.Timber;
import com.mapbox.mapboxsdk.maps.MapboxMap;
@@ -22,49 +23,50 @@ import static android.support.test.espresso.matcher.ViewMatchers.withId;
public abstract class BaseActivityTest {
@Rule
public ActivityTestRule<Activity> rule = new ActivityTestRule<>(getActivityClass());
protected MapboxMap mapboxMap;
protected OnMapReadyIdlingResource idlingResource;
@Rule
public ActivityTestRule<Activity> rule = new ActivityTestRule<>(getActivityClass());
protected MapboxMap mapboxMap;
protected OnMapReadyIdlingResource idlingResource;
@Before
public void beforeTest() {
try {
Timber.e("@Before test: register idle resource");
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
checkViewIsDisplayed(R.id.mapView);
mapboxMap = idlingResource.getMapboxMap();
} catch (IdlingResourceTimeoutException e) {
Timber.e("Idling resource timed out. Couldn't not validate if map is ready.");
throw new RuntimeException("Could not start test for " + getActivityClass().getSimpleName() + ".\n" +
"The ViewHierarchy doesn't contain a view with resource id = R.id.mapView or \n" +
"the Activity doesn't contain an instance variable with a name equal to mapboxMap.\n" +
"You can resolve this issue be implementing the requirements above or\n add " + getActivityClass().getSimpleName() + " to the excludeActivities array in `generate-test-code.js`.\n");
}
@Before
public void beforeTest() {
try {
Timber.e("@Before test: register idle resource");
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
checkViewIsDisplayed(R.id.mapView);
mapboxMap = idlingResource.getMapboxMap();
} catch (IdlingResourceTimeoutException idlingResourceTimeoutException) {
Timber.e("Idling resource timed out. Couldn't not validate if map is ready.");
throw new RuntimeException("Could not start test for " + getActivityClass().getSimpleName() + ".\n"
+ "The ViewHierarchy doesn't contain a view with resource id = R.id.mapView or \n"
+ "the Activity doesn't contain an instance variable with a name equal to mapboxMap.\n"
+ "You can resolve this issue be implementing the requirements above or\n add "
+ getActivityClass().getSimpleName() + " to the excludeActivities array in `generate-test-code.js`.\n");
}
}
protected abstract Class getActivityClass();
protected abstract Class getActivityClass();
protected void checkViewIsDisplayed(int id) {
onView(withId(id))
.check(matches(isDisplayed()));
}
protected void checkViewIsDisplayed(int id) {
onView(withId(id))
.check(matches(isDisplayed()));
}
protected void takeScreenshot(final String name) {
final Activity activity = rule.getActivity();
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
ScreenshotUtil.take(activity, name);
}
});
}
protected void takeScreenshot(final String name) {
final Activity activity = rule.getActivity();
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
ScreenshotUtil.take(activity, name);
}
});
}
@After
public void afterTest() {
Timber.e("@After test: unregister idle resource");
Espresso.unregisterIdlingResources(idlingResource);
}
@After
public void afterTest() {
Timber.e("@After test: unregister idle resource");
Espresso.unregisterIdlingResources(idlingResource);
}
}

View File

@@ -32,111 +32,111 @@ import static org.junit.Assert.assertEquals;
public class MarkerTest {
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
private OnMapReadyIdlingResource idlingResource;
private Marker marker;
private OnMapReadyIdlingResource idlingResource;
private Marker marker;
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
@Ignore
public void addMarkerTest() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
assertEquals("Markers should be empty", 0, mapboxMap.getMarkers().size());
MarkerOptions options = new MarkerOptions();
options.setPosition(new LatLng());
options.setSnippet(TestConstants.TEXT_MARKER_SNIPPET);
options.setTitle(TestConstants.TEXT_MARKER_TITLE);
onView(withId(R.id.mapView)).perform(new AddMarkerAction(mapboxMap, options));
assertEquals("Markers sze should be 1, ", 1, mapboxMap.getMarkers().size());
assertEquals("Marker id should be 0", 0, marker.getId());
assertEquals("Marker target should match", new LatLng(), marker.getPosition());
assertEquals("Marker snippet should match", TestConstants.TEXT_MARKER_SNIPPET, marker.getSnippet());
assertEquals("Marker target should match", TestConstants.TEXT_MARKER_TITLE, marker.getTitle());
mapboxMap.clear();
assertEquals("Markers should be empty", 0, mapboxMap.getMarkers().size());
}
@Test
@Ignore
public void showInfoWindowTest() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final MarkerOptions options = new MarkerOptions();
options.setPosition(new LatLng());
options.setSnippet(TestConstants.TEXT_MARKER_SNIPPET);
options.setTitle(TestConstants.TEXT_MARKER_TITLE);
onView(withId(R.id.mapView)).perform(new AddMarkerAction(mapboxMap, options));
onView(withId(R.id.mapView)).perform(new ShowInfoWindowAction(mapboxMap));
onView(withText(TestConstants.TEXT_MARKER_TITLE)).check(matches(isDisplayed()));
onView(withText(TestConstants.TEXT_MARKER_SNIPPET)).check(matches(isDisplayed()));
}
private class AddMarkerAction implements ViewAction {
private MapboxMap mapboxMap;
private MarkerOptions options;
AddMarkerAction(MapboxMap map, MarkerOptions markerOptions) {
mapboxMap = map;
options = markerOptions;
}
@Test
@Ignore
public void addMarkerTest() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
assertEquals("Markers should be empty", 0, mapboxMap.getMarkers().size());
MarkerOptions options = new MarkerOptions();
options.setPosition(new LatLng());
options.setSnippet(TestConstants.TEXT_MARKER_SNIPPET);
options.setTitle(TestConstants.TEXT_MARKER_TITLE);
onView(withId(R.id.mapView)).perform(new AddMarkerAction(mapboxMap, options));
assertEquals("Markers sze should be 1, ", 1, mapboxMap.getMarkers().size());
assertEquals("Marker id should be 0", 0, marker.getId());
assertEquals("Marker target should match", new LatLng(), marker.getPosition());
assertEquals("Marker snippet should match", TestConstants.TEXT_MARKER_SNIPPET, marker.getSnippet());
assertEquals("Marker target should match", TestConstants.TEXT_MARKER_TITLE, marker.getTitle());
mapboxMap.clear();
assertEquals("Markers should be empty", 0, mapboxMap.getMarkers().size());
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Test
@Ignore
public void showInfoWindowTest(){
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final MarkerOptions options = new MarkerOptions();
options.setPosition(new LatLng());
options.setSnippet(TestConstants.TEXT_MARKER_SNIPPET);
options.setTitle(TestConstants.TEXT_MARKER_TITLE);
onView(withId(R.id.mapView)).perform(new AddMarkerAction(mapboxMap, options));
onView(withId(R.id.mapView)).perform(new ShowInfoWindowAction(mapboxMap));
onView(withText(TestConstants.TEXT_MARKER_TITLE)).check(matches(isDisplayed()));
onView(withText(TestConstants.TEXT_MARKER_SNIPPET)).check(matches(isDisplayed()));
@Override
public String getDescription() {
return getClass().getSimpleName();
}
private class AddMarkerAction implements ViewAction {
@Override
public void perform(UiController uiController, View view) {
marker = mapboxMap.addMarker(options);
}
}
private MapboxMap mapboxMap;
private MarkerOptions options;
private class ShowInfoWindowAction implements ViewAction {
AddMarkerAction(MapboxMap map, MarkerOptions markerOptions) {
mapboxMap = map;
options = markerOptions;
}
private MapboxMap mapboxMap;
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
marker = mapboxMap.addMarker(options);
}
ShowInfoWindowAction(MapboxMap map) {
mapboxMap = map;
}
private class ShowInfoWindowAction implements ViewAction {
private MapboxMap mapboxMap;
ShowInfoWindowAction(MapboxMap map) {
mapboxMap = map;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.selectMarker(marker);
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.selectMarker(marker);
}
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
}

View File

@@ -33,114 +33,115 @@ import static org.junit.Assert.assertEquals;
public class MarkerViewTest {
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
private OnMapReadyIdlingResource idlingResource;
private Marker marker;
private OnMapReadyIdlingResource idlingResource;
private Marker marker;
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
@Ignore
public void addMarkerViewTest() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
assertEquals("Markers should be empty", 0, mapboxMap.getMarkers().size());
TextMarkerViewOptions options = new TextMarkerViewOptions();
options.text(TestConstants.TEXT_MARKER_TEXT);
options.position(new LatLng());
options.snippet(TestConstants.TEXT_MARKER_SNIPPET);
options.title(TestConstants.TEXT_MARKER_TITLE);
onView(withId(R.id.mapView)).perform(new AddTextMarkerViewAction(mapboxMap, options));
assertEquals("Markers sze should be 1, ", 1, mapboxMap.getMarkers().size());
assertEquals("Marker id should be 0", 0, marker.getId());
assertEquals("Marker target should match", new LatLng(), marker.getPosition());
assertEquals("Marker snippet should match", TestConstants.TEXT_MARKER_SNIPPET, marker.getSnippet());
assertEquals("Marker target should match", TestConstants.TEXT_MARKER_TITLE, marker.getTitle());
onView(withText(TestConstants.TEXT_MARKER_TEXT)).check(matches(isDisplayed()));
}
@Test
@Ignore
public void showInfoWindowTest() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final TextMarkerViewOptions options = new TextMarkerViewOptions();
options.position(new LatLng());
options.text(TestConstants.TEXT_MARKER_TEXT);
options.snippet(TestConstants.TEXT_MARKER_SNIPPET);
options.title(TestConstants.TEXT_MARKER_TITLE);
onView(withId(R.id.mapView)).perform(new AddTextMarkerViewAction(mapboxMap, options));
onView(withText(TestConstants.TEXT_MARKER_TEXT)).check(matches(isDisplayed()));
onView(withId(R.id.mapView)).perform(new ShowInfoWindowAction(mapboxMap));
onView(withText(TestConstants.TEXT_MARKER_TITLE)).check(matches(isDisplayed()));
onView(withText(TestConstants.TEXT_MARKER_SNIPPET)).check(matches(isDisplayed()));
}
private class AddTextMarkerViewAction implements ViewAction {
private MapboxMap mapboxMap;
private TextMarkerViewOptions options;
AddTextMarkerViewAction(MapboxMap map, TextMarkerViewOptions markerOptions) {
mapboxMap = map;
options = markerOptions;
}
@Test
@Ignore
public void addMarkerViewTest() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
assertEquals("Markers should be empty", 0, mapboxMap.getMarkers().size());
TextMarkerViewOptions options = new TextMarkerViewOptions();
options.text(TestConstants.TEXT_MARKER_TEXT);
options.position(new LatLng());
options.snippet(TestConstants.TEXT_MARKER_SNIPPET);
options.title(TestConstants.TEXT_MARKER_TITLE);
onView(withId(R.id.mapView)).perform(new AddTextMarkerViewAction(mapboxMap, options));
assertEquals("Markers sze should be 1, ", 1, mapboxMap.getMarkers().size());
assertEquals("Marker id should be 0", 0, marker.getId());
assertEquals("Marker target should match", new LatLng(), marker.getPosition());
assertEquals("Marker snippet should match", TestConstants.TEXT_MARKER_SNIPPET, marker.getSnippet());
assertEquals("Marker target should match", TestConstants.TEXT_MARKER_TITLE, marker.getTitle());
onView(withText(TestConstants.TEXT_MARKER_TEXT)).check(matches(isDisplayed()));
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Test
@Ignore
public void showInfoWindowTest() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final TextMarkerViewOptions options = new TextMarkerViewOptions();
options.position(new LatLng());
options.text(TestConstants.TEXT_MARKER_TEXT);
options.snippet(TestConstants.TEXT_MARKER_SNIPPET);
options.title(TestConstants.TEXT_MARKER_TITLE);
onView(withId(R.id.mapView)).perform(new AddTextMarkerViewAction(mapboxMap, options));
onView(withText(TestConstants.TEXT_MARKER_TEXT)).check(matches(isDisplayed()));
onView(withId(R.id.mapView)).perform(new ShowInfoWindowAction(mapboxMap));
onView(withText(TestConstants.TEXT_MARKER_TITLE)).check(matches(isDisplayed()));
onView(withText(TestConstants.TEXT_MARKER_SNIPPET)).check(matches(isDisplayed()));
@Override
public String getDescription() {
return getClass().getSimpleName();
}
private class AddTextMarkerViewAction implements ViewAction {
@Override
public void perform(UiController uiController, View view) {
mapboxMap.getMarkerViewManager().addMarkerViewAdapter(
new MarkerViewActivity.TextAdapter(view.getContext(), mapboxMap));
marker = mapboxMap.addMarker(options);
uiController.loopMainThreadForAtLeast(250);
}
}
private MapboxMap mapboxMap;
private TextMarkerViewOptions options;
private class ShowInfoWindowAction implements ViewAction {
AddTextMarkerViewAction(MapboxMap map, TextMarkerViewOptions markerOptions) {
mapboxMap = map;
options = markerOptions;
}
private MapboxMap mapboxMap;
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.getMarkerViewManager().addMarkerViewAdapter(new MarkerViewActivity.TextAdapter(view.getContext(), mapboxMap));
marker = mapboxMap.addMarker(options);
uiController.loopMainThreadForAtLeast(250);
}
ShowInfoWindowAction(MapboxMap map) {
mapboxMap = map;
}
private class ShowInfoWindowAction implements ViewAction {
private MapboxMap mapboxMap;
ShowInfoWindowAction(MapboxMap map) {
mapboxMap = map;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.selectMarker(marker);
uiController.loopMainThreadForAtLeast(250);
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.selectMarker(marker);
uiController.loopMainThreadForAtLeast(250);
}
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
}

View File

@@ -30,75 +30,76 @@ import static org.junit.Assert.assertEquals;
public class PolygonTest {
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
private OnMapReadyIdlingResource idlingResource;
private Polygon polygon;
private OnMapReadyIdlingResource idlingResource;
private Polygon polygon;
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
@Ignore
/** native crash **/
public void addPolygonTest() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
LatLng latLngOne = new LatLng();
LatLng latLngTwo = new LatLng(1, 0);
LatLng latLngThree = new LatLng(1, 1);
assertEquals("Polygons should be empty", 0, mapboxMap.getPolygons().size());
final PolygonOptions options = new PolygonOptions();
options.strokeColor(Color.BLUE);
options.fillColor(Color.RED);
options.add(latLngOne);
options.add(latLngTwo);
options.add(latLngThree);
onView(withId(R.id.mapView)).perform(new AddPolygonAction(mapboxMap, options));
assertEquals("Polygons should be 1", 1, mapboxMap.getPolygons().size());
assertEquals("Polygon id should be 0", 0, polygon.getId());
assertEquals("Polygon points size should match", 3, polygon.getPoints().size());
assertEquals("Polygon stroke color should match", Color.BLUE, polygon.getStrokeColor());
assertEquals("Polygon target should match", Color.RED, polygon.getFillColor());
mapboxMap.clear();
assertEquals("Polygons should be empty", 0, mapboxMap.getPolygons().size());
}
private class AddPolygonAction implements ViewAction {
private MapboxMap mapboxMap;
private PolygonOptions options;
AddPolygonAction(MapboxMap map, PolygonOptions polygonOptions) {
mapboxMap = map;
options = polygonOptions;
}
@Test
@Ignore /** native crash **/
public void addPolygonTest() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
LatLng latLngOne = new LatLng();
LatLng latLngTwo = new LatLng(1, 0);
LatLng latLngThree = new LatLng(1, 1);
assertEquals("Polygons should be empty", 0, mapboxMap.getPolygons().size());
final PolygonOptions options = new PolygonOptions();
options.strokeColor(Color.BLUE);
options.fillColor(Color.RED);
options.add(latLngOne);
options.add(latLngTwo);
options.add(latLngThree);
onView(withId(R.id.mapView)).perform(new AddPolygonAction(mapboxMap, options));
assertEquals("Polygons should be 1", 1, mapboxMap.getPolygons().size());
assertEquals("Polygon id should be 0", 0, polygon.getId());
assertEquals("Polygon points size should match", 3, polygon.getPoints().size());
assertEquals("Polygon stroke color should match", Color.BLUE, polygon.getStrokeColor());
assertEquals("Polygon target should match", Color.RED, polygon.getFillColor());
mapboxMap.clear();
assertEquals("Polygons should be empty", 0, mapboxMap.getPolygons().size());
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
private class AddPolygonAction implements ViewAction {
private MapboxMap mapboxMap;
private PolygonOptions options;
AddPolygonAction(MapboxMap map, PolygonOptions polygonOptions) {
mapboxMap = map;
options = polygonOptions;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
polygon = mapboxMap.addPolygon(options);
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
@Override
public void perform(UiController uiController, View view) {
polygon = mapboxMap.addPolygon(options);
}
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
}

View File

@@ -30,71 +30,71 @@ import static org.junit.Assert.assertEquals;
public class PolylineTest {
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
private OnMapReadyIdlingResource idlingResource;
private Polyline polyline;
private OnMapReadyIdlingResource idlingResource;
private Polyline polyline;
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Ignore
@Test
public void addPolylineTest() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
LatLng latLngOne = new LatLng();
LatLng latLngTwo = new LatLng(1, 0);
assertEquals("Polygons should be empty", 0, mapboxMap.getPolygons().size());
final PolylineOptions options = new PolylineOptions();
options.color(Color.BLUE);
options.add(latLngOne);
options.add(latLngTwo);
onView(withId(R.id.mapView)).perform(new AddPolyLineAction(mapboxMap, options));
assertEquals("Polylines should be 1", 1, mapboxMap.getPolylines().size());
assertEquals("Polyline id should be 0", 0, polyline.getId());
assertEquals("Polyline points size should match", 2, polyline.getPoints().size());
assertEquals("Polyline stroke color should match", Color.BLUE, polyline.getColor());
mapboxMap.clear();
assertEquals("Polyline should be empty", 0, mapboxMap.getPolylines().size());
}
private class AddPolyLineAction implements ViewAction {
private MapboxMap mapboxMap;
private PolylineOptions options;
AddPolyLineAction(MapboxMap map, PolylineOptions polylineOptions) {
mapboxMap = map;
options = polylineOptions;
}
@Ignore
@Test
public void addPolylineTest() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
LatLng latLngOne = new LatLng();
LatLng latLngTwo = new LatLng(1, 0);
assertEquals("Polygons should be empty", 0, mapboxMap.getPolygons().size());
final PolylineOptions options = new PolylineOptions();
options.color(Color.BLUE);
options.add(latLngOne);
options.add(latLngTwo);
onView(withId(R.id.mapView)).perform(new AddPolyLineAction(mapboxMap, options));
assertEquals("Polylines should be 1", 1, mapboxMap.getPolylines().size());
assertEquals("Polyline id should be 0", 0, polyline.getId());
assertEquals("Polyline points size should match", 2, polyline.getPoints().size());
assertEquals("Polyline stroke color should match", Color.BLUE, polyline.getColor());
mapboxMap.clear();
assertEquals("Polyline should be empty", 0, mapboxMap.getPolylines().size());
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
private class AddPolyLineAction implements ViewAction {
private MapboxMap mapboxMap;
private PolylineOptions options;
AddPolyLineAction(MapboxMap map, PolylineOptions polylineOptions) {
mapboxMap = map;
options = polylineOptions;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
polyline = mapboxMap.addPolyline(options);
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
@Override
public void perform(UiController uiController, View view) {
polyline = mapboxMap.addPolyline(options);
}
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
}

View File

@@ -10,7 +10,6 @@ import android.view.View;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.camera.CameraUpdate;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.constants.MapboxConstants;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.geometry.LatLngBounds;
import com.mapbox.mapboxsdk.maps.MapboxMap;
@@ -33,206 +32,222 @@ import static org.junit.Assert.assertEquals;
public class CameraAnimateTest {
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
public void testAnimateToCameraPositionTarget() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO remove zoom #6474*/
float zoom = 1.0f;
LatLng moveTarget = new LatLng(1, 1);
CameraPosition initialPosition = new CameraPosition.Builder().target(
new LatLng()).zoom(zoom).bearing(0).tilt(0).build();
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Default camera position should match default", cameraPosition, initialPosition);
onView(withId(R.id.mapView)).perform(new AnimateCameraAction(mapboxMap, CameraUpdateFactory.newLatLng(moveTarget)));
cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(),
moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(),
moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA);
}
@Test
public void testAnimateToCameraPositionTargetZoom() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final float moveZoom = 15.5f;
final LatLng moveTarget = new LatLng(1.0000000001, 1.0000000003);
onView(withId(R.id.mapView)).perform(new AnimateCameraAction(mapboxMap,
CameraUpdateFactory.newLatLngZoom(moveTarget, moveZoom)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(),
moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(),
moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved zoom should match", cameraPosition.zoom, moveZoom, TestConstants.ZOOM_DELTA);
}
@Test
public void testAnimateToCameraPosition() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final LatLng moveTarget = new LatLng(1.0000000001, 1.0000000003);
final float moveZoom = 15.5f;
final float moveTilt = 45.5f;
final float moveBearing = 12.5f;
onView(withId(R.id.mapView)).perform(
new AnimateCameraAction(mapboxMap, CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(moveTarget)
.zoom(moveZoom)
.tilt(moveTilt)
.bearing(moveBearing)
.build()))
);
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(),
moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(),
moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved zoom should match", cameraPosition.zoom, moveZoom, TestConstants.ZOOM_DELTA);
assertEquals("Moved zoom should match", cameraPosition.tilt, moveTilt, TestConstants.TILT_DELTA);
assertEquals("Moved bearing should match", cameraPosition.bearing, moveBearing, TestConstants.BEARING_DELTA);
}
@Test
public void testAnimateToBounds() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final LatLng centerBounds = new LatLng(1, 1);
LatLng cornerOne = new LatLng();
LatLng cornerTwo = new LatLng(2, 2);
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(cornerOne);
builder.include(cornerTwo);
onView(withId(R.id.mapView)).perform(new AnimateCameraAction(mapboxMap,
CameraUpdateFactory.newLatLngBounds(builder.build(), 0)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match center bounds",
cameraPosition.target.getLatitude(),
centerBounds.getLatitude(),
TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match center bounds",
cameraPosition.target.getLongitude(),
centerBounds.getLongitude(),
TestConstants.LAT_LNG_DELTA);
}
@Test
public void testAnimateToMoveBy() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final PointF centerPoint = mapboxMap.getProjection().toScreenLocation(mapboxMap.getCameraPosition().target);
final LatLng moveTarget = new LatLng(2, 2);
final PointF moveTargetPoint = mapboxMap.getProjection().toScreenLocation(moveTarget);
onView(withId(R.id.mapView)).perform(new AnimateCameraAction(mapboxMap, CameraUpdateFactory.scrollBy(
moveTargetPoint.x - centerPoint.x, moveTargetPoint.y - centerPoint.y)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(),
moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA_LARGE);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(),
moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA_LARGE);
}
@Test
public void testAnimateToZoomIn() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
float zoom = 1.0f;
onView(withId(R.id.mapView)).perform(new AnimateCameraAction(mapboxMap, CameraUpdateFactory.zoomIn()));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoom + 1,
TestConstants.ZOOM_DELTA);
}
@Test
public void testAnimateToZoomOut() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
float zoom = 10.0f;
onView(withId(R.id.mapView)).perform(new AnimateCameraAction(mapboxMap,
CameraUpdateFactory.newLatLngZoom(new LatLng(), zoom)));
onView(withId(R.id.mapView)).perform(new AnimateCameraAction(mapboxMap, CameraUpdateFactory.zoomOut()));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoom - 1,
TestConstants.ZOOM_DELTA);
}
@Test
public void testAnimateToZoomBy() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
float zoom = 1.0f;
final float zoomBy = 2.45f;
onView(withId(R.id.mapView)).perform(new AnimateCameraAction(mapboxMap, CameraUpdateFactory.zoomBy(zoomBy)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoom + zoomBy,
TestConstants.ZOOM_DELTA);
}
@Test
public void testAnimateToZoomTo() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
final float zoomTo = 2.45f;
onView(withId(R.id.mapView)).perform(new AnimateCameraAction(mapboxMap, CameraUpdateFactory.zoomTo(zoomTo)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoomTo,
TestConstants.ZOOM_DELTA);
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
private class AnimateCameraAction implements ViewAction {
private MapboxMap mapboxMap;
private CameraUpdate cameraUpdate;
AnimateCameraAction(MapboxMap map, CameraUpdate update) {
mapboxMap = map;
cameraUpdate = update;
}
@Test
public void testAnimateToCameraPositionTarget() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO remove zoom #6474*/
float zoom = 1.0f;
LatLng moveTarget = new LatLng(1, 1);
CameraPosition initialPosition = new CameraPosition.Builder().target(new LatLng()).zoom(zoom).bearing(0).tilt(0).build();
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Default camera position should match default", cameraPosition, initialPosition);
onView(withId(R.id.mapView)).perform(new AnimateCameraAction(mapboxMap, CameraUpdateFactory.newLatLng(moveTarget)));
cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(), moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(), moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA);
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Test
public void testAnimateToCameraPositionTargetZoom() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final float moveZoom = 15.5f;
final LatLng moveTarget = new LatLng(1.0000000001, 1.0000000003);
onView(withId(R.id.mapView)).perform(new AnimateCameraAction(mapboxMap, CameraUpdateFactory.newLatLngZoom(moveTarget, moveZoom)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(), moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(), moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved zoom should match", cameraPosition.zoom, moveZoom, TestConstants.ZOOM_DELTA);
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Test
public void testAnimateToCameraPosition() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final LatLng moveTarget = new LatLng(1.0000000001, 1.0000000003);
final float moveZoom = 15.5f;
final float moveTilt = 45.5f;
final float moveBearing = 12.5f;
onView(withId(R.id.mapView)).perform(
new AnimateCameraAction(mapboxMap, CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(moveTarget)
.zoom(moveZoom)
.tilt(moveTilt)
.bearing(moveBearing)
.build()))
);
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(), moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(), moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved zoom should match", cameraPosition.zoom, moveZoom, TestConstants.ZOOM_DELTA);
assertEquals("Moved zoom should match", cameraPosition.tilt, moveTilt, TestConstants.TILT_DELTA);
assertEquals("Moved bearing should match", cameraPosition.bearing, moveBearing, TestConstants.BEARING_DELTA);
}
@Test
public void testAnimateToBounds() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final LatLng centerBounds = new LatLng(1, 1);
LatLng cornerOne = new LatLng();
LatLng cornerTwo = new LatLng(2, 2);
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(cornerOne);
builder.include(cornerTwo);
onView(withId(R.id.mapView)).perform(new AnimateCameraAction(mapboxMap, CameraUpdateFactory.newLatLngBounds(builder.build(), 0)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match center bounds",
cameraPosition.target.getLatitude(),
centerBounds.getLatitude(),
TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match center bounds",
cameraPosition.target.getLongitude(),
centerBounds.getLongitude(),
TestConstants.LAT_LNG_DELTA);
}
@Test
public void testAnimateToMoveBy() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final PointF centerPoint = mapboxMap.getProjection().toScreenLocation(mapboxMap.getCameraPosition().target);
final LatLng moveTarget = new LatLng(2, 2);
final PointF moveTargetPoint = mapboxMap.getProjection().toScreenLocation(moveTarget);
onView(withId(R.id.mapView)).perform(new AnimateCameraAction(mapboxMap, CameraUpdateFactory.scrollBy(
moveTargetPoint.x - centerPoint.x, moveTargetPoint.y - centerPoint.y)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(), moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA_LARGE);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(), moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA_LARGE);
}
@Test
public void testAnimateToZoomIn() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
float zoom = 1.0f;
onView(withId(R.id.mapView)).perform(new AnimateCameraAction(mapboxMap, CameraUpdateFactory.zoomIn()));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoom + 1, TestConstants.ZOOM_DELTA);
}
@Test
public void testAnimateToZoomOut() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
float zoom = 10.0f;
onView(withId(R.id.mapView)).perform(new AnimateCameraAction(mapboxMap, CameraUpdateFactory.newLatLngZoom(new LatLng(), zoom)));
onView(withId(R.id.mapView)).perform(new AnimateCameraAction(mapboxMap, CameraUpdateFactory.zoomOut()));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoom - 1, TestConstants.ZOOM_DELTA);
}
@Test
public void testAnimateToZoomBy() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
float zoom = 1.0f;
final float zoomBy = 2.45f;
onView(withId(R.id.mapView)).perform(new AnimateCameraAction(mapboxMap, CameraUpdateFactory.zoomBy(zoomBy)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoom + zoomBy, TestConstants.ZOOM_DELTA);
}
@Test
public void testAnimateToZoomTo() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
final float zoomTo = 2.45f;
onView(withId(R.id.mapView)).perform(new AnimateCameraAction(mapboxMap, CameraUpdateFactory.zoomTo(zoomTo)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoomTo, TestConstants.ZOOM_DELTA);
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
private class AnimateCameraAction implements ViewAction {
private MapboxMap mapboxMap;
private CameraUpdate cameraUpdate;
AnimateCameraAction(MapboxMap map, CameraUpdate update) {
mapboxMap = map;
cameraUpdate = update;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.animateCamera(cameraUpdate);
uiController.loopMainThreadForAtLeast(TestConstants.ANIMATION_TEST_TIME);
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.animateCamera(cameraUpdate);
uiController.loopMainThreadForAtLeast(TestConstants.ANIMATION_TEST_TIME);
}
}
}

View File

@@ -10,7 +10,6 @@ import android.view.View;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.camera.CameraUpdate;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.constants.MapboxConstants;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.geometry.LatLngBounds;
import com.mapbox.mapboxsdk.maps.MapboxMap;
@@ -33,206 +32,221 @@ import static org.junit.Assert.assertEquals;
public class CameraEaseTest {
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
public void testEaseToCameraPositionTarget() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO remove zoom #6474*/
float zoom = 1.0f;
LatLng moveTarget = new LatLng(1, 1);
CameraPosition initialPosition = new CameraPosition.Builder().target(
new LatLng()).zoom(zoom).bearing(0).tilt(0).build();
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Default camera position should match default", cameraPosition, initialPosition);
onView(withId(R.id.mapView)).perform(new EaseCameraAction(mapboxMap, CameraUpdateFactory.newLatLng(moveTarget)));
cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(),
moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(),
moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA);
}
@Test
public void testEaseToCameraPositionTargetZoom() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final float moveZoom = 15.5f;
final LatLng moveTarget = new LatLng(1.0000000001, 1.0000000003);
onView(withId(R.id.mapView)).perform(new EaseCameraAction(mapboxMap,
CameraUpdateFactory.newLatLngZoom(moveTarget, moveZoom)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(),
moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(),
moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved zoom should match", cameraPosition.zoom, moveZoom, TestConstants.ZOOM_DELTA);
}
@Test
public void testEaseToCameraPosition() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final LatLng moveTarget = new LatLng(1.0000000001, 1.0000000003);
final float moveZoom = 15.5f;
final float moveTilt = 45.5f;
final float moveBearing = 12.5f;
onView(withId(R.id.mapView)).perform(
new EaseCameraAction(mapboxMap, CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(moveTarget)
.zoom(moveZoom)
.tilt(moveTilt)
.bearing(moveBearing)
.build()))
);
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(),
moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(),
moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved zoom should match", cameraPosition.zoom, moveZoom, TestConstants.ZOOM_DELTA);
assertEquals("Moved zoom should match", cameraPosition.tilt, moveTilt, TestConstants.TILT_DELTA);
assertEquals("Moved bearing should match", cameraPosition.bearing, moveBearing, TestConstants.BEARING_DELTA);
}
@Test
public void testEaseToBounds() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final LatLng centerBounds = new LatLng(1, 1);
LatLng cornerOne = new LatLng();
LatLng cornerTwo = new LatLng(2, 2);
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(cornerOne);
builder.include(cornerTwo);
onView(withId(R.id.mapView)).perform(new EaseCameraAction(mapboxMap,
CameraUpdateFactory.newLatLngBounds(builder.build(), 0)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match center bounds",
cameraPosition.target.getLatitude(),
centerBounds.getLatitude(),
TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match center bounds",
cameraPosition.target.getLongitude(),
centerBounds.getLongitude(),
TestConstants.LAT_LNG_DELTA);
}
@Test
public void testEaseToMoveBy() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final PointF centerPoint = mapboxMap.getProjection().toScreenLocation(mapboxMap.getCameraPosition().target);
final LatLng moveTarget = new LatLng(2, 2);
final PointF moveTargetPoint = mapboxMap.getProjection().toScreenLocation(moveTarget);
onView(withId(R.id.mapView)).perform(new EaseCameraAction(mapboxMap, CameraUpdateFactory.scrollBy(
moveTargetPoint.x - centerPoint.x, moveTargetPoint.y - centerPoint.y)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(),
moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA_LARGE);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(),
moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA_LARGE);
}
@Test
public void testEaseToZoomIn() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
float zoom = 1.0f;
onView(withId(R.id.mapView)).perform(new EaseCameraAction(mapboxMap, CameraUpdateFactory.zoomIn()));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoom + 1,
TestConstants.ZOOM_DELTA);
}
@Test
public void testEaseToZoomOut() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
float zoom = 10.0f;
onView(withId(R.id.mapView)).perform(new EaseCameraAction(mapboxMap,
CameraUpdateFactory.newLatLngZoom(new LatLng(), zoom)));
onView(withId(R.id.mapView)).perform(new EaseCameraAction(mapboxMap, CameraUpdateFactory.zoomOut()));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", 9, cameraPosition.zoom, TestConstants.ZOOM_DELTA);
}
@Test
public void testEaseToZoomBy() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
float zoom = 1.0f;
final float zoomBy = 2.45f;
onView(withId(R.id.mapView)).perform(new EaseCameraAction(mapboxMap, CameraUpdateFactory.zoomBy(zoomBy)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoom + zoomBy,
TestConstants.ZOOM_DELTA);
}
@Test
public void testEaseToZoomTo() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
final float zoomTo = 2.45f;
onView(withId(R.id.mapView)).perform(new EaseCameraAction(mapboxMap, CameraUpdateFactory.zoomTo(zoomTo)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoomTo,
TestConstants.ZOOM_DELTA);
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
private class EaseCameraAction implements ViewAction {
private MapboxMap mapboxMap;
private CameraUpdate cameraUpdate;
EaseCameraAction(MapboxMap map, CameraUpdate update) {
mapboxMap = map;
cameraUpdate = update;
}
@Test
public void testEaseToCameraPositionTarget() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO remove zoom #6474*/
float zoom = 1.0f;
LatLng moveTarget = new LatLng(1, 1);
CameraPosition initialPosition = new CameraPosition.Builder().target(new LatLng()).zoom(zoom).bearing(0).tilt(0).build();
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Default camera position should match default", cameraPosition, initialPosition);
onView(withId(R.id.mapView)).perform(new EaseCameraAction(mapboxMap, CameraUpdateFactory.newLatLng(moveTarget)));
cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(), moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(), moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA);
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Test
public void testEaseToCameraPositionTargetZoom() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final float moveZoom = 15.5f;
final LatLng moveTarget = new LatLng(1.0000000001, 1.0000000003);
onView(withId(R.id.mapView)).perform(new EaseCameraAction(mapboxMap, CameraUpdateFactory.newLatLngZoom(moveTarget, moveZoom)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(), moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(), moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved zoom should match", cameraPosition.zoom, moveZoom, TestConstants.ZOOM_DELTA);
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Test
public void testEaseToCameraPosition() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final LatLng moveTarget = new LatLng(1.0000000001, 1.0000000003);
final float moveZoom = 15.5f;
final float moveTilt = 45.5f;
final float moveBearing = 12.5f;
onView(withId(R.id.mapView)).perform(
new EaseCameraAction(mapboxMap, CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(moveTarget)
.zoom(moveZoom)
.tilt(moveTilt)
.bearing(moveBearing)
.build()))
);
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(), moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(), moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved zoom should match", cameraPosition.zoom, moveZoom, TestConstants.ZOOM_DELTA);
assertEquals("Moved zoom should match", cameraPosition.tilt, moveTilt, TestConstants.TILT_DELTA);
assertEquals("Moved bearing should match", cameraPosition.bearing, moveBearing, TestConstants.BEARING_DELTA);
}
@Test
public void testEaseToBounds() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final LatLng centerBounds = new LatLng(1, 1);
LatLng cornerOne = new LatLng();
LatLng cornerTwo = new LatLng(2, 2);
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(cornerOne);
builder.include(cornerTwo);
onView(withId(R.id.mapView)).perform(new EaseCameraAction(mapboxMap, CameraUpdateFactory.newLatLngBounds(builder.build(), 0)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match center bounds",
cameraPosition.target.getLatitude(),
centerBounds.getLatitude(),
TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match center bounds",
cameraPosition.target.getLongitude(),
centerBounds.getLongitude(),
TestConstants.LAT_LNG_DELTA);
}
@Test
public void testEaseToMoveBy() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final PointF centerPoint = mapboxMap.getProjection().toScreenLocation(mapboxMap.getCameraPosition().target);
final LatLng moveTarget = new LatLng(2, 2);
final PointF moveTargetPoint = mapboxMap.getProjection().toScreenLocation(moveTarget);
onView(withId(R.id.mapView)).perform(new EaseCameraAction(mapboxMap, CameraUpdateFactory.scrollBy(
moveTargetPoint.x - centerPoint.x, moveTargetPoint.y - centerPoint.y)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(), moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA_LARGE);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(), moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA_LARGE);
}
@Test
public void testEaseToZoomIn() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
float zoom = 1.0f;
onView(withId(R.id.mapView)).perform(new EaseCameraAction(mapboxMap, CameraUpdateFactory.zoomIn()));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoom + 1, TestConstants.ZOOM_DELTA);
}
@Test
public void testEaseToZoomOut() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
float zoom = 10.0f;
onView(withId(R.id.mapView)).perform(new EaseCameraAction(mapboxMap, CameraUpdateFactory.newLatLngZoom(new LatLng(), zoom)));
onView(withId(R.id.mapView)).perform(new EaseCameraAction(mapboxMap, CameraUpdateFactory.zoomOut()));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", 9, cameraPosition.zoom, TestConstants.ZOOM_DELTA);
}
@Test
public void testEaseToZoomBy() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
float zoom = 1.0f;
final float zoomBy = 2.45f;
onView(withId(R.id.mapView)).perform(new EaseCameraAction(mapboxMap, CameraUpdateFactory.zoomBy(zoomBy)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoom + zoomBy, TestConstants.ZOOM_DELTA);
}
@Test
public void testEaseToZoomTo() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
final float zoomTo = 2.45f;
onView(withId(R.id.mapView)).perform(new EaseCameraAction(mapboxMap, CameraUpdateFactory.zoomTo(zoomTo)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoomTo, TestConstants.ZOOM_DELTA);
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
private class EaseCameraAction implements ViewAction {
private MapboxMap mapboxMap;
private CameraUpdate cameraUpdate;
EaseCameraAction(MapboxMap map, CameraUpdate update) {
mapboxMap = map;
cameraUpdate = update;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.easeCamera(cameraUpdate);
uiController.loopMainThreadForAtLeast(TestConstants.ANIMATION_TEST_TIME);
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.easeCamera(cameraUpdate);
uiController.loopMainThreadForAtLeast(TestConstants.ANIMATION_TEST_TIME);
}
}
}

View File

@@ -1,167 +0,0 @@
package com.mapbox.mapboxsdk.testapp.camera;
import android.support.test.espresso.Espresso;
import android.support.test.espresso.UiController;
import android.support.test.espresso.ViewAction;
import android.support.test.rule.ActivityTestRule;
import android.view.View;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.MapViewUtils;
import com.mapbox.mapboxsdk.testapp.R;
import com.mapbox.mapboxsdk.testapp.activity.espresso.EspressoTestActivity;
import com.mapbox.mapboxsdk.testapp.utils.OnMapReadyIdlingResource;
import com.mapbox.mapboxsdk.testapp.utils.TestConstants;
import com.mapbox.mapboxsdk.testapp.utils.ViewUtils;
import org.hamcrest.Matcher;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static org.junit.Assert.assertEquals;
/**
* Tests camera transformations that aren't part of our public API
*/
public class CameraInternalAPITest {
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
private OnMapReadyIdlingResource idlingResource;
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
public void testBearing() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
EspressoTestActivity activity = rule.getActivity();
MapboxMap mapboxMap = activity.getMapboxMap();
CameraPosition initialPosition = new CameraPosition.Builder().target(new LatLng()).zoom(1).bearing(0).tilt(0).build();
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Default camera position should match default", cameraPosition, initialPosition);
onView(withId(R.id.mapView)).perform(new BearingAction(mapboxMap));
assertEquals("Bearing should match", 45.1f, MapViewUtils.getDirection(mapboxMap), TestConstants.BEARING_DELTA);
}
@Test
public void testTilt() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
EspressoTestActivity activity = rule.getActivity();
MapboxMap mapboxMap = activity.getMapboxMap();
CameraPosition initialPosition = new CameraPosition.Builder().target(new LatLng()).zoom(1).bearing(0).tilt(0).build();
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Default camera position should match default", cameraPosition, initialPosition);
onView(withId(R.id.mapView)).perform(new TiltAction(mapboxMap));
assertEquals("Tilt should match", 40.0f, MapViewUtils.getTilt(mapboxMap), TestConstants.TILT_DELTA);
}
@Test
public void testLatLng() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
EspressoTestActivity activity = rule.getActivity();
MapboxMap mapboxMap = activity.getMapboxMap();
CameraPosition initialPosition = new CameraPosition.Builder().target(new LatLng()).zoom(1).bearing(0).tilt(0).build();
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Default camera position should match default", cameraPosition, initialPosition);
onView(withId(R.id.mapView)).perform(new LatLngAction(mapboxMap));
LatLng centerCoordinate = MapViewUtils.getLatLng(mapboxMap);
assertEquals("Latitude should match", 1.1f, centerCoordinate.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Longitude should match", 2.2f, centerCoordinate.getLongitude(), TestConstants.LAT_LNG_DELTA);
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
private class BearingAction implements ViewAction {
private MapboxMap mapboxMap;
BearingAction(MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
MapViewUtils.setDirection(mapboxMap, -45.1f);
}
}
private class TiltAction implements ViewAction {
private MapboxMap mapboxMap;
TiltAction(MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
MapViewUtils.setTilt(mapboxMap, 40.0f);
}
}
private class LatLngAction implements ViewAction {
private MapboxMap mapboxMap;
LatLngAction(MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
MapViewUtils.setLatLng(mapboxMap, new LatLng(1.1, 2.2));
}
}
}

View File

@@ -0,0 +1,169 @@
package com.mapbox.mapboxsdk.testapp.camera;
import android.support.test.espresso.Espresso;
import android.support.test.espresso.UiController;
import android.support.test.espresso.ViewAction;
import android.support.test.rule.ActivityTestRule;
import android.view.View;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapViewUtils;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.testapp.R;
import com.mapbox.mapboxsdk.testapp.activity.espresso.EspressoTestActivity;
import com.mapbox.mapboxsdk.testapp.utils.OnMapReadyIdlingResource;
import com.mapbox.mapboxsdk.testapp.utils.TestConstants;
import com.mapbox.mapboxsdk.testapp.utils.ViewUtils;
import org.hamcrest.Matcher;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static org.junit.Assert.assertEquals;
/**
* Tests camera transformations that aren't part of our public API
*/
public class CameraInternalApiTest {
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
private OnMapReadyIdlingResource idlingResource;
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
public void testBearing() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
EspressoTestActivity activity = rule.getActivity();
MapboxMap mapboxMap = activity.getMapboxMap();
CameraPosition initialPosition = new
CameraPosition.Builder().target(new LatLng()).zoom(1).bearing(0).tilt(0).build();
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Default camera position should match default", cameraPosition, initialPosition);
onView(withId(R.id.mapView)).perform(new BearingAction(mapboxMap));
assertEquals("Bearing should match", 45.1f, MapViewUtils.getDirection(mapboxMap), TestConstants.BEARING_DELTA);
}
@Test
public void testTilt() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
EspressoTestActivity activity = rule.getActivity();
MapboxMap mapboxMap = activity.getMapboxMap();
CameraPosition initialPosition = new CameraPosition.Builder().target(
new LatLng()).zoom(1).bearing(0).tilt(0).build();
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Default camera position should match default", cameraPosition, initialPosition);
onView(withId(R.id.mapView)).perform(new TiltAction(mapboxMap));
assertEquals("Tilt should match", 40.0f, MapViewUtils.getTilt(mapboxMap), TestConstants.TILT_DELTA);
}
@Test
public void testLatLng() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
EspressoTestActivity activity = rule.getActivity();
MapboxMap mapboxMap = activity.getMapboxMap();
CameraPosition initialPosition = new CameraPosition.Builder().target(
new LatLng()).zoom(1).bearing(0).tilt(0).build();
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Default camera position should match default", cameraPosition, initialPosition);
onView(withId(R.id.mapView)).perform(new LatLngAction(mapboxMap));
LatLng centerCoordinate = MapViewUtils.getLatLng(mapboxMap);
assertEquals("Latitude should match", 1.1f, centerCoordinate.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Longitude should match", 2.2f, centerCoordinate.getLongitude(), TestConstants.LAT_LNG_DELTA);
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
private class BearingAction implements ViewAction {
private MapboxMap mapboxMap;
BearingAction(MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
MapViewUtils.setDirection(mapboxMap, -45.1f);
}
}
private class TiltAction implements ViewAction {
private MapboxMap mapboxMap;
TiltAction(MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
MapViewUtils.setTilt(mapboxMap, 40.0f);
}
}
private class LatLngAction implements ViewAction {
private MapboxMap mapboxMap;
LatLngAction(MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
MapViewUtils.setLatLng(mapboxMap, new LatLng(1.1, 2.2));
}
}
}

View File

@@ -29,209 +29,224 @@ import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CameraMoveTest {
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
private OnMapReadyIdlingResource idlingResource;
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
private OnMapReadyIdlingResource idlingResource;
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
public void testMoveToCameraPositionTarget() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO remove zoom #6474*/
float zoom = 1.0f;
LatLng moveTarget = new LatLng(1, 1);
CameraPosition initialPosition = new CameraPosition.Builder().target(
new LatLng()).zoom(zoom).bearing(0).tilt(0).build();
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Default camera position should match default", cameraPosition, initialPosition);
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap, CameraUpdateFactory.newLatLng(moveTarget)));
cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(),
moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(),
moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA);
}
@Test
public void testMoveToCameraPositionTargetZoom() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final float moveZoom = 15.5f;
final LatLng moveTarget = new LatLng(1.0000000001, 1.0000000003);
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap,
CameraUpdateFactory.newLatLngZoom(moveTarget, moveZoom)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(),
moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(),
moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved zoom should match", cameraPosition.zoom, moveZoom, TestConstants.ZOOM_DELTA);
}
@Test
public void testMoveToCameraPosition() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final LatLng moveTarget = new LatLng(1.0000000001, 1.0000000003);
final float moveZoom = 15.5f;
final float moveTilt = 45.5f;
final float moveBearing = 12.5f;
onView(withId(R.id.mapView)).perform(
new MoveCameraAction(mapboxMap, CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(moveTarget)
.zoom(moveZoom)
.tilt(moveTilt)
.bearing(moveBearing)
.build()))
);
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(),
moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(),
moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved zoom should match", cameraPosition.zoom, moveZoom, TestConstants.ZOOM_DELTA);
assertEquals("Moved zoom should match", cameraPosition.tilt, moveTilt, TestConstants.TILT_DELTA);
assertEquals("Moved bearing should match", cameraPosition.bearing, moveBearing, TestConstants.BEARING_DELTA);
}
@Test
public void testMoveToBounds() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final LatLng centerBounds = new LatLng(1, 1);
LatLng cornerOne = new LatLng();
LatLng cornerTwo = new LatLng(2, 2);
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(cornerOne);
builder.include(cornerTwo);
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap,
CameraUpdateFactory.newLatLngBounds(builder.build(), 0)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match center bounds",
cameraPosition.target.getLatitude(),
centerBounds.getLatitude(),
TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match center bounds",
cameraPosition.target.getLongitude(),
centerBounds.getLongitude(),
TestConstants.LAT_LNG_DELTA);
}
@Test
public void testMoveToMoveBy() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final PointF centerPoint = mapboxMap.getProjection().toScreenLocation(mapboxMap.getCameraPosition().target);
final LatLng moveTarget = new LatLng(2, 2);
final PointF moveTargetPoint = mapboxMap.getProjection().toScreenLocation(moveTarget);
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap, CameraUpdateFactory.scrollBy(
moveTargetPoint.x - centerPoint.x, moveTargetPoint.y - centerPoint.y)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(),
moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA_LARGE);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(),
moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA_LARGE);
}
@Test
public void testMoveToZoomIn() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
float zoom = 1.0f;
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap, CameraUpdateFactory.zoomIn()));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoom + 1,
TestConstants.ZOOM_DELTA);
}
@Test
public void testMoveToZoomOut() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
float zoom = 10.0f;
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap,
CameraUpdateFactory.newLatLngZoom(new LatLng(), zoom)));
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap, CameraUpdateFactory.zoomOut()));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoom - 1,
TestConstants.ZOOM_DELTA);
}
@Test
public void testMoveToZoomBy() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
float zoom = 1.0f;
final float zoomBy = 2.45f;
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap, CameraUpdateFactory.zoomBy(zoomBy)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoom + zoomBy,
TestConstants.ZOOM_DELTA);
}
@Test
public void testMoveToZoomTo() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
final float zoomTo = 2.45f;
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap, CameraUpdateFactory.zoomTo(zoomTo)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoomTo,
TestConstants.ZOOM_DELTA);
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
private class MoveCameraAction implements ViewAction {
private MapboxMap mapboxMap;
private CameraUpdate cameraUpdate;
MoveCameraAction(MapboxMap map, CameraUpdate update) {
mapboxMap = map;
cameraUpdate = update;
}
@Test
public void testMoveToCameraPositionTarget() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO remove zoom #6474*/
float zoom = 1.0f;
LatLng moveTarget = new LatLng(1, 1);
CameraPosition initialPosition = new CameraPosition.Builder().target(new LatLng()).zoom(zoom).bearing(0).tilt(0).build();
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Default camera position should match default", cameraPosition, initialPosition);
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap, CameraUpdateFactory.newLatLng(moveTarget)));
cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(), moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(), moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA);
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Test
public void testMoveToCameraPositionTargetZoom() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final float moveZoom = 15.5f;
final LatLng moveTarget = new LatLng(1.0000000001, 1.0000000003);
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap, CameraUpdateFactory.newLatLngZoom(moveTarget, moveZoom)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(), moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(), moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved zoom should match", cameraPosition.zoom, moveZoom, TestConstants.ZOOM_DELTA);
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Test
public void testMoveToCameraPosition() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final LatLng moveTarget = new LatLng(1.0000000001, 1.0000000003);
final float moveZoom = 15.5f;
final float moveTilt = 45.5f;
final float moveBearing = 12.5f;
onView(withId(R.id.mapView)).perform(
new MoveCameraAction(mapboxMap, CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(moveTarget)
.zoom(moveZoom)
.tilt(moveTilt)
.bearing(moveBearing)
.build()))
);
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(), moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(), moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA);
assertEquals("Moved zoom should match", cameraPosition.zoom, moveZoom, TestConstants.ZOOM_DELTA);
assertEquals("Moved zoom should match", cameraPosition.tilt, moveTilt, TestConstants.TILT_DELTA);
assertEquals("Moved bearing should match", cameraPosition.bearing, moveBearing, TestConstants.BEARING_DELTA);
}
@Test
public void testMoveToBounds() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final LatLng centerBounds = new LatLng(1, 1);
LatLng cornerOne = new LatLng();
LatLng cornerTwo = new LatLng(2, 2);
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(cornerOne);
builder.include(cornerTwo);
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap, CameraUpdateFactory.newLatLngBounds(builder.build(), 0)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match center bounds",
cameraPosition.target.getLatitude(),
centerBounds.getLatitude(),
TestConstants.LAT_LNG_DELTA);
assertEquals("Moved camera position longitude should match center bounds",
cameraPosition.target.getLongitude(),
centerBounds.getLongitude(),
TestConstants.LAT_LNG_DELTA);
}
@Test
public void testMoveToMoveBy() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
final PointF centerPoint = mapboxMap.getProjection().toScreenLocation(mapboxMap.getCameraPosition().target);
final LatLng moveTarget = new LatLng(2, 2);
final PointF moveTargetPoint = mapboxMap.getProjection().toScreenLocation(moveTarget);
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap, CameraUpdateFactory.scrollBy(
moveTargetPoint.x - centerPoint.x, moveTargetPoint.y - centerPoint.y)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera position latitude should match", cameraPosition.target.getLatitude(), moveTarget.getLatitude(), TestConstants.LAT_LNG_DELTA_LARGE);
assertEquals("Moved camera position longitude should match", cameraPosition.target.getLongitude(), moveTarget.getLongitude(), TestConstants.LAT_LNG_DELTA_LARGE);
}
@Test
public void testMoveToZoomIn() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
float zoom = 1.0f;
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap, CameraUpdateFactory.zoomIn()));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoom + 1, TestConstants.ZOOM_DELTA);
}
@Test
public void testMoveToZoomOut() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
float zoom = 10.0f;
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap, CameraUpdateFactory.newLatLngZoom(new LatLng(), zoom)));
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap, CameraUpdateFactory.zoomOut()));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoom - 1, TestConstants.ZOOM_DELTA);
}
@Test
public void testMoveToZoomBy() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
float zoom = 1.0f;
final float zoomBy = 2.45f;
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap, CameraUpdateFactory.zoomBy(zoomBy)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoom + zoomBy, TestConstants.ZOOM_DELTA);
}
@Test
public void testMoveToZoomTo() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
final MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
/*TODO fix zoom #6474*/
final float zoomTo = 2.45f;
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap, CameraUpdateFactory.zoomTo(zoomTo)));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Moved camera zoom should match moved camera zoom", cameraPosition.zoom, zoomTo, TestConstants.ZOOM_DELTA);
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
private class MoveCameraAction implements ViewAction {
private MapboxMap mapboxMap;
private CameraUpdate cameraUpdate;
MoveCameraAction(MapboxMap map, CameraUpdate update) {
mapboxMap = map;
cameraUpdate = update;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.moveCamera(cameraUpdate);
uiController.loopMainThreadForAtLeast(100);
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.moveCamera(cameraUpdate);
uiController.loopMainThreadForAtLeast(100);
}
}
}

View File

@@ -29,32 +29,33 @@ import static org.hamcrest.Matchers.not;
*/
public class QueryRenderedFeaturesBoxCountTest {
@Rule
public final ActivityTestRule<QueryRenderedFeaturesBoxCountActivity> rule = new ActivityTestRule<>(QueryRenderedFeaturesBoxCountActivity.class);
@Rule
public final ActivityTestRule<QueryRenderedFeaturesBoxCountActivity> rule =
new ActivityTestRule<>(QueryRenderedFeaturesBoxCountActivity.class);
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
@Ignore
public void testCountFeatures() {
// click on box to query map
onView(withId(R.id.selection_box)).perform(click());
@Test
@Ignore
public void testCountFeatures() {
// click on box to query map
onView(withId(R.id.selection_box)).perform(click());
// validate if toast is shown
onView(withText("149 features in box"))
.inRoot(withDecorView(not(is(rule.getActivity().getWindow().getDecorView()))))
.check(matches(isDisplayed()));
}
// validate if toast is shown
onView(withText("149 features in box"))
.inRoot(withDecorView(not(is(rule.getActivity().getWindow().getDecorView()))))
.check(matches(isDisplayed()));
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
}

View File

@@ -34,47 +34,48 @@ import static org.hamcrest.Matchers.not;
*/
public class QueryRenderedFeaturesHighlightTest {
@Rule
public final ActivityTestRule<QueryRenderedFeaturesBoxHighlightActivity> rule = new ActivityTestRule<>(QueryRenderedFeaturesBoxHighlightActivity.class);
@Rule
public final ActivityTestRule<QueryRenderedFeaturesBoxHighlightActivity> rule =
new ActivityTestRule<>(QueryRenderedFeaturesBoxHighlightActivity.class);
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
@Ignore
public void testCountFeatures() {
// click on box to query map
onView(withId(R.id.selection_box)).perform(click());
@Test
@Ignore
public void testCountFeatures() {
// click on box to query map
onView(withId(R.id.selection_box)).perform(click());
// validate if toast is shown
onView(withText("50 features in box"))
.inRoot(withDecorView(not(is(rule.getActivity().getWindow().getDecorView()))))
.check(matches(isDisplayed()));
}
// validate if toast is shown
onView(withText("50 features in box"))
.inRoot(withDecorView(not(is(rule.getActivity().getWindow().getDecorView()))))
.check(matches(isDisplayed()));
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
private static ViewAction clickXY(final float x, final float y) {
return new GeneralClickAction(
Tap.SINGLE,
new CoordinatesProvider() {
@Override
public float[] calculateCoordinates(View view) {
final int[] screenPos = new int[2];
view.getLocationOnScreen(screenPos);
final float screenX = screenPos[0] + x;
final float screenY = screenPos[1] + y;
return new float[]{screenX, screenY};
}
},
Press.FINGER);
}
private static ViewAction clickXY(final float x, final float y) {
return new GeneralClickAction(
Tap.SINGLE,
new CoordinatesProvider() {
@Override
public float[] calculateCoordinates(View view) {
final int[] screenPos = new int[2];
view.getLocationOnScreen(screenPos);
final float screenX = screenPos[0] + x;
final float screenY = screenPos[1] + y;
return new float[] {screenX, screenY};
}
},
Press.FINGER);
}
}

View File

@@ -33,45 +33,46 @@ import static android.support.test.espresso.matcher.ViewMatchers.withText;
*/
public class QueryRenderedFeaturesPropertiesTest {
@Rule
public final ActivityTestRule<QueryRenderedFeaturesPropertiesActivity> rule = new ActivityTestRule<>(QueryRenderedFeaturesPropertiesActivity.class);
@Rule
public final ActivityTestRule<QueryRenderedFeaturesPropertiesActivity> rule =
new ActivityTestRule<>(QueryRenderedFeaturesPropertiesActivity.class);
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
@Ignore
public void testCountFeatures() {
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
LatLng centerScreen = mapboxMap.getCameraPosition().target;
PointF centerPixel = mapboxMap.getProjection().toScreenLocation(centerScreen);
onView(withId(R.id.mapView)).perform(clickXY(centerPixel.x, centerPixel.y));
onView(withText("Found 4 features")).check(matches(isDisplayed()));
}
@Test
@Ignore
public void testCountFeatures() {
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
LatLng centerScreen = mapboxMap.getCameraPosition().target;
PointF centerPixel = mapboxMap.getProjection().toScreenLocation(centerScreen);
onView(withId(R.id.mapView)).perform(clickXY(centerPixel.x, centerPixel.y));
onView(withText("Found 4 features")).check(matches(isDisplayed()));
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
private static ViewAction clickXY(final float x, final float y) {
return new GeneralClickAction(
Tap.SINGLE,
new CoordinatesProvider() {
@Override
public float[] calculateCoordinates(View view) {
final int[] screenPos = new int[2];
view.getLocationOnScreen(screenPos);
final float screenX = screenPos[0] + x;
final float screenY = screenPos[1] + y;
return new float[]{screenX, screenY};
}
},
Press.FINGER);
}
private static ViewAction clickXY(final float x, final float y) {
return new GeneralClickAction(
Tap.SINGLE,
new CoordinatesProvider() {
@Override
public float[] calculateCoordinates(View view) {
final int[] screenPos = new int[2];
view.getLocationOnScreen(screenPos);
final float screenX = screenPos[0] + x;
final float screenY = screenPos[1] + y;
return new float[] {screenX, screenY};
}
},
Press.FINGER);
}
}

View File

@@ -29,33 +29,34 @@ import static org.hamcrest.Matchers.not;
*/
public class QueryRenderedSymbolBoxCountTest {
@Rule
public final ActivityTestRule<QueryRenderedFeaturesBoxSymbolCountActivity> rule = new ActivityTestRule<>(QueryRenderedFeaturesBoxSymbolCountActivity.class);
@Rule
public final ActivityTestRule<QueryRenderedFeaturesBoxSymbolCountActivity> rule =
new ActivityTestRule<>(QueryRenderedFeaturesBoxSymbolCountActivity.class);
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
@Ignore
public void testCountSymbols() {
// click on box to query map
onView(withId(R.id.selection_box)).perform(click());
@Test
@Ignore
public void testCountSymbols() {
// click on box to query map
onView(withId(R.id.selection_box)).perform(click());
// validate if toast is shown
onView(withText("2 features in box"))
.inRoot(withDecorView(not(is(rule.getActivity().getWindow().getDecorView()))))
.check(matches(isDisplayed()));
}
// validate if toast is shown
onView(withText("2 features in box"))
.inRoot(withDecorView(not(is(rule.getActivity().getWindow().getDecorView()))))
.check(matches(isDisplayed()));
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
}

View File

@@ -37,120 +37,120 @@ import static org.hamcrest.core.IsNot.not;
public class AttributionTest {
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
private String[] dialogTexts;
private String[] dialogLinks;
private String[] dialogTexts;
private String[] dialogLinks;
@Before
public void beforeTest() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
Intents.init();
dialogTexts = rule.getActivity().getResources().getStringArray(R.array.mapbox_attribution_names);
dialogLinks = rule.getActivity().getResources().getStringArray(R.array.mapbox_attribution_links);
@Before
public void beforeTest() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
Intents.init();
dialogTexts = rule.getActivity().getResources().getStringArray(R.array.mapbox_attribution_names);
dialogLinks = rule.getActivity().getResources().getStringArray(R.array.mapbox_attribution_links);
}
@Test
public void testDisabled() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
// Default
onView(withId(R.id.attributionView)).check(matches(isDisplayed()));
// Disabled
onView(withId(R.id.attributionView))
.perform(new DisableAction(mapboxMap))
.check(matches(not(isDisplayed())));
}
@Test
public void testMapboxLink() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
// click on View to open dialog
onView(withId(R.id.attributionView)).perform(click());
onView(withText(R.string.mapbox_attributionsDialogTitle)).check(matches(isDisplayed()));
// click on link and validate browser opening
Matcher<Intent> expectedIntent = allOf(hasAction(Intent.ACTION_VIEW), hasData(Uri.parse(dialogLinks[0])));
intending(expectedIntent).respondWith(new Instrumentation.ActivityResult(0, null));
onView(withText(dialogTexts[0])).perform(click());
intended(expectedIntent);
}
@Test
public void testOpenStreetMapLink() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
// click on View to open dialog
onView(withId(R.id.attributionView)).perform(click());
onView(withText(R.string.mapbox_attributionsDialogTitle)).check(matches(isDisplayed()));
// click on link and validate browser opening
Matcher<Intent> expectedIntent = allOf(hasAction(Intent.ACTION_VIEW), hasData(Uri.parse(dialogLinks[1])));
intending(expectedIntent).respondWith(new Instrumentation.ActivityResult(0, null));
onView(withText(dialogTexts[1])).perform(click());
}
@Test
public void testImproveMapLink() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
// click on View to open dialog
onView(withId(R.id.attributionView)).perform(click());
onView(withText(R.string.mapbox_attributionsDialogTitle)).check(matches(isDisplayed()));
// click on Mapbox link and validate browser opening
Matcher<Intent> expectedIntent = allOf(hasAction(Intent.ACTION_VIEW), hasData(Uri.parse(dialogLinks[3])));
intending(expectedIntent).respondWith(new Instrumentation.ActivityResult(0, null));
onView(withText(dialogTexts[3])).perform(click());
}
@Test
public void testTelemetryDialog() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
// click on View to open dialog
onView(withId(R.id.attributionView)).perform(click());
onView(withText(R.string.mapbox_attributionsDialogTitle)).check(matches(isDisplayed()));
// click on item to open second dialog
onView(withText(dialogTexts[3])).perform(click());
onView(withText(R.string.mapbox_attributionTelemetryTitle)).check(matches(isDisplayed()));
}
@After
public void afterTest() {
Intents.release();
Espresso.unregisterIdlingResources(idlingResource);
}
private class DisableAction implements ViewAction {
private MapboxMap mapboxMap;
DisableAction(MapboxMap map) {
mapboxMap = map;
}
@Test
public void testDisabled() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
// Default
onView(withId(R.id.attributionView)).check(matches(isDisplayed()));
// Disabled
onView(withId(R.id.attributionView))
.perform(new DisableAction(mapboxMap))
.check(matches(not(isDisplayed())));
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Test
public void testMapboxLink() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
// click on View to open dialog
onView(withId(R.id.attributionView)).perform(click());
onView(withText(R.string.mapbox_attributionsDialogTitle)).check(matches(isDisplayed()));
// click on link and validate browser opening
Matcher<Intent> expectedIntent = allOf(hasAction(Intent.ACTION_VIEW), hasData(Uri.parse(dialogLinks[0])));
intending(expectedIntent).respondWith(new Instrumentation.ActivityResult(0, null));
onView(withText(dialogTexts[0])).perform(click());
intended(expectedIntent);
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Test
public void testOpenStreetMapLink() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
// click on View to open dialog
onView(withId(R.id.attributionView)).perform(click());
onView(withText(R.string.mapbox_attributionsDialogTitle)).check(matches(isDisplayed()));
// click on link and validate browser opening
Matcher<Intent> expectedIntent = allOf(hasAction(Intent.ACTION_VIEW), hasData(Uri.parse(dialogLinks[1])));
intending(expectedIntent).respondWith(new Instrumentation.ActivityResult(0, null));
onView(withText(dialogTexts[1])).perform(click());
}
@Test
public void testImproveMapLink() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
// click on View to open dialog
onView(withId(R.id.attributionView)).perform(click());
onView(withText(R.string.mapbox_attributionsDialogTitle)).check(matches(isDisplayed()));
// click on Mapbox link and validate browser opening
Matcher<Intent> expectedIntent = allOf(hasAction(Intent.ACTION_VIEW), hasData(Uri.parse(dialogLinks[3])));
intending(expectedIntent).respondWith(new Instrumentation.ActivityResult(0, null));
onView(withText(dialogTexts[3])).perform(click());
}
@Test
public void testTelemetryDialog() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
// click on View to open dialog
onView(withId(R.id.attributionView)).perform(click());
onView(withText(R.string.mapbox_attributionsDialogTitle)).check(matches(isDisplayed()));
// click on item to open second dialog
onView(withText(dialogTexts[3])).perform(click());
onView(withText(R.string.mapbox_attributionTelemetryTitle)).check(matches(isDisplayed()));
}
@After
public void afterTest() {
Intents.release();
Espresso.unregisterIdlingResources(idlingResource);
}
private class DisableAction implements ViewAction {
private MapboxMap mapboxMap;
DisableAction(MapboxMap map) {
mapboxMap = map;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.getUiSettings().setAttributionEnabled(false);
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.getUiSettings().setAttributionEnabled(false);
}
}
}

View File

@@ -34,120 +34,120 @@ import static org.junit.Assert.assertEquals;
public class CompassViewTest {
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
public void testDefault() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
onView(withId(R.id.compassView)).check(matches(not(isDisplayed())));
}
@Test
public void testVisible() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap,
CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.bearing(45)
.zoom(1)
.target(new LatLng())
.build()
)
)
);
onView(withId(R.id.compassView)).check(matches(isDisplayed()));
}
@Test
@Ignore // 10-31-2016 click action is not working
public void testClick() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap,
CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.bearing(45)
.zoom(1)
.target(new LatLng())
.build()
)
)
);
onView(withId(R.id.compassView)).perform(click());
onView(withId(R.id.mapView)).perform(new WaitAction(3000));
onView(withId(R.id.compassView)).check(matches(not(isDisplayed())));
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Camera bearing should face north, ", 0, cameraPosition.bearing, TestConstants.BEARING_DELTA);
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
private class WaitAction implements ViewAction {
private long waitTime;
WaitAction(long waitTime) {
this.waitTime = waitTime;
}
@Test
public void testDefault() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
onView(withId(R.id.compassView)).check(matches(not(isDisplayed())));
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Test
public void testVisible(){
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap,
CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.bearing(45)
.zoom(1)
.target(new LatLng())
.build()
)
)
);
onView(withId(R.id.compassView)).check(matches(isDisplayed()));
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Test
@Ignore // 10-31-2016 click action is not working
public void testClick() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
@Override
public void perform(UiController uiController, View view) {
uiController.loopMainThreadForAtLeast(waitTime);
}
}
onView(withId(R.id.mapView)).perform(new MoveCameraAction(mapboxMap,
CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.bearing(45)
.zoom(1)
.target(new LatLng())
.build()
)
)
);
private class MoveCameraAction implements ViewAction {
onView(withId(R.id.compassView)).perform(click());
onView(withId(R.id.mapView)).perform(new WaitAction(3000));
onView(withId(R.id.compassView)).check(matches(not(isDisplayed())));
private MapboxMap mapboxMap;
private CameraUpdate cameraUpdate;
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
assertEquals("Camera bearing should face north, ", 0, cameraPosition.bearing, TestConstants.BEARING_DELTA);
MoveCameraAction(MapboxMap map, CameraUpdate update) {
mapboxMap = map;
cameraUpdate = update;
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
private class WaitAction implements ViewAction {
private long waitTime;
WaitAction(long waitTime) {
this.waitTime = waitTime;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
uiController.loopMainThreadForAtLeast(waitTime);
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
private class MoveCameraAction implements ViewAction {
private MapboxMap mapboxMap;
private CameraUpdate cameraUpdate;
MoveCameraAction(MapboxMap map, CameraUpdate update) {
mapboxMap = map;
cameraUpdate = update;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.moveCamera(cameraUpdate);
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.moveCamera(cameraUpdate);
}
}
}

View File

@@ -26,59 +26,59 @@ import static org.hamcrest.Matchers.not;
public class LogoTest {
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
public void testDefault() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
onView(withId(R.id.logoView)).check(matches(isDisplayed()));
}
@Test
public void testDisabled() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
onView(withId(R.id.logoView))
.perform(new DisableAction(mapboxMap))
.check(matches(not(isDisplayed())));
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
private class DisableAction implements ViewAction {
private MapboxMap mapboxMap;
DisableAction(MapboxMap map) {
mapboxMap = map;
}
@Test
public void testDefault() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
onView(withId(R.id.logoView)).check(matches(isDisplayed()));
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Test
public void testDisabled() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
onView(withId(R.id.logoView))
.perform(new DisableAction(mapboxMap))
.check(matches(not(isDisplayed())));
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@After
public void unregisterIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
private class DisableAction implements ViewAction {
private MapboxMap mapboxMap;
DisableAction(MapboxMap map) {
mapboxMap = map;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.getUiSettings().setLogoEnabled(false);
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.getUiSettings().setLogoEnabled(false);
}
}
}

View File

@@ -51,192 +51,196 @@ import static org.hamcrest.Matchers.not;
*/
public class MyLocationViewTest {
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
@Rule
public final ActivityTestRule<EspressoTestActivity> rule = new ActivityTestRule<>(EspressoTestActivity.class);
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
@Before
public void beforeTest() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
@Before
public void beforeTest() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
@Ignore // requires runtime permissions, disabled for CI
public void testEnabled() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
onView(withId(R.id.userLocationView)).check(matches(not(isDisplayed())));
onView(withId(R.id.mapView)).perform(new ToggleLocationAction(mapboxMap, true));
onView(withId(R.id.userLocationView)).check(matches(isDisplayed()));
onView(withId(R.id.mapView)).perform(new ToggleLocationAction(mapboxMap, false));
onView(withId(R.id.userLocationView)).check(matches(not(isDisplayed())));
}
@Test
@Ignore
// requires runtime permissions, disabled for CI + issue with android.support.test.espresso.AppNotIdleException:
// Looped for 5049 iterations over 60 SECONDS.
public void testTracking() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
onView(withId(R.id.userLocationView)).check(matches(not(isDisplayed())));
onView(withId(R.id.mapView)).perform(new EnableLocationTrackingAction(mapboxMap));
onView(withId(R.id.userLocationView)).check(matches(isDisplayed()));
onView(withId(R.id.userLocationView)).check(matches(new DrawableMatcher(mapboxMap,
R.drawable.mapbox_mylocation_icon_default, false)));
onView(withId(R.id.mapView)).perform(new EnableCompassBearingTrackingAction(mapboxMap));
onView(withId(R.id.userLocationView)).check(matches(new DrawableMatcher(mapboxMap,
R.drawable.mapbox_mylocation_icon_bearing, true)));
}
@After
public void afterTest() {
Espresso.unregisterIdlingResources(idlingResource);
}
private class ToggleLocationAction implements ViewAction {
private MapboxMap mapboxMap;
private boolean isEnabled;
ToggleLocationAction(MapboxMap map, boolean enable) {
mapboxMap = map;
isEnabled = enable;
}
@Test
@Ignore // requires runtime permissions, disabled for CI
public void testEnabled() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
onView(withId(R.id.userLocationView)).check(matches(not(isDisplayed())));
onView(withId(R.id.mapView)).perform(new ToggleLocationAction(mapboxMap, true));
onView(withId(R.id.userLocationView)).check(matches(isDisplayed()));
onView(withId(R.id.mapView)).perform(new ToggleLocationAction(mapboxMap, false));
onView(withId(R.id.userLocationView)).check(matches(not(isDisplayed())));
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Test
@Ignore // requires runtime permissions, disabled for CI + issue with android.support.test.espresso.AppNotIdleException: Looped for 5049 iterations over 60 SECONDS.
public void testTracking() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
onView(withId(R.id.userLocationView)).check(matches(not(isDisplayed())));
onView(withId(R.id.mapView)).perform(new EnableLocationTrackingAction(mapboxMap));
onView(withId(R.id.userLocationView)).check(matches(isDisplayed()));
onView(withId(R.id.userLocationView)).check(matches(new DrawableMatcher(mapboxMap, R.drawable.mapbox_mylocation_icon_default, false)));
onView(withId(R.id.mapView)).perform(new EnableCompassBearingTrackingAction(mapboxMap));
onView(withId(R.id.userLocationView)).check(matches(new DrawableMatcher(mapboxMap, R.drawable.mapbox_mylocation_icon_bearing, true)));
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@After
public void afterTest() {
Espresso.unregisterIdlingResources(idlingResource);
@Override
public void perform(UiController uiController, View view) {
if (isEnabled) {
// move camera above user location
mapboxMap.moveCamera(
CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(new LatLng(LocationServices.getLocationServices(view.getContext()).getLastLocation()))
.build()
)
);
}
// show loction on screen
mapboxMap.setMyLocationEnabled(isEnabled);
}
}
private class EnableLocationTrackingAction implements ViewAction {
private MapboxMap mapboxMap;
EnableLocationTrackingAction(MapboxMap map) {
mapboxMap = map;
}
private class ToggleLocationAction implements ViewAction {
private MapboxMap mapboxMap;
private boolean isEnabled;
ToggleLocationAction(MapboxMap map, boolean enable) {
mapboxMap = map;
isEnabled = enable;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
if (isEnabled) {
// move camera above user location
mapboxMap.moveCamera(
CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(new LatLng(LocationServices.getLocationServices(view.getContext()).getLastLocation()))
.build()
)
);
}
// show loction on screen
mapboxMap.setMyLocationEnabled(isEnabled);
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
private class EnableLocationTrackingAction implements ViewAction {
private MapboxMap mapboxMap;
EnableLocationTrackingAction(MapboxMap map) {
mapboxMap = map;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.getTrackingSettings().setMyLocationTrackingMode(MyLocationTracking.TRACKING_FOLLOW);
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
private class EnableCompassBearingTrackingAction implements ViewAction {
@Override
public void perform(UiController uiController, View view) {
mapboxMap.getTrackingSettings().setMyLocationTrackingMode(MyLocationTracking.TRACKING_FOLLOW);
}
}
private MapboxMap mapboxMap;
private class EnableCompassBearingTrackingAction implements ViewAction {
EnableCompassBearingTrackingAction(MapboxMap map) {
mapboxMap = map;
}
private MapboxMap mapboxMap;
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.getTrackingSettings().setMyBearingTrackingMode(MyBearingTracking.COMPASS);
// wait for next compass update cycle
uiController.loopMainThreadForAtLeast(500);
}
EnableCompassBearingTrackingAction(MapboxMap map) {
mapboxMap = map;
}
private class DrawableMatcher extends TypeSafeMatcher<View> {
private MapboxMap mapboxMap;
private boolean isBearingDrawable;
private final int expectedId;
DrawableMatcher(MapboxMap mapboxMap, int expectedId, boolean isBearingDrawable) {
super(MyLocationView.class);
this.mapboxMap = mapboxMap;
this.expectedId = expectedId;
this.isBearingDrawable = isBearingDrawable;
}
@Override
protected boolean matchesSafely(View target) {
Drawable currentDrawable = isBearingDrawable ?
mapboxMap.getMyLocationViewSettings().getForegroundBearingDrawable() :
mapboxMap.getMyLocationViewSettings().getForegroundDrawable();
Resources resources = target.getContext().getResources();
Drawable expectedDrawable = resources.getDrawable(expectedId);
return areDrawablesIdentical(currentDrawable, expectedDrawable);
}
@Override
public void describeTo(Description description) {
description.appendText("trying to match MyLocationView drawable to " + expectedId);
}
boolean areDrawablesIdentical(Drawable drawableA, Drawable drawableB) {
Drawable.ConstantState stateA = drawableA.getConstantState();
Drawable.ConstantState stateB = drawableB.getConstantState();
return (stateA != null && stateB != null && stateA.equals(stateB))
|| getBitmap(drawableA).sameAs(getBitmap(drawableB));
}
Bitmap getBitmap(Drawable drawable) {
Bitmap result;
if (drawable instanceof BitmapDrawable) {
result = ((BitmapDrawable) drawable).getBitmap();
} else {
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
// Some drawables have no intrinsic width - e.g. solid colours.
if (width <= 0) {
width = 1;
}
if (height <= 0) {
height = 1;
}
result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
}
return result;
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
mapboxMap.getTrackingSettings().setMyBearingTrackingMode(MyBearingTracking.COMPASS);
// wait for next compass update cycle
uiController.loopMainThreadForAtLeast(500);
}
}
private class DrawableMatcher extends TypeSafeMatcher<View> {
private MapboxMap mapboxMap;
private boolean isBearingDrawable;
private final int expectedId;
DrawableMatcher(MapboxMap mapboxMap, int expectedId, boolean isBearingDrawable) {
super(MyLocationView.class);
this.mapboxMap = mapboxMap;
this.expectedId = expectedId;
this.isBearingDrawable = isBearingDrawable;
}
@Override
protected boolean matchesSafely(View target) {
Drawable currentDrawable = isBearingDrawable
? mapboxMap.getMyLocationViewSettings().getForegroundBearingDrawable() :
mapboxMap.getMyLocationViewSettings().getForegroundDrawable();
Resources resources = target.getContext().getResources();
Drawable expectedDrawable = resources.getDrawable(expectedId);
return areDrawablesIdentical(currentDrawable, expectedDrawable);
}
@Override
public void describeTo(Description description) {
description.appendText("trying to match MyLocationView drawable to " + expectedId);
}
boolean areDrawablesIdentical(Drawable drawableA, Drawable drawableB) {
Drawable.ConstantState stateA = drawableA.getConstantState();
Drawable.ConstantState stateB = drawableB.getConstantState();
return (stateA != null && stateB != null && stateA.equals(stateB))
|| getBitmap(drawableA).sameAs(getBitmap(drawableB));
}
Bitmap getBitmap(Drawable drawable) {
Bitmap result;
if (drawable instanceof BitmapDrawable) {
result = ((BitmapDrawable) drawable).getBitmap();
} else {
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
// Some drawables have no intrinsic width - e.g. solid colours.
if (width <= 0) {
width = 1;
}
if (height <= 0) {
height = 1;
}
result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
}
return result;
}
}
}

View File

@@ -1,11 +1,10 @@
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make style-code-android`.
package com.mapbox.mapboxsdk.testapp.style;
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make style-code-android`.
import android.graphics.Color;
import android.support.test.espresso.Espresso;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import timber.log.Timber;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.style.layers.BackgroundLayer;
@@ -19,9 +18,16 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
import static com.mapbox.mapboxsdk.style.layers.Property.*;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
import timber.log.Timber;
import static com.mapbox.mapboxsdk.style.layers.Property.NONE;
import static com.mapbox.mapboxsdk.style.layers.Property.VISIBLE;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.backgroundColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.backgroundOpacity;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.backgroundPattern;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.visibility;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Basic smoke tests for BackgroundLayer
@@ -29,107 +35,107 @@ import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
@RunWith(AndroidJUnit4.class)
public class BackgroundLayerStyleTest extends BaseStyleTest {
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
private BackgroundLayer layer;
private BackgroundLayer layer;
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
private MapboxMap mapboxMap;
private MapboxMap mapboxMap;
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
mapboxMap = rule.getActivity().getMapboxMap();
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("visibility");
assertNotNull(layer);
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("visibility");
assertNotNull(layer);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
}
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
}
@Test
public void testBackgroundColor() {
checkViewIsDisplayed(R.id.mapView);
@Test
public void testBackgroundColor() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
mapboxMap = rule.getActivity().getMapboxMap();
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("background-color");
assertNotNull(layer);
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("background-color");
assertNotNull(layer);
//Set and Get
layer.setProperties(backgroundColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getBackgroundColor().getValue(), (String) "rgba(0, 0, 0, 1)");
}
//Set and Get
layer.setProperties(backgroundColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getBackgroundColor().getValue(), (String) "rgba(0, 0, 0, 1)");
}
@Test
public void testBackgroundColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
@Test
public void testBackgroundColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
mapboxMap = rule.getActivity().getMapboxMap();
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("background-color");
assertNotNull(layer);
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("background-color");
assertNotNull(layer);
//Set and Get
layer.setProperties(backgroundColor(Color.RED));
assertEquals(layer.getBackgroundColorAsInt(), Color.RED);
}
//Set and Get
layer.setProperties(backgroundColor(Color.RED));
assertEquals(layer.getBackgroundColorAsInt(), Color.RED);
}
@Test
public void testBackgroundPattern() {
checkViewIsDisplayed(R.id.mapView);
@Test
public void testBackgroundPattern() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
mapboxMap = rule.getActivity().getMapboxMap();
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("background-pattern");
assertNotNull(layer);
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("background-pattern");
assertNotNull(layer);
//Set and Get
layer.setProperties(backgroundPattern("pedestrian-polygon"));
assertEquals((String) layer.getBackgroundPattern().getValue(), (String) "pedestrian-polygon");
}
//Set and Get
layer.setProperties(backgroundPattern("pedestrian-polygon"));
assertEquals((String) layer.getBackgroundPattern().getValue(), (String) "pedestrian-polygon");
}
@Test
public void testBackgroundOpacity() {
checkViewIsDisplayed(R.id.mapView);
@Test
public void testBackgroundOpacity() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
mapboxMap = rule.getActivity().getMapboxMap();
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("background-opacity");
assertNotNull(layer);
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("background-opacity");
assertNotNull(layer);
//Set and Get
layer.setProperties(backgroundOpacity(0.3f));
assertEquals((Float) layer.getBackgroundOpacity().getValue(), (Float) 0.3f);
}
//Set and Get
layer.setProperties(backgroundOpacity(0.3f));
assertEquals((Float) layer.getBackgroundOpacity().getValue(), (Float) 0.3f);
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
}

View File

@@ -1,11 +1,10 @@
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make android-style-code`.
package com.mapbox.mapboxsdk.testapp.style;
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make android-style-code`.
import android.graphics.Color;
import android.support.test.espresso.Espresso;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import timber.log.Timber;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.style.layers.BackgroundLayer;
@@ -19,9 +18,16 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
import static com.mapbox.mapboxsdk.style.layers.Property.*;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
import timber.log.Timber;
import static com.mapbox.mapboxsdk.style.layers.Property.NONE;
import static com.mapbox.mapboxsdk.style.layers.Property.VISIBLE;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.backgroundColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.backgroundOpacity;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.backgroundPattern;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.visibility;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Basic smoke tests for BackgroundLayer
@@ -29,107 +35,107 @@ import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
@RunWith(AndroidJUnit4.class)
public class BackgroundLayerTest extends BaseStyleTest {
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
private BackgroundLayer layer;
private BackgroundLayer layer;
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
private MapboxMap mapboxMap;
private MapboxMap mapboxMap;
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
mapboxMap = rule.getActivity().getMapboxMap();
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("visibility");
assertNotNull(layer);
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("visibility");
assertNotNull(layer);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
}
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
}
@Test
public void testBackgroundColor() {
checkViewIsDisplayed(R.id.mapView);
@Test
public void testBackgroundColor() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
mapboxMap = rule.getActivity().getMapboxMap();
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("background-color");
assertNotNull(layer);
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("background-color");
assertNotNull(layer);
//Set and Get
layer.setProperties(backgroundColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getBackgroundColor().getValue(), (String) "rgba(0, 0, 0, 1)");
}
//Set and Get
layer.setProperties(backgroundColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getBackgroundColor().getValue(), (String) "rgba(0, 0, 0, 1)");
}
@Test
public void testBackgroundColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
@Test
public void testBackgroundColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
mapboxMap = rule.getActivity().getMapboxMap();
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("background-color");
assertNotNull(layer);
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("background-color");
assertNotNull(layer);
//Set and Get
layer.setProperties(backgroundColor(Color.RED));
assertEquals(layer.getBackgroundColorAsInt(), Color.RED);
}
//Set and Get
layer.setProperties(backgroundColor(Color.RED));
assertEquals(layer.getBackgroundColorAsInt(), Color.RED);
}
@Test
public void testBackgroundPattern() {
checkViewIsDisplayed(R.id.mapView);
@Test
public void testBackgroundPattern() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
mapboxMap = rule.getActivity().getMapboxMap();
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("background-pattern");
assertNotNull(layer);
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("background-pattern");
assertNotNull(layer);
//Set and Get
layer.setProperties(backgroundPattern("pedestrian-polygon"));
assertEquals((String) layer.getBackgroundPattern().getValue(), (String) "pedestrian-polygon");
}
//Set and Get
layer.setProperties(backgroundPattern("pedestrian-polygon"));
assertEquals((String) layer.getBackgroundPattern().getValue(), (String) "pedestrian-polygon");
}
@Test
public void testBackgroundOpacity() {
checkViewIsDisplayed(R.id.mapView);
@Test
public void testBackgroundOpacity() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
mapboxMap = rule.getActivity().getMapboxMap();
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("background-opacity");
assertNotNull(layer);
Timber.i("Retrieving layer");
layer = mapboxMap.getLayerAs("background");
Timber.i("background-opacity");
assertNotNull(layer);
//Set and Get
layer.setProperties(backgroundOpacity(0.3f));
assertEquals((Float) layer.getBackgroundOpacity().getValue(), (Float) 0.3f);
}
//Set and Get
layer.setProperties(backgroundOpacity(0.3f));
assertEquals((Float) layer.getBackgroundOpacity().getValue(), (Float) 0.3f);
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
}

View File

@@ -14,31 +14,31 @@ import static android.support.test.espresso.matcher.ViewMatchers.withId;
*/
public class BaseStyleTest {
protected final static String HOME_BUTTON_STRING = "Navigate up";
protected static final String HOME_BUTTON_STRING = "Navigate up";
/*
* Shortcuts for common UI tests
*/
/*
* Shortcuts for common UI tests
*/
protected void checkViewIsDisplayed(int id) {
onView(withId(id))
.check(matches(isDisplayed()));
}
protected void checkViewIsDisplayed(int id) {
onView(withId(id))
.check(matches(isDisplayed()));
}
/*
* Screenshots logic
*/
/*
* Screenshots logic
*/
protected void takeNamedScreenshot(final Activity activity, final String name) {
protected void takeNamedScreenshot(final Activity activity, final String name) {
// Screenshots need to be taken on the UI thread
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
ScreenshotUtil.take(activity, name);
}
});
// Screenshots need to be taken on the UI thread
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
ScreenshotUtil.take(activity, name);
}
});
}
}
}

View File

@@ -1,11 +1,10 @@
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make style-code-android`.
package com.mapbox.mapboxsdk.testapp.style;
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make style-code-android`.
import android.graphics.Color;
import android.support.test.espresso.Espresso;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import timber.log.Timber;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.style.layers.CircleLayer;
@@ -19,9 +18,22 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
import static com.mapbox.mapboxsdk.style.layers.Property.*;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
import timber.log.Timber;
import static com.mapbox.mapboxsdk.style.layers.Property.CIRCLE_PITCH_SCALE_MAP;
import static com.mapbox.mapboxsdk.style.layers.Property.CIRCLE_TRANSLATE_ANCHOR_MAP;
import static com.mapbox.mapboxsdk.style.layers.Property.NONE;
import static com.mapbox.mapboxsdk.style.layers.Property.VISIBLE;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleBlur;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleOpacity;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circlePitchScale;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleRadius;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleTranslate;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleTranslateAnchor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.visibility;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Basic smoke tests for CircleLayer
@@ -29,225 +41,225 @@ import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
@RunWith(AndroidJUnit4.class)
public class CircleLayerStyleTest extends BaseStyleTest {
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
private CircleLayer layer;
private CircleLayer layer;
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
private MapboxMap mapboxMap;
private MapboxMap mapboxMap;
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("visibility");
assertNotNull(layer);
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
mapboxMap = rule.getActivity().getMapboxMap();
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
}
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("visibility");
assertNotNull(layer);
@Test
public void testCircleRadius() {
checkViewIsDisplayed(R.id.mapView);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
mapboxMap = rule.getActivity().getMapboxMap();
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-radius");
assertNotNull(layer);
@Test
public void testCircleRadius() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(circleRadius(0.3f));
assertEquals((Float) layer.getCircleRadius().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testCircleColor() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-radius");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(circleRadius(0.3f));
assertEquals((Float) layer.getCircleRadius().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-color");
assertNotNull(layer);
@Test
public void testCircleColor() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(circleColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getCircleColor().getValue(), (String) "rgba(0, 0, 0, 1)");
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testCircleColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-color");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(circleColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getCircleColor().getValue(), (String) "rgba(0, 0, 0, 1)");
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-color");
assertNotNull(layer);
@Test
public void testCircleColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(circleColor(Color.RED));
assertEquals(layer.getCircleColorAsInt(), Color.RED);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testCircleBlur() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-color");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(circleColor(Color.RED));
assertEquals(layer.getCircleColorAsInt(), Color.RED);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-blur");
assertNotNull(layer);
@Test
public void testCircleBlur() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(circleBlur(0.3f));
assertEquals((Float) layer.getCircleBlur().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testCircleOpacity() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-blur");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(circleBlur(0.3f));
assertEquals((Float) layer.getCircleBlur().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-opacity");
assertNotNull(layer);
@Test
public void testCircleOpacity() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(circleOpacity(0.3f));
assertEquals((Float) layer.getCircleOpacity().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testCircleTranslate() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-opacity");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(circleOpacity(0.3f));
assertEquals((Float) layer.getCircleOpacity().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-translate");
assertNotNull(layer);
@Test
public void testCircleTranslate() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(circleTranslate(new Float[] {0f, 0f}));
assertEquals((Float[]) layer.getCircleTranslate().getValue(), (Float[]) new Float[] {0f, 0f});
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testCircleTranslateAnchor() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-translate");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(circleTranslate(new Float[]{0f,0f}));
assertEquals((Float[]) layer.getCircleTranslate().getValue(), (Float[]) new Float[]{0f,0f});
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-translate-anchor");
assertNotNull(layer);
@Test
public void testCircleTranslateAnchor() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(circleTranslateAnchor(CIRCLE_TRANSLATE_ANCHOR_MAP));
assertEquals((String) layer.getCircleTranslateAnchor().getValue(), (String) CIRCLE_TRANSLATE_ANCHOR_MAP);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testCirclePitchScale() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-translate-anchor");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(circleTranslateAnchor(CIRCLE_TRANSLATE_ANCHOR_MAP));
assertEquals((String) layer.getCircleTranslateAnchor().getValue(), (String) CIRCLE_TRANSLATE_ANCHOR_MAP);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-pitch-scale");
assertNotNull(layer);
@Test
public void testCirclePitchScale() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-pitch-scale");
assertNotNull(layer);
//Set and Get
layer.setProperties(circlePitchScale(CIRCLE_PITCH_SCALE_MAP));
assertEquals((String) layer.getCirclePitchScale().getValue(), (String) CIRCLE_PITCH_SCALE_MAP);
}
//Set and Get
layer.setProperties(circlePitchScale(CIRCLE_PITCH_SCALE_MAP));
assertEquals((String) layer.getCirclePitchScale().getValue(), (String) CIRCLE_PITCH_SCALE_MAP);
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
}

View File

@@ -1,11 +1,10 @@
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make android-style-code`.
package com.mapbox.mapboxsdk.testapp.style;
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make android-style-code`.
import android.graphics.Color;
import android.support.test.espresso.Espresso;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import timber.log.Timber;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.style.layers.CircleLayer;
@@ -19,9 +18,25 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
import static com.mapbox.mapboxsdk.style.layers.Property.*;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
import timber.log.Timber;
import static com.mapbox.mapboxsdk.style.layers.Property.CIRCLE_PITCH_SCALE_MAP;
import static com.mapbox.mapboxsdk.style.layers.Property.CIRCLE_TRANSLATE_ANCHOR_MAP;
import static com.mapbox.mapboxsdk.style.layers.Property.NONE;
import static com.mapbox.mapboxsdk.style.layers.Property.VISIBLE;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleBlur;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleOpacity;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circlePitchScale;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleRadius;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleStrokeColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleStrokeOpacity;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleStrokeWidth;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleTranslate;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleTranslateAnchor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.visibility;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Basic smoke tests for CircleLayer
@@ -29,313 +44,313 @@ import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
@RunWith(AndroidJUnit4.class)
public class CircleLayerTest extends BaseStyleTest {
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
private CircleLayer layer;
private CircleLayer layer;
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
private MapboxMap mapboxMap;
private MapboxMap mapboxMap;
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("visibility");
assertNotNull(layer);
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
mapboxMap = rule.getActivity().getMapboxMap();
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
}
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("visibility");
assertNotNull(layer);
@Test
public void testCircleRadius() {
checkViewIsDisplayed(R.id.mapView);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
mapboxMap = rule.getActivity().getMapboxMap();
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-radius");
assertNotNull(layer);
@Test
public void testCircleRadius() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(circleRadius(0.3f));
assertEquals((Float) layer.getCircleRadius().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testCircleColor() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-radius");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(circleRadius(0.3f));
assertEquals((Float) layer.getCircleRadius().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-color");
assertNotNull(layer);
@Test
public void testCircleColor() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(circleColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getCircleColor().getValue(), (String) "rgba(0, 0, 0, 1)");
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testCircleColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-color");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(circleColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getCircleColor().getValue(), (String) "rgba(0, 0, 0, 1)");
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-color");
assertNotNull(layer);
@Test
public void testCircleColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(circleColor(Color.RED));
assertEquals(layer.getCircleColorAsInt(), Color.RED);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testCircleBlur() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-color");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(circleColor(Color.RED));
assertEquals(layer.getCircleColorAsInt(), Color.RED);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-blur");
assertNotNull(layer);
@Test
public void testCircleBlur() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(circleBlur(0.3f));
assertEquals((Float) layer.getCircleBlur().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testCircleOpacity() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-blur");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(circleBlur(0.3f));
assertEquals((Float) layer.getCircleBlur().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-opacity");
assertNotNull(layer);
@Test
public void testCircleOpacity() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(circleOpacity(0.3f));
assertEquals((Float) layer.getCircleOpacity().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testCircleTranslate() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-opacity");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(circleOpacity(0.3f));
assertEquals((Float) layer.getCircleOpacity().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-translate");
assertNotNull(layer);
@Test
public void testCircleTranslate() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(circleTranslate(new Float[] {0f, 0f}));
assertEquals((Float[]) layer.getCircleTranslate().getValue(), (Float[]) new Float[] {0f, 0f});
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testCircleTranslateAnchor() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-translate");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(circleTranslate(new Float[]{0f,0f}));
assertEquals((Float[]) layer.getCircleTranslate().getValue(), (Float[]) new Float[]{0f,0f});
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-translate-anchor");
assertNotNull(layer);
@Test
public void testCircleTranslateAnchor() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(circleTranslateAnchor(CIRCLE_TRANSLATE_ANCHOR_MAP));
assertEquals((String) layer.getCircleTranslateAnchor().getValue(), (String) CIRCLE_TRANSLATE_ANCHOR_MAP);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testCirclePitchScale() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-translate-anchor");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(circleTranslateAnchor(CIRCLE_TRANSLATE_ANCHOR_MAP));
assertEquals((String) layer.getCircleTranslateAnchor().getValue(), (String) CIRCLE_TRANSLATE_ANCHOR_MAP);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-pitch-scale");
assertNotNull(layer);
@Test
public void testCirclePitchScale() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(circlePitchScale(CIRCLE_PITCH_SCALE_MAP));
assertEquals((String) layer.getCirclePitchScale().getValue(), (String) CIRCLE_PITCH_SCALE_MAP);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testCircleStrokeWidth() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-pitch-scale");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(circlePitchScale(CIRCLE_PITCH_SCALE_MAP));
assertEquals((String) layer.getCirclePitchScale().getValue(), (String) CIRCLE_PITCH_SCALE_MAP);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-stroke-width");
assertNotNull(layer);
@Test
public void testCircleStrokeWidth() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(circleStrokeWidth(0.3f));
assertEquals((Float) layer.getCircleStrokeWidth().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testCircleStrokeColor() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-stroke-width");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(circleStrokeWidth(0.3f));
assertEquals((Float) layer.getCircleStrokeWidth().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-stroke-color");
assertNotNull(layer);
@Test
public void testCircleStrokeColor() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(circleStrokeColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getCircleStrokeColor().getValue(), (String) "rgba(0, 0, 0, 1)");
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testCircleStrokeColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-stroke-color");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(circleStrokeColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getCircleStrokeColor().getValue(), (String) "rgba(0, 0, 0, 1)");
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-stroke-color");
assertNotNull(layer);
@Test
public void testCircleStrokeColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(circleStrokeColor(Color.RED));
assertEquals(layer.getCircleStrokeColorAsInt(), Color.RED);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testCircleStrokeOpacity() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-stroke-color");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(circleStrokeColor(Color.RED));
assertEquals(layer.getCircleStrokeColorAsInt(), Color.RED);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-stroke-opacity");
assertNotNull(layer);
@Test
public void testCircleStrokeOpacity() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new CircleLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("circle-stroke-opacity");
assertNotNull(layer);
//Set and Get
layer.setProperties(circleStrokeOpacity(0.3f));
assertEquals((Float) layer.getCircleStrokeOpacity().getValue(), (Float) 0.3f);
}
//Set and Get
layer.setProperties(circleStrokeOpacity(0.3f));
assertEquals((Float) layer.getCircleStrokeOpacity().getValue(), (Float) 0.3f);
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
}

View File

@@ -1,11 +1,10 @@
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make style-code-android`.
package com.mapbox.mapboxsdk.testapp.style;
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make style-code-android`.
import android.graphics.Color;
import android.support.test.espresso.Espresso;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import timber.log.Timber;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.style.layers.FillLayer;
@@ -19,9 +18,21 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
import static com.mapbox.mapboxsdk.style.layers.Property.*;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
import timber.log.Timber;
import static com.mapbox.mapboxsdk.style.layers.Property.FILL_TRANSLATE_ANCHOR_MAP;
import static com.mapbox.mapboxsdk.style.layers.Property.NONE;
import static com.mapbox.mapboxsdk.style.layers.Property.VISIBLE;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillAntialias;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillOpacity;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillOutlineColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillPattern;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillTranslate;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillTranslateAnchor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.visibility;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Basic smoke tests for FillLayer
@@ -29,247 +40,247 @@ import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
@RunWith(AndroidJUnit4.class)
public class FillLayerStyleTest extends BaseStyleTest {
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
private FillLayer layer;
private FillLayer layer;
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
private MapboxMap mapboxMap;
private MapboxMap mapboxMap;
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("visibility");
assertNotNull(layer);
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
mapboxMap = rule.getActivity().getMapboxMap();
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
}
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("visibility");
assertNotNull(layer);
@Test
public void testFillAntialias() {
checkViewIsDisplayed(R.id.mapView);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
mapboxMap = rule.getActivity().getMapboxMap();
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-antialias");
assertNotNull(layer);
@Test
public void testFillAntialias() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(fillAntialias(true));
assertEquals((Boolean) layer.getFillAntialias().getValue(), (Boolean) true);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testFillOpacity() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-antialias");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(fillAntialias(true));
assertEquals((Boolean) layer.getFillAntialias().getValue(), (Boolean) true);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-opacity");
assertNotNull(layer);
@Test
public void testFillOpacity() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(fillOpacity(0.3f));
assertEquals((Float) layer.getFillOpacity().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testFillColor() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-opacity");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(fillOpacity(0.3f));
assertEquals((Float) layer.getFillOpacity().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-color");
assertNotNull(layer);
@Test
public void testFillColor() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(fillColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getFillColor().getValue(), (String) "rgba(0, 0, 0, 1)");
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testFillColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-color");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(fillColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getFillColor().getValue(), (String) "rgba(0, 0, 0, 1)");
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-color");
assertNotNull(layer);
@Test
public void testFillColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(fillColor(Color.RED));
assertEquals(layer.getFillColorAsInt(), Color.RED);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testFillOutlineColor() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-color");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(fillColor(Color.RED));
assertEquals(layer.getFillColorAsInt(), Color.RED);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-outline-color");
assertNotNull(layer);
@Test
public void testFillOutlineColor() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(fillOutlineColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getFillOutlineColor().getValue(), (String) "rgba(0, 0, 0, 1)");
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testFillOutlineColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-outline-color");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(fillOutlineColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getFillOutlineColor().getValue(), (String) "rgba(0, 0, 0, 1)");
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-outline-color");
assertNotNull(layer);
@Test
public void testFillOutlineColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(fillOutlineColor(Color.RED));
assertEquals(layer.getFillOutlineColorAsInt(), Color.RED);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testFillTranslate() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-outline-color");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(fillOutlineColor(Color.RED));
assertEquals(layer.getFillOutlineColorAsInt(), Color.RED);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-translate");
assertNotNull(layer);
@Test
public void testFillTranslate() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(fillTranslate(new Float[] {0f, 0f}));
assertEquals((Float[]) layer.getFillTranslate().getValue(), (Float[]) new Float[] {0f, 0f});
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testFillTranslateAnchor() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-translate");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(fillTranslate(new Float[]{0f,0f}));
assertEquals((Float[]) layer.getFillTranslate().getValue(), (Float[]) new Float[]{0f,0f});
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-translate-anchor");
assertNotNull(layer);
@Test
public void testFillTranslateAnchor() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(fillTranslateAnchor(FILL_TRANSLATE_ANCHOR_MAP));
assertEquals((String) layer.getFillTranslateAnchor().getValue(), (String) FILL_TRANSLATE_ANCHOR_MAP);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testFillPattern() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-translate-anchor");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(fillTranslateAnchor(FILL_TRANSLATE_ANCHOR_MAP));
assertEquals((String) layer.getFillTranslateAnchor().getValue(), (String) FILL_TRANSLATE_ANCHOR_MAP);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-pattern");
assertNotNull(layer);
@Test
public void testFillPattern() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-pattern");
assertNotNull(layer);
//Set and Get
layer.setProperties(fillPattern("pedestrian-polygon"));
assertEquals((String) layer.getFillPattern().getValue(), (String) "pedestrian-polygon");
}
//Set and Get
layer.setProperties(fillPattern("pedestrian-polygon"));
assertEquals((String) layer.getFillPattern().getValue(), (String) "pedestrian-polygon");
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
}

View File

@@ -1,11 +1,10 @@
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make android-style-code`.
package com.mapbox.mapboxsdk.testapp.style;
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make android-style-code`.
import android.graphics.Color;
import android.support.test.espresso.Espresso;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import timber.log.Timber;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.style.layers.FillLayer;
@@ -19,9 +18,21 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
import static com.mapbox.mapboxsdk.style.layers.Property.*;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
import timber.log.Timber;
import static com.mapbox.mapboxsdk.style.layers.Property.FILL_TRANSLATE_ANCHOR_MAP;
import static com.mapbox.mapboxsdk.style.layers.Property.NONE;
import static com.mapbox.mapboxsdk.style.layers.Property.VISIBLE;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillAntialias;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillOpacity;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillOutlineColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillPattern;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillTranslate;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillTranslateAnchor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.visibility;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Basic smoke tests for FillLayer
@@ -29,247 +40,247 @@ import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
@RunWith(AndroidJUnit4.class)
public class FillLayerTest extends BaseStyleTest {
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
private FillLayer layer;
private FillLayer layer;
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
private MapboxMap mapboxMap;
private MapboxMap mapboxMap;
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("visibility");
assertNotNull(layer);
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
mapboxMap = rule.getActivity().getMapboxMap();
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
}
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("visibility");
assertNotNull(layer);
@Test
public void testFillAntialias() {
checkViewIsDisplayed(R.id.mapView);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
mapboxMap = rule.getActivity().getMapboxMap();
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-antialias");
assertNotNull(layer);
@Test
public void testFillAntialias() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(fillAntialias(true));
assertEquals((Boolean) layer.getFillAntialias().getValue(), (Boolean) true);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testFillOpacity() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-antialias");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(fillAntialias(true));
assertEquals((Boolean) layer.getFillAntialias().getValue(), (Boolean) true);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-opacity");
assertNotNull(layer);
@Test
public void testFillOpacity() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(fillOpacity(0.3f));
assertEquals((Float) layer.getFillOpacity().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testFillColor() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-opacity");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(fillOpacity(0.3f));
assertEquals((Float) layer.getFillOpacity().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-color");
assertNotNull(layer);
@Test
public void testFillColor() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(fillColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getFillColor().getValue(), (String) "rgba(0, 0, 0, 1)");
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testFillColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-color");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(fillColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getFillColor().getValue(), (String) "rgba(0, 0, 0, 1)");
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-color");
assertNotNull(layer);
@Test
public void testFillColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(fillColor(Color.RED));
assertEquals(layer.getFillColorAsInt(), Color.RED);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testFillOutlineColor() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-color");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(fillColor(Color.RED));
assertEquals(layer.getFillColorAsInt(), Color.RED);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-outline-color");
assertNotNull(layer);
@Test
public void testFillOutlineColor() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(fillOutlineColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getFillOutlineColor().getValue(), (String) "rgba(0, 0, 0, 1)");
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testFillOutlineColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-outline-color");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(fillOutlineColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getFillOutlineColor().getValue(), (String) "rgba(0, 0, 0, 1)");
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-outline-color");
assertNotNull(layer);
@Test
public void testFillOutlineColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(fillOutlineColor(Color.RED));
assertEquals(layer.getFillOutlineColorAsInt(), Color.RED);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testFillTranslate() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-outline-color");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(fillOutlineColor(Color.RED));
assertEquals(layer.getFillOutlineColorAsInt(), Color.RED);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-translate");
assertNotNull(layer);
@Test
public void testFillTranslate() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(fillTranslate(new Float[] {0f, 0f}));
assertEquals((Float[]) layer.getFillTranslate().getValue(), (Float[]) new Float[] {0f, 0f});
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testFillTranslateAnchor() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-translate");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(fillTranslate(new Float[]{0f,0f}));
assertEquals((Float[]) layer.getFillTranslate().getValue(), (Float[]) new Float[]{0f,0f});
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-translate-anchor");
assertNotNull(layer);
@Test
public void testFillTranslateAnchor() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(fillTranslateAnchor(FILL_TRANSLATE_ANCHOR_MAP));
assertEquals((String) layer.getFillTranslateAnchor().getValue(), (String) FILL_TRANSLATE_ANCHOR_MAP);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testFillPattern() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-translate-anchor");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(fillTranslateAnchor(FILL_TRANSLATE_ANCHOR_MAP));
assertEquals((String) layer.getFillTranslateAnchor().getValue(), (String) FILL_TRANSLATE_ANCHOR_MAP);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-pattern");
assertNotNull(layer);
@Test
public void testFillPattern() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new FillLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("fill-pattern");
assertNotNull(layer);
//Set and Get
layer.setProperties(fillPattern("pedestrian-polygon"));
assertEquals((String) layer.getFillPattern().getValue(), (String) "pedestrian-polygon");
}
//Set and Get
layer.setProperties(fillPattern("pedestrian-polygon"));
assertEquals((String) layer.getFillPattern().getValue(), (String) "pedestrian-polygon");
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
}

View File

@@ -1,11 +1,10 @@
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make style-code-android`.
package com.mapbox.mapboxsdk.testapp.style;
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make style-code-android`.
import android.graphics.Color;
import android.support.test.espresso.Espresso;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import timber.log.Timber;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.style.layers.LineLayer;
@@ -19,9 +18,30 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
import static com.mapbox.mapboxsdk.style.layers.Property.*;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
import timber.log.Timber;
import static com.mapbox.mapboxsdk.style.layers.Property.LINE_CAP_BUTT;
import static com.mapbox.mapboxsdk.style.layers.Property.LINE_JOIN_BEVEL;
import static com.mapbox.mapboxsdk.style.layers.Property.LINE_TRANSLATE_ANCHOR_MAP;
import static com.mapbox.mapboxsdk.style.layers.Property.NONE;
import static com.mapbox.mapboxsdk.style.layers.Property.VISIBLE;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineBlur;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineCap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineDasharray;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineGapWidth;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineJoin;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineMiterLimit;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineOffset;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineOpacity;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.linePattern;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineRoundLimit;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineTranslate;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineTranslateAnchor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineWidth;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.visibility;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Basic smoke tests for LineLayer
@@ -29,379 +49,379 @@ import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
@RunWith(AndroidJUnit4.class)
public class LineLayerStyleTest extends BaseStyleTest {
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
private LineLayer layer;
private LineLayer layer;
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
private MapboxMap mapboxMap;
private MapboxMap mapboxMap;
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("visibility");
assertNotNull(layer);
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
mapboxMap = rule.getActivity().getMapboxMap();
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
}
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("visibility");
assertNotNull(layer);
@Test
public void testLineCap() {
checkViewIsDisplayed(R.id.mapView);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
mapboxMap = rule.getActivity().getMapboxMap();
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-cap");
assertNotNull(layer);
@Test
public void testLineCap() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineCap(LINE_CAP_BUTT));
assertEquals((String) layer.getLineCap().getValue(), (String) LINE_CAP_BUTT);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineJoin() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-cap");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineCap(LINE_CAP_BUTT));
assertEquals((String) layer.getLineCap().getValue(), (String) LINE_CAP_BUTT);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-join");
assertNotNull(layer);
@Test
public void testLineJoin() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineJoin(LINE_JOIN_BEVEL));
assertEquals((String) layer.getLineJoin().getValue(), (String) LINE_JOIN_BEVEL);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineMiterLimit() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-join");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineJoin(LINE_JOIN_BEVEL));
assertEquals((String) layer.getLineJoin().getValue(), (String) LINE_JOIN_BEVEL);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-miter-limit");
assertNotNull(layer);
@Test
public void testLineMiterLimit() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineMiterLimit(0.3f));
assertEquals((Float) layer.getLineMiterLimit().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineRoundLimit() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-miter-limit");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineMiterLimit(0.3f));
assertEquals((Float) layer.getLineMiterLimit().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-round-limit");
assertNotNull(layer);
@Test
public void testLineRoundLimit() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineRoundLimit(0.3f));
assertEquals((Float) layer.getLineRoundLimit().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineOpacity() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-round-limit");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineRoundLimit(0.3f));
assertEquals((Float) layer.getLineRoundLimit().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-opacity");
assertNotNull(layer);
@Test
public void testLineOpacity() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineOpacity(0.3f));
assertEquals((Float) layer.getLineOpacity().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineColor() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-opacity");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineOpacity(0.3f));
assertEquals((Float) layer.getLineOpacity().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-color");
assertNotNull(layer);
@Test
public void testLineColor() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getLineColor().getValue(), (String) "rgba(0, 0, 0, 1)");
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-color");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getLineColor().getValue(), (String) "rgba(0, 0, 0, 1)");
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-color");
assertNotNull(layer);
@Test
public void testLineColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineColor(Color.RED));
assertEquals(layer.getLineColorAsInt(), Color.RED);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineTranslate() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-color");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineColor(Color.RED));
assertEquals(layer.getLineColorAsInt(), Color.RED);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-translate");
assertNotNull(layer);
@Test
public void testLineTranslate() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineTranslate(new Float[] {0f, 0f}));
assertEquals((Float[]) layer.getLineTranslate().getValue(), (Float[]) new Float[] {0f, 0f});
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineTranslateAnchor() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-translate");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineTranslate(new Float[]{0f,0f}));
assertEquals((Float[]) layer.getLineTranslate().getValue(), (Float[]) new Float[]{0f,0f});
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-translate-anchor");
assertNotNull(layer);
@Test
public void testLineTranslateAnchor() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineTranslateAnchor(LINE_TRANSLATE_ANCHOR_MAP));
assertEquals((String) layer.getLineTranslateAnchor().getValue(), (String) LINE_TRANSLATE_ANCHOR_MAP);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineWidth() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-translate-anchor");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineTranslateAnchor(LINE_TRANSLATE_ANCHOR_MAP));
assertEquals((String) layer.getLineTranslateAnchor().getValue(), (String) LINE_TRANSLATE_ANCHOR_MAP);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-width");
assertNotNull(layer);
@Test
public void testLineWidth() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineWidth(0.3f));
assertEquals((Float) layer.getLineWidth().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineGapWidth() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-width");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineWidth(0.3f));
assertEquals((Float) layer.getLineWidth().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-gap-width");
assertNotNull(layer);
@Test
public void testLineGapWidth() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineGapWidth(0.3f));
assertEquals((Float) layer.getLineGapWidth().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineOffset() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-gap-width");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineGapWidth(0.3f));
assertEquals((Float) layer.getLineGapWidth().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-offset");
assertNotNull(layer);
@Test
public void testLineOffset() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineOffset(0.3f));
assertEquals((Float) layer.getLineOffset().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineBlur() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-offset");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineOffset(0.3f));
assertEquals((Float) layer.getLineOffset().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-blur");
assertNotNull(layer);
@Test
public void testLineBlur() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineBlur(0.3f));
assertEquals((Float) layer.getLineBlur().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineDasharray() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-blur");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineBlur(0.3f));
assertEquals((Float) layer.getLineBlur().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-dasharray");
assertNotNull(layer);
@Test
public void testLineDasharray() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineDasharray(new Float[] {}));
assertEquals((Float[]) layer.getLineDasharray().getValue(), (Float[]) new Float[] {});
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLinePattern() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-dasharray");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineDasharray(new Float[]{}));
assertEquals((Float[]) layer.getLineDasharray().getValue(), (Float[]) new Float[]{});
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-pattern");
assertNotNull(layer);
@Test
public void testLinePattern() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-pattern");
assertNotNull(layer);
//Set and Get
layer.setProperties(linePattern("pedestrian-polygon"));
assertEquals((String) layer.getLinePattern().getValue(), (String) "pedestrian-polygon");
}
//Set and Get
layer.setProperties(linePattern("pedestrian-polygon"));
assertEquals((String) layer.getLinePattern().getValue(), (String) "pedestrian-polygon");
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
}

View File

@@ -1,11 +1,10 @@
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make android-style-code`.
package com.mapbox.mapboxsdk.testapp.style;
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make android-style-code`.
import android.graphics.Color;
import android.support.test.espresso.Espresso;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import timber.log.Timber;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.style.layers.LineLayer;
@@ -19,9 +18,30 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
import static com.mapbox.mapboxsdk.style.layers.Property.*;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
import timber.log.Timber;
import static com.mapbox.mapboxsdk.style.layers.Property.LINE_CAP_BUTT;
import static com.mapbox.mapboxsdk.style.layers.Property.LINE_JOIN_BEVEL;
import static com.mapbox.mapboxsdk.style.layers.Property.LINE_TRANSLATE_ANCHOR_MAP;
import static com.mapbox.mapboxsdk.style.layers.Property.NONE;
import static com.mapbox.mapboxsdk.style.layers.Property.VISIBLE;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineBlur;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineCap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineDasharray;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineGapWidth;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineJoin;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineMiterLimit;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineOffset;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineOpacity;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.linePattern;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineRoundLimit;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineTranslate;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineTranslateAnchor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineWidth;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.visibility;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Basic smoke tests for LineLayer
@@ -29,379 +49,379 @@ import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
@RunWith(AndroidJUnit4.class)
public class LineLayerTest extends BaseStyleTest {
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
private LineLayer layer;
private LineLayer layer;
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
private MapboxMap mapboxMap;
private MapboxMap mapboxMap;
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("visibility");
assertNotNull(layer);
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
mapboxMap = rule.getActivity().getMapboxMap();
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
}
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("visibility");
assertNotNull(layer);
@Test
public void testLineCap() {
checkViewIsDisplayed(R.id.mapView);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
mapboxMap = rule.getActivity().getMapboxMap();
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-cap");
assertNotNull(layer);
@Test
public void testLineCap() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineCap(LINE_CAP_BUTT));
assertEquals((String) layer.getLineCap().getValue(), (String) LINE_CAP_BUTT);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineJoin() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-cap");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineCap(LINE_CAP_BUTT));
assertEquals((String) layer.getLineCap().getValue(), (String) LINE_CAP_BUTT);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-join");
assertNotNull(layer);
@Test
public void testLineJoin() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineJoin(LINE_JOIN_BEVEL));
assertEquals((String) layer.getLineJoin().getValue(), (String) LINE_JOIN_BEVEL);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineMiterLimit() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-join");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineJoin(LINE_JOIN_BEVEL));
assertEquals((String) layer.getLineJoin().getValue(), (String) LINE_JOIN_BEVEL);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-miter-limit");
assertNotNull(layer);
@Test
public void testLineMiterLimit() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineMiterLimit(0.3f));
assertEquals((Float) layer.getLineMiterLimit().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineRoundLimit() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-miter-limit");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineMiterLimit(0.3f));
assertEquals((Float) layer.getLineMiterLimit().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-round-limit");
assertNotNull(layer);
@Test
public void testLineRoundLimit() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineRoundLimit(0.3f));
assertEquals((Float) layer.getLineRoundLimit().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineOpacity() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-round-limit");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineRoundLimit(0.3f));
assertEquals((Float) layer.getLineRoundLimit().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-opacity");
assertNotNull(layer);
@Test
public void testLineOpacity() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineOpacity(0.3f));
assertEquals((Float) layer.getLineOpacity().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineColor() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-opacity");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineOpacity(0.3f));
assertEquals((Float) layer.getLineOpacity().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-color");
assertNotNull(layer);
@Test
public void testLineColor() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getLineColor().getValue(), (String) "rgba(0, 0, 0, 1)");
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-color");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineColor("rgba(0, 0, 0, 1)"));
assertEquals((String) layer.getLineColor().getValue(), (String) "rgba(0, 0, 0, 1)");
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-color");
assertNotNull(layer);
@Test
public void testLineColorAsInt() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineColor(Color.RED));
assertEquals(layer.getLineColorAsInt(), Color.RED);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineTranslate() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-color");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineColor(Color.RED));
assertEquals(layer.getLineColorAsInt(), Color.RED);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-translate");
assertNotNull(layer);
@Test
public void testLineTranslate() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineTranslate(new Float[] {0f, 0f}));
assertEquals((Float[]) layer.getLineTranslate().getValue(), (Float[]) new Float[] {0f, 0f});
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineTranslateAnchor() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-translate");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineTranslate(new Float[]{0f,0f}));
assertEquals((Float[]) layer.getLineTranslate().getValue(), (Float[]) new Float[]{0f,0f});
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-translate-anchor");
assertNotNull(layer);
@Test
public void testLineTranslateAnchor() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineTranslateAnchor(LINE_TRANSLATE_ANCHOR_MAP));
assertEquals((String) layer.getLineTranslateAnchor().getValue(), (String) LINE_TRANSLATE_ANCHOR_MAP);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineWidth() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-translate-anchor");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineTranslateAnchor(LINE_TRANSLATE_ANCHOR_MAP));
assertEquals((String) layer.getLineTranslateAnchor().getValue(), (String) LINE_TRANSLATE_ANCHOR_MAP);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-width");
assertNotNull(layer);
@Test
public void testLineWidth() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineWidth(0.3f));
assertEquals((Float) layer.getLineWidth().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineGapWidth() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-width");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineWidth(0.3f));
assertEquals((Float) layer.getLineWidth().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-gap-width");
assertNotNull(layer);
@Test
public void testLineGapWidth() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineGapWidth(0.3f));
assertEquals((Float) layer.getLineGapWidth().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineOffset() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-gap-width");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineGapWidth(0.3f));
assertEquals((Float) layer.getLineGapWidth().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-offset");
assertNotNull(layer);
@Test
public void testLineOffset() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineOffset(0.3f));
assertEquals((Float) layer.getLineOffset().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineBlur() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-offset");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineOffset(0.3f));
assertEquals((Float) layer.getLineOffset().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-blur");
assertNotNull(layer);
@Test
public void testLineBlur() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineBlur(0.3f));
assertEquals((Float) layer.getLineBlur().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLineDasharray() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-blur");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineBlur(0.3f));
assertEquals((Float) layer.getLineBlur().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-dasharray");
assertNotNull(layer);
@Test
public void testLineDasharray() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(lineDasharray(new Float[] {}));
assertEquals((Float[]) layer.getLineDasharray().getValue(), (Float[]) new Float[] {});
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testLinePattern() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-dasharray");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(lineDasharray(new Float[]{}));
assertEquals((Float[]) layer.getLineDasharray().getValue(), (Float[]) new Float[]{});
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-pattern");
assertNotNull(layer);
@Test
public void testLinePattern() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new LineLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("line-pattern");
assertNotNull(layer);
//Set and Get
layer.setProperties(linePattern("pedestrian-polygon"));
assertEquals((String) layer.getLinePattern().getValue(), (String) "pedestrian-polygon");
}
//Set and Get
layer.setProperties(linePattern("pedestrian-polygon"));
assertEquals((String) layer.getLinePattern().getValue(), (String) "pedestrian-polygon");
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
}

View File

@@ -1,10 +1,9 @@
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make style-code-android`.
package com.mapbox.mapboxsdk.testapp.style;
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make style-code-android`.
import android.support.test.espresso.Espresso;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import timber.log.Timber;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.style.layers.RasterLayer;
@@ -18,9 +17,20 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
import static com.mapbox.mapboxsdk.style.layers.Property.*;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
import timber.log.Timber;
import static com.mapbox.mapboxsdk.style.layers.Property.NONE;
import static com.mapbox.mapboxsdk.style.layers.Property.VISIBLE;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.rasterBrightnessMax;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.rasterBrightnessMin;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.rasterContrast;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.rasterFadeDuration;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.rasterHueRotate;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.rasterOpacity;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.rasterSaturation;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.visibility;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Basic smoke tests for RasterLayer
@@ -28,203 +38,203 @@ import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
@RunWith(AndroidJUnit4.class)
public class RasterLayerStyleTest extends BaseStyleTest {
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
private RasterLayer layer;
private RasterLayer layer;
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
private MapboxMap mapboxMap;
private MapboxMap mapboxMap;
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("visibility");
assertNotNull(layer);
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
mapboxMap = rule.getActivity().getMapboxMap();
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
}
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("visibility");
assertNotNull(layer);
@Test
public void testRasterOpacity() {
checkViewIsDisplayed(R.id.mapView);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
mapboxMap = rule.getActivity().getMapboxMap();
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-opacity");
assertNotNull(layer);
@Test
public void testRasterOpacity() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(rasterOpacity(0.3f));
assertEquals((Float) layer.getRasterOpacity().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testRasterHueRotate() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-opacity");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(rasterOpacity(0.3f));
assertEquals((Float) layer.getRasterOpacity().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-hue-rotate");
assertNotNull(layer);
@Test
public void testRasterHueRotate() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(rasterHueRotate(0.3f));
assertEquals((Float) layer.getRasterHueRotate().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testRasterBrightnessMin() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-hue-rotate");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(rasterHueRotate(0.3f));
assertEquals((Float) layer.getRasterHueRotate().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-brightness-min");
assertNotNull(layer);
@Test
public void testRasterBrightnessMin() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(rasterBrightnessMin(0.3f));
assertEquals((Float) layer.getRasterBrightnessMin().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testRasterBrightnessMax() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-brightness-min");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(rasterBrightnessMin(0.3f));
assertEquals((Float) layer.getRasterBrightnessMin().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-brightness-max");
assertNotNull(layer);
@Test
public void testRasterBrightnessMax() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(rasterBrightnessMax(0.3f));
assertEquals((Float) layer.getRasterBrightnessMax().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testRasterSaturation() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-brightness-max");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(rasterBrightnessMax(0.3f));
assertEquals((Float) layer.getRasterBrightnessMax().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-saturation");
assertNotNull(layer);
@Test
public void testRasterSaturation() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(rasterSaturation(0.3f));
assertEquals((Float) layer.getRasterSaturation().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testRasterContrast() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-saturation");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(rasterSaturation(0.3f));
assertEquals((Float) layer.getRasterSaturation().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-contrast");
assertNotNull(layer);
@Test
public void testRasterContrast() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(rasterContrast(0.3f));
assertEquals((Float) layer.getRasterContrast().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testRasterFadeDuration() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-contrast");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(rasterContrast(0.3f));
assertEquals((Float) layer.getRasterContrast().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-fade-duration");
assertNotNull(layer);
@Test
public void testRasterFadeDuration() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-fade-duration");
assertNotNull(layer);
//Set and Get
layer.setProperties(rasterFadeDuration(0.3f));
assertEquals((Float) layer.getRasterFadeDuration().getValue(), (Float) 0.3f);
}
//Set and Get
layer.setProperties(rasterFadeDuration(0.3f));
assertEquals((Float) layer.getRasterFadeDuration().getValue(), (Float) 0.3f);
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
}

View File

@@ -1,11 +1,9 @@
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make android-style-code`.
package com.mapbox.mapboxsdk.testapp.style;
// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make android-style-code`.
import android.graphics.Color;
import android.support.test.espresso.Espresso;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import timber.log.Timber;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.style.layers.RasterLayer;
@@ -19,9 +17,20 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
import static com.mapbox.mapboxsdk.style.layers.Property.*;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
import timber.log.Timber;
import static com.mapbox.mapboxsdk.style.layers.Property.NONE;
import static com.mapbox.mapboxsdk.style.layers.Property.VISIBLE;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.rasterBrightnessMax;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.rasterBrightnessMin;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.rasterContrast;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.rasterFadeDuration;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.rasterHueRotate;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.rasterOpacity;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.rasterSaturation;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.visibility;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Basic smoke tests for RasterLayer
@@ -29,203 +38,203 @@ import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.*;
@RunWith(AndroidJUnit4.class)
public class RasterLayerTest extends BaseStyleTest {
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
private RasterLayer layer;
private RasterLayer layer;
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
private MapboxMap mapboxMap;
private MapboxMap mapboxMap;
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
@Before
public void setup() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("visibility");
assertNotNull(layer);
@Test
public void testSetVisibility() {
checkViewIsDisplayed(R.id.mapView);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
mapboxMap = rule.getActivity().getMapboxMap();
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
}
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("visibility");
assertNotNull(layer);
@Test
public void testRasterOpacity() {
checkViewIsDisplayed(R.id.mapView);
//Get initial
assertEquals(layer.getVisibility().getValue(), VISIBLE);
mapboxMap = rule.getActivity().getMapboxMap();
//Set
layer.setProperties(visibility(NONE));
assertEquals(layer.getVisibility().getValue(), NONE);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-opacity");
assertNotNull(layer);
@Test
public void testRasterOpacity() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(rasterOpacity(0.3f));
assertEquals((Float) layer.getRasterOpacity().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testRasterHueRotate() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-opacity");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(rasterOpacity(0.3f));
assertEquals((Float) layer.getRasterOpacity().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-hue-rotate");
assertNotNull(layer);
@Test
public void testRasterHueRotate() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(rasterHueRotate(0.3f));
assertEquals((Float) layer.getRasterHueRotate().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testRasterBrightnessMin() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-hue-rotate");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(rasterHueRotate(0.3f));
assertEquals((Float) layer.getRasterHueRotate().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-brightness-min");
assertNotNull(layer);
@Test
public void testRasterBrightnessMin() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(rasterBrightnessMin(0.3f));
assertEquals((Float) layer.getRasterBrightnessMin().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testRasterBrightnessMax() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-brightness-min");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(rasterBrightnessMin(0.3f));
assertEquals((Float) layer.getRasterBrightnessMin().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-brightness-max");
assertNotNull(layer);
@Test
public void testRasterBrightnessMax() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(rasterBrightnessMax(0.3f));
assertEquals((Float) layer.getRasterBrightnessMax().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testRasterSaturation() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-brightness-max");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(rasterBrightnessMax(0.3f));
assertEquals((Float) layer.getRasterBrightnessMax().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-saturation");
assertNotNull(layer);
@Test
public void testRasterSaturation() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(rasterSaturation(0.3f));
assertEquals((Float) layer.getRasterSaturation().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testRasterContrast() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-saturation");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(rasterSaturation(0.3f));
assertEquals((Float) layer.getRasterSaturation().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-contrast");
assertNotNull(layer);
@Test
public void testRasterContrast() {
checkViewIsDisplayed(R.id.mapView);
//Set and Get
layer.setProperties(rasterContrast(0.3f));
assertEquals((Float) layer.getRasterContrast().getValue(), (Float) 0.3f);
}
mapboxMap = rule.getActivity().getMapboxMap();
@Test
public void testRasterFadeDuration() {
checkViewIsDisplayed(R.id.mapView);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-contrast");
assertNotNull(layer);
mapboxMap = rule.getActivity().getMapboxMap();
//Set and Get
layer.setProperties(rasterContrast(0.3f));
assertEquals((Float) layer.getRasterContrast().getValue(), (Float) 0.3f);
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-fade-duration");
assertNotNull(layer);
@Test
public void testRasterFadeDuration() {
checkViewIsDisplayed(R.id.mapView);
mapboxMap = rule.getActivity().getMapboxMap();
if ((layer = mapboxMap.getLayerAs("my-layer")) == null) {
Timber.i("Adding layer");
layer = new RasterLayer("my-layer", "composite");
layer.setSourceLayer("composite");
mapboxMap.addLayer(layer);
//Layer reference is now stale, get new reference
layer = mapboxMap.getLayerAs("my-layer");
}
Timber.i("raster-fade-duration");
assertNotNull(layer);
//Set and Get
layer.setProperties(rasterFadeDuration(0.3f));
assertEquals((Float) layer.getRasterFadeDuration().getValue(), (Float) 0.3f);
}
//Set and Get
layer.setProperties(rasterFadeDuration(0.3f));
assertEquals((Float) layer.getRasterFadeDuration().getValue(), (Float) 0.3f);
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
}

View File

@@ -3,6 +3,7 @@ package com.mapbox.mapboxsdk.testapp.style;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.test.ActivityInstrumentationTestCase2;
import timber.log.Timber;
import com.mapbox.mapboxsdk.maps.MapboxMap;
@@ -22,39 +23,39 @@ import org.junit.runner.RunWith;
*/
@RunWith(AndroidJUnit4.class)
public class RuntimeStyleBackgroundLayerTest
extends ActivityInstrumentationTestCase2<RuntimeStyleTestActivity> {
extends ActivityInstrumentationTestCase2<RuntimeStyleTestActivity> {
public RuntimeStyleBackgroundLayerTest() {
super(RuntimeStyleTestActivity.class);
}
public RuntimeStyleBackgroundLayerTest() {
super(RuntimeStyleTestActivity.class);
}
@Before
public void setUp() throws Exception {
super.setUp();
injectInstrumentation(InstrumentationRegistry.getInstrumentation());
}
@Before
public void setUp() throws Exception {
super.setUp();
injectInstrumentation(InstrumentationRegistry.getInstrumentation());
}
@Test
public void testSetVisibility() {
getActivity().mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap mapboxMap) {
Timber.i("visibility");
BackgroundLayer layer = mapboxMap.getLayerAs("background");
assertNotNull(layer);
@Test
public void testSetVisibility() {
getActivity().mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap mapboxMap) {
Timber.i("visibility");
BackgroundLayer layer = mapboxMap.getLayerAs("background");
assertNotNull(layer);
//Get initial
assertEquals(layer.getVisibility().getValue(), Property.VISIBLE);
//Get initial
assertEquals(layer.getVisibility().getValue(), Property.VISIBLE);
//Set
layer.setProperties(PropertyFactory.visibility(Property.NONE));
assertEquals(layer.getVisibility().getValue(), Property.NONE);
}
});
}
//Set
layer.setProperties(PropertyFactory.visibility(Property.NONE));
assertEquals(layer.getVisibility().getValue(), Property.NONE);
}
});
}
@After
public void tearDown() throws Exception {
super.tearDown();
}
@After
public void tearDown() throws Exception {
super.tearDown();
}
}

View File

@@ -45,157 +45,157 @@ import static org.junit.Assert.assertNull;
@RunWith(AndroidJUnit4.class)
public class RuntimeStyleTests {
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
@Rule
public final ActivityTestRule<RuntimeStyleTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTestActivity.class);
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
public void testGetAddRemoveLayer() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
onView(withId(R.id.mapView)).perform(new AddRemoveLayerAction());
}
@Test
public void testAddRemoveSource() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
mapboxMap.addSource(new VectorSource("my-source", "mapbox://mapbox.mapbox-terrain-v2"));
try {
mapboxMap.removeSource("my-source");
} catch (NoSuchSourceException noSuchSourceException) {
// it's ok..
}
@Test
public void testGetAddRemoveLayer() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
onView(withId(R.id.mapView)).perform(new AddRemoveLayerAction());
onView(withId(R.id.mapView)).perform(new AddRemoveSourceAction());
}
private class AddRemoveLayerAction implements ViewAction {
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Test
public void testAddRemoveSource() {
ViewUtils.checkViewIsDisplayed(R.id.mapView);
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
mapboxMap.addSource(new VectorSource("my-source", "mapbox://mapbox.mapbox-terrain-v2"));
try {
mapboxMap.removeSource("my-source");
} catch (NoSuchSourceException e) {
// it's ok..
}
onView(withId(R.id.mapView)).perform(new AddRemoveSourceAction());
@Override
public String getDescription() {
return getClass().getSimpleName();
}
private class AddRemoveLayerAction implements ViewAction {
@Override
public void perform(UiController uiController, View view) {
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
//Get initial
assertNotNull(mapboxMap.getLayer("building"));
@Override
public String getDescription() {
return getClass().getSimpleName();
}
//Remove
try {
mapboxMap.removeLayer("building");
} catch (NoSuchLayerException noSuchSourceException) {
fail("Definitively exists: " + noSuchSourceException.getMessage());
}
assertNull(mapboxMap.getLayer("building"));
@Override
public void perform(UiController uiController, View view) {
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
//Add
FillLayer layer = new FillLayer("building", "composite");
layer.setSourceLayer("building");
mapboxMap.addLayer(layer);
assertNotNull(mapboxMap.getLayer("building"));
//Get initial
assertNotNull(mapboxMap.getLayer("building"));
//Assure the reference still works
layer.setProperties(PropertyFactory.visibility(Property.VISIBLE));
//Remove
try {
mapboxMap.removeLayer("building");
} catch (NoSuchLayerException e) {
fail("Definitively exists: " + e.getMessage());
}
assertNull(mapboxMap.getLayer("building"));
//Remove, preserving the reference
try {
mapboxMap.removeLayer(layer);
} catch (NoSuchLayerException noSuchSourceException) {
fail("Definitively exists: " + noSuchSourceException.getMessage());
}
//Add
FillLayer layer = new FillLayer("building", "composite");
layer.setSourceLayer("building");
mapboxMap.addLayer(layer);
assertNotNull(mapboxMap.getLayer("building"));
//Property setters should still work
layer.setProperties(PropertyFactory.fillColor(Color.RED));
//Assure the reference still works
layer.setProperties(PropertyFactory.visibility(Property.VISIBLE));
//Re-add the reference...
mapboxMap.addLayer(layer);
//Remove, preserving the reference
try {
mapboxMap.removeLayer(layer);
} catch (NoSuchLayerException e) {
fail("Definitively exists: " + e.getMessage());
}
//Ensure it's there
Assert.assertNotNull(mapboxMap.getLayer(layer.getId()));
//Property setters should still work
layer.setProperties(PropertyFactory.fillColor(Color.RED));
//Test adding a duplicate layer
try {
mapboxMap.addLayer(new FillLayer("building", "composite"));
fail("Should not have been allowed to add a layer with a duplicate id");
} catch (CannotAddLayerException cannotAddLayerException) {
//OK
}
}
}
//Re-add the reference...
mapboxMap.addLayer(layer);
private class AddRemoveSourceAction implements ViewAction {
//Ensure it's there
Assert.assertNotNull(mapboxMap.getLayer(layer.getId()));
//Test adding a duplicate layer
try {
mapboxMap.addLayer(new FillLayer("building", "composite"));
fail("Should not have been allowed to add a layer with a duplicate id");
} catch (CannotAddLayerException e) {
//OK
}
}
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
private class AddRemoveSourceAction implements ViewAction {
@Override
public Matcher<View> getConstraints() {
return isDisplayed();
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@Override
public void perform(UiController uiController, View view) {
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
//Add initial source
mapboxMap.addSource(new VectorSource("my-source", "mapbox://mapbox.mapbox-terrain-v2"));
//Remove
try {
mapboxMap.removeSource("my-source");
} catch (NoSuchSourceException e) {
fail("Definitively exists: " + e.getMessage());
}
assertNull(mapboxMap.getLayer("my-source"));
//Add
Source source = new VectorSource("my-source", "mapbox://mapbox.mapbox-terrain-v2");
mapboxMap.addSource(source);
//Remove, preserving the reference
try {
mapboxMap.removeSource(source);
} catch (NoSuchSourceException e) {
fail("Definitively exists: " + e.getMessage());
}
//Re-add the reference...
mapboxMap.addSource(source);
//Ensure it's there
Assert.assertNotNull(mapboxMap.getSource(source.getId()));
//Test adding a duplicate source
try {
Source source2 = new VectorSource("my-source", "mapbox://mapbox.mapbox-terrain-v2");
mapboxMap.addSource(source2);
fail("Should not have been allowed to add a source with a duplicate id");
} catch (CannotAddSourceException e) {
//OK
}
}
@Override
public String getDescription() {
return getClass().getSimpleName();
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
@Override
public void perform(UiController uiController, View view) {
MapboxMap mapboxMap = rule.getActivity().getMapboxMap();
//Add initial source
mapboxMap.addSource(new VectorSource("my-source", "mapbox://mapbox.mapbox-terrain-v2"));
//Remove
try {
mapboxMap.removeSource("my-source");
} catch (NoSuchSourceException noSuchSourceException) {
fail("Definitively exists: " + noSuchSourceException.getMessage());
}
assertNull(mapboxMap.getLayer("my-source"));
//Add
Source source = new VectorSource("my-source", "mapbox://mapbox.mapbox-terrain-v2");
mapboxMap.addSource(source);
//Remove, preserving the reference
try {
mapboxMap.removeSource(source);
} catch (NoSuchSourceException noSuchSourceException) {
fail("Definitively exists: " + noSuchSourceException.getMessage());
}
//Re-add the reference...
mapboxMap.addSource(source);
//Ensure it's there
Assert.assertNotNull(mapboxMap.getSource(source.getId()));
//Test adding a duplicate source
try {
Source source2 = new VectorSource("my-source", "mapbox://mapbox.mapbox-terrain-v2");
mapboxMap.addSource(source2);
fail("Should not have been allowed to add a source with a duplicate id");
} catch (CannotAddSourceException cannotAddSourceException) {
//OK
}
}
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
}

View File

@@ -20,25 +20,26 @@ import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
public class RuntimeStyleTimingTests extends BaseStyleTest {
@Rule
public final ActivityTestRule<RuntimeStyleTimingTestActivity> rule = new ActivityTestRule<>(RuntimeStyleTimingTestActivity.class);
@Rule
public final ActivityTestRule<RuntimeStyleTimingTestActivity> rule =
new ActivityTestRule<>(RuntimeStyleTimingTestActivity.class);
private OnMapReadyIdlingResource idlingResource;
private OnMapReadyIdlingResource idlingResource;
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Before
public void registerIdlingResource() {
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
Espresso.registerIdlingResources(idlingResource);
}
@Test
public void testGetAddRemoveLayer() {
checkViewIsDisplayed(R.id.mapView);
//We're good if it didn't crash
}
@Test
public void testGetAddRemoveLayer() {
checkViewIsDisplayed(R.id.mapView);
//We're good if it didn't crash
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
@After
public void unregisterIntentServiceIdlingResource() {
Espresso.unregisterIdlingResources(idlingResource);
}
}

View File

@@ -15,15 +15,15 @@ import static android.support.test.espresso.matcher.ViewMatchers.withContentDesc
public class DrawerUtils {
private final static String HOME_BUTTON_STRING = "Navigate up";
private static final String HOME_BUTTON_STRING = "Navigate up";
public static void openDrawer(){
onView(withContentDescription(HOME_BUTTON_STRING)).perform(click());
}
public static void openDrawer() {
onView(withContentDescription(HOME_BUTTON_STRING)).perform(click());
}
public static void clickItem(@StringRes int txtId){
Espresso.onView(Matchers.allOf(ViewMatchers.withId(R.id.design_menu_item_text),
ViewMatchers.hasSibling(ViewMatchers.withText(txtId)))).perform(ViewActions.click());
}
public static void clickItem(@StringRes int txtId) {
Espresso.onView(Matchers.allOf(ViewMatchers.withId(R.id.design_menu_item_text),
ViewMatchers.hasSibling(ViewMatchers.withText(txtId)))).perform(ViewActions.click());
}
}

View File

@@ -8,8 +8,8 @@ import static android.support.test.espresso.matcher.ViewMatchers.withId;
public class GestureUtils {
public static void doubleClickGesture(@IdRes int id){
onView(withId(id)).perform(doubleClick());
}
public static void doubleClickGesture(@IdRes int id) {
onView(withId(id)).perform(doubleClick());
}
}

View File

@@ -2,6 +2,7 @@ package com.mapbox.mapboxsdk.testapp.utils;
import android.app.Activity;
import android.support.test.espresso.IdlingResource;
import timber.log.Timber;
import com.mapbox.mapboxsdk.maps.MapboxMap;
@@ -10,47 +11,47 @@ import java.lang.reflect.Field;
public class OnMapReadyIdlingResource implements IdlingResource {
private final Activity activity;
private MapboxMap mapboxMap;
private IdlingResource.ResourceCallback resourceCallback;
private final Activity activity;
private MapboxMap mapboxMap;
private IdlingResource.ResourceCallback resourceCallback;
public OnMapReadyIdlingResource(Activity activity) {
this.activity = activity;
}
public OnMapReadyIdlingResource(Activity activity) {
this.activity = activity;
}
@Override
public String getName() {
return getClass().getSimpleName();
}
@Override
public String getName() {
return getClass().getSimpleName();
}
@Override
public boolean isIdleNow() {
boolean idle = isMapboxMapReady();
if (idle && resourceCallback != null) {
resourceCallback.onTransitionToIdle();
}
return idle;
@Override
public boolean isIdleNow() {
boolean idle = isMapboxMapReady();
if (idle && resourceCallback != null) {
resourceCallback.onTransitionToIdle();
}
return idle;
}
@Override
public void registerIdleTransitionCallback(ResourceCallback resourceCallback) {
this.resourceCallback = resourceCallback;
}
@Override
public void registerIdleTransitionCallback(ResourceCallback resourceCallback) {
this.resourceCallback = resourceCallback;
}
private boolean isMapboxMapReady() {
try {
Field field = activity.getClass().getDeclaredField("mapboxMap");
field.setAccessible(true);
mapboxMap = (MapboxMap) field.get(activity);
Timber.e("isMapboxReady called with value " + (mapboxMap != null));
return mapboxMap != null;
} catch (Exception e) {
Timber.e("could not reflect", e);
return false;
}
private boolean isMapboxMapReady() {
try {
Field field = activity.getClass().getDeclaredField("mapboxMap");
field.setAccessible(true);
mapboxMap = (MapboxMap) field.get(activity);
Timber.e("isMapboxReady called with value " + (mapboxMap != null));
return mapboxMap != null;
} catch (Exception exception) {
Timber.e("could not reflect", exception);
return false;
}
}
public MapboxMap getMapboxMap() {
return mapboxMap;
}
public MapboxMap getMapboxMap() {
return mapboxMap;
}
}

View File

@@ -4,7 +4,9 @@ import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Environment;
import timber.log.Timber;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
@@ -23,112 +25,113 @@ import java.util.UUID;
*/
public class ScreenshotUtil {
// Where to store the files. This path is required by AWS Device Farm:
// http://docs.aws.amazon.com/devicefarm/latest/developerguide/test-types-android-instrumentation.html#test-types-android-instrumentation-screenshots
private static final String SCREENSHOT_FOLDER = "test-screenshots";
// Where to store the files. This path is required by AWS Device Farm:
// http://docs.aws.amazon.com/devicefarm/latest/developerguide/test-types-android-instrumentation.html
// #test-types-android-instrumentation-screenshots
private static final String SCREENSHOT_FOLDER = "test-screenshots";
// Image type and quality
private static final String DEFAULT_IMAGE_EXTENSION = ".png";
private static final Bitmap.CompressFormat DEFAULT_IMAGE_FORMAT = Bitmap.CompressFormat.PNG;
private static final int DEFAULT_IMAGE_QUALITY = 100;
// Image type and quality
private static final String DEFAULT_IMAGE_EXTENSION = ".png";
private static final Bitmap.CompressFormat DEFAULT_IMAGE_FORMAT = Bitmap.CompressFormat.PNG;
private static final int DEFAULT_IMAGE_QUALITY = 100;
public static void take(Activity activity, String testName) {
public static void take(Activity activity, String testName) {
// Check if storage is available
if (!isExternalStorageWritable()) {
Timber.d("External storage is not available.");
return;
}
// Check if storage is available
if (!isExternalStorageWritable()) {
Timber.d("External storage is not available.");
return;
}
// Get a bitmap from the activity root view. When the drawing cache is enabled,
// // the next call to getDrawingCache() will draw the view in a bitmap.
View rootView = activity.getWindow().getDecorView().getRootView();
// rootView.setDrawingCacheEnabled(true);r
// rootView.setDrawingCacheEnabled(false);
// Get a bitmap from the activity root view. When the drawing cache is enabled,
// the next call to getDrawingCache() will draw the view in a bitmap.
View rootView = activity.getWindow().getDecorView().getRootView();
// rootView.setDrawingCacheEnabled(true);r
// rootView.setDrawingCacheEnabled(false);
Bitmap bitmap = null;
Bitmap bitmap = null;
// Add the SurfaceView bit (see getAllTextureViews() below)
List<TextureView> tilingViews = getAllTextureViews(rootView);
if (tilingViews.size() > 0) {
bitmap = Bitmap.createBitmap(tilingViews.get(0).getHeight(),tilingViews.get(0).getWidth(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
for (TextureView TextureView : tilingViews) {
Bitmap b = TextureView.getBitmap(TextureView.getWidth(), TextureView.getHeight());
int[] location = new int[2];
TextureView.getLocationInWindow(location);
int[] location2 = new int[2];
TextureView.getLocationOnScreen(location2);
canvas.drawBitmap(b, 0,0, null);
}
}
// Add the SurfaceView bit (see getAllTextureViews() below)
List<TextureView> tilingViews = getAllTextureViews(rootView);
if (tilingViews.size() > 0) {
bitmap = Bitmap.createBitmap(tilingViews.get(0).getHeight(), tilingViews.get(0).getWidth(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
for (TextureView TextureView : tilingViews) {
Bitmap b = TextureView.getBitmap(TextureView.getWidth(), TextureView.getHeight());
int[] location = new int[2];
TextureView.getLocationInWindow(location);
int[] location2 = new int[2];
TextureView.getLocationOnScreen(location2);
canvas.drawBitmap(b, 0, 0, null);
}
}
// Save the bitmap in external storage
String uniqueAbsolutePath = getUniqueAbsolutePath(testName);
File outputFile = new File(uniqueAbsolutePath);
OutputStream outputStream = null;
// Save the bitmap in external storage
String uniqueAbsolutePath = getUniqueAbsolutePath(testName);
File outputFile = new File(uniqueAbsolutePath);
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(outputFile);
bitmap.compress(DEFAULT_IMAGE_FORMAT, DEFAULT_IMAGE_QUALITY, outputStream);
outputStream.flush();
} catch (Exception exception) {
exception.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream = new FileOutputStream(outputFile);
bitmap.compress(DEFAULT_IMAGE_FORMAT, DEFAULT_IMAGE_QUALITY, outputStream);
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
outputStream.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
}
/*
* The classic way of taking a screenshot (above) doesn't work with TextureView, this fixes it:
* http://stackoverflow.com/questions/19704060/screen-capture-textureview-is-black-using-drawingcache
*/
public static List<TextureView> getAllTextureViews(View view) {
List<TextureView> tilingViews = new ArrayList<TextureView>();
if (view instanceof TextureView) {
tilingViews.add((TextureView) view);
} else if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
tilingViews.addAll(getAllTextureViews(viewGroup.getChildAt(i)));
}
}
/*
* The classic way of taking a screenshot (above) doesn't work with TextureView, this fixes it:
* http://stackoverflow.com/questions/19704060/screen-capture-textureview-is-black-using-drawingcache
*/
return tilingViews;
}
public static List<TextureView> getAllTextureViews(View view)
{
List<TextureView> tilingViews = new ArrayList<TextureView>();
if (view instanceof TextureView) {
tilingViews.add((TextureView)view);
} else if(view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup)view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
tilingViews.addAll(getAllTextureViews(viewGroup.getChildAt(i)));
}
}
/*
* Utils
*/
return tilingViews;
public static boolean isExternalStorageWritable() {
// Checks if external storage is available for read and write
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
private static String getUniqueAbsolutePath(String testName) {
// A screenshot after every test vs. manual tests
String filename = UUID.randomUUID().toString() + DEFAULT_IMAGE_EXTENSION;
if (testName != null && !testName.isEmpty()) {
filename = testName + DEFAULT_IMAGE_EXTENSION;
}
/*
* Utils
*/
public static boolean isExternalStorageWritable() {
// Checks if external storage is available for read and write
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
private static String getUniqueAbsolutePath(String testName) {
// A screenshot after every test vs. manual tests
String filename = UUID.randomUUID().toString() + DEFAULT_IMAGE_EXTENSION;
if (testName != null && !testName.isEmpty()) {
filename = testName + DEFAULT_IMAGE_EXTENSION;
}
String externalPath = Environment.getExternalStorageDirectory().toString();
String path = externalPath + File.separator + SCREENSHOT_FOLDER;
File dir = new File(path);
dir.mkdirs();
path += File.separator + filename;
Timber.d("Screenshot path: " + path);
return path;
}
String externalPath = Environment.getExternalStorageDirectory().toString();
String path = externalPath + File.separator + SCREENSHOT_FOLDER;
File dir = new File(path);
dir.mkdirs();
path += File.separator + filename;
Timber.d("Screenshot path: " + path);
return path;
}
}

View File

@@ -4,15 +4,15 @@ import com.mapbox.mapboxsdk.constants.MapboxConstants;
public class TestConstants {
public static final long ANIMATION_TEST_TIME = MapboxConstants.ANIMATION_DURATION * 2;
public static final long ANIMATION_TEST_TIME = MapboxConstants.ANIMATION_DURATION * 2;
public static final double LAT_LNG_DELTA_LARGE = 0.1;
public static final double LAT_LNG_DELTA = 0.01;
public static final double BEARING_DELTA = 0.1;
public static final double TILT_DELTA = 0.1;
public static final double ZOOM_DELTA = 0.3;
public static final double LAT_LNG_DELTA_LARGE = 0.1;
public static final double LAT_LNG_DELTA = 0.01;
public static final double BEARING_DELTA = 0.1;
public static final double TILT_DELTA = 0.1;
public static final double ZOOM_DELTA = 0.3;
public static final String TEXT_MARKER_TEXT = "Text";
public static final String TEXT_MARKER_TITLE = "Marker";
public static final String TEXT_MARKER_SNIPPET = "Snippet";
public static final String TEXT_MARKER_TEXT = "Text";
public static final String TEXT_MARKER_TITLE = "Marker";
public static final String TEXT_MARKER_SNIPPET = "Snippet";
}

View File

@@ -10,13 +10,13 @@ import static android.support.test.espresso.matcher.ViewMatchers.withId;
public class ViewUtils {
public static void clickView(@IdRes int viewRes) {
onView(withId(viewRes))
.perform(click());
}
public static void clickView(@IdRes int viewRes) {
onView(withId(viewRes))
.perform(click());
}
public static void checkViewIsDisplayed(int id) {
onView(withId(id))
.check(matches(isDisplayed()));
}
public static void checkViewIsDisplayed(int id) {
onView(withId(id))
.check(matches(isDisplayed()));
}
}

View File

@@ -5,43 +5,44 @@ import android.os.StrictMode;
import com.mapbox.mapboxsdk.MapboxAccountManager;
import com.squareup.leakcanary.LeakCanary;
import timber.log.Timber;
import static timber.log.Timber.DebugTree;
public class MapboxApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
@Override
public void onCreate() {
super.onCreate();
if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return;
}
LeakCanary.install(this);
initializeLogger();
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.penaltyLog()
.penaltyDeath()
.build());
MapboxAccountManager.start(getApplicationContext(), getString(R.string.mapbox_access_token));
if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return;
}
LeakCanary.install(this);
private void initializeLogger() {
if (BuildConfig.DEBUG) {
Timber.plant(new DebugTree());
}
initializeLogger();
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.penaltyLog()
.penaltyDeath()
.build());
MapboxAccountManager.start(getApplicationContext(), getString(R.string.mapbox_access_token));
}
private void initializeLogger() {
if (BuildConfig.DEBUG) {
Timber.plant(new DebugTree());
}
}
}

View File

@@ -19,7 +19,9 @@ import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.View;
import com.mapbox.mapboxsdk.testapp.R;
@@ -35,199 +37,199 @@ import java.util.List;
public class FeatureOverviewActivity extends AppCompatActivity {
private static final String KEY_STATE_FEATURES = "featureList";
private static final String KEY_STATE_FEATURES = "featureList";
private RecyclerView recyclerView;
private FeatureSectionAdapter sectionAdapter;
private List<Feature> features;
private RecyclerView recyclerView;
private FeatureSectionAdapter sectionAdapter;
private List<Feature> features;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getString(R.string.app_name));
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setElevation(getResources().getDimension(R.dimen.toolbar_shadow));
}
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addOnItemTouchListener(new RecyclerView.SimpleOnItemTouchListener());
recyclerView.setHasFixedSize(true);
ItemClickSupport.addTo(recyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
@Override
public void onItemClicked(RecyclerView recyclerView, int position, View view) {
if (!sectionAdapter.isSectionHeaderPosition(position)) {
int itemPosition = sectionAdapter.getConvertedPosition(position);
Feature feature = features.get(itemPosition);
if (feature.isRequiresLocationPermission()) {
if (requestLocationPermission(itemPosition)) {
return;
}
}
startFeature(feature);
}
}
});
if (savedInstanceState == null) {
loadFeatures();
} else {
features = savedInstanceState.getParcelableArrayList(KEY_STATE_FEATURES);
onFeaturesLoaded(features);
}
}
private void loadFeatures() {
try {
new LoadFeatureTask().execute(
getPackageManager().getPackageInfo(getPackageName(),
PackageManager.GET_ACTIVITIES | PackageManager.GET_META_DATA));
} catch (PackageManager.NameNotFoundException exception) {
Timber.e("Could not resolve package info", exception);
}
}
private void onFeaturesLoaded(List<Feature> featuresList) {
features = featuresList;
List<FeatureSectionAdapter.Section> sections = new ArrayList<>();
String currentCat = "";
for (int i = 0; i < features.size(); i++) {
String category = features.get(i).getCategory();
if (!currentCat.equals(category)) {
sections.add(new FeatureSectionAdapter.Section(i, category));
currentCat = category;
}
}
FeatureSectionAdapter.Section[] dummy = new FeatureSectionAdapter.Section[sections.size()];
sectionAdapter = new FeatureSectionAdapter(
this, R.layout.section_main_layout, R.id.section_text, new FeatureAdapter(features));
sectionAdapter.setSections(sections.toArray(dummy));
recyclerView.setAdapter(sectionAdapter);
}
private void startFeature(Feature feature) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(getPackageName(), feature.getName()));
startActivity(intent);
}
private boolean requestLocationPermission(final int positionInList) {
if ((ContextCompat.checkSelfPermission(FeatureOverviewActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
|| (ContextCompat.checkSelfPermission(FeatureOverviewActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(FeatureOverviewActivity.this, new String[] {
Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, positionInList);
return true;
} else {
return false;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startFeature(features.get(requestCode));
} else {
Snackbar.make(
findViewById(android.R.id.content),
"Can't open without accepting the location permission.",
Snackbar.LENGTH_SHORT).show();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(KEY_STATE_FEATURES, (ArrayList<Feature>) features);
}
private class LoadFeatureTask extends AsyncTask<PackageInfo, Void, List<Feature>> {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
protected List<Feature> doInBackground(PackageInfo... params) {
List<Feature> features = new ArrayList<>();
PackageInfo app = params[0];
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getString(R.string.app_name));
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setElevation(getResources().getDimension(R.dimen.toolbar_shadow));
String packageName = getApplicationContext().getPackageName();
String metaDataKey = getString(R.string.category);
for (ActivityInfo info : app.activities) {
if (info.labelRes != 0 && info.name.startsWith(packageName)
&& !info.name.equals(FeatureOverviewActivity.class.getName())) {
String label = getString(info.labelRes);
String description = resolveString(info.descriptionRes);
String category = resolveMetaData(info.metaData, metaDataKey);
boolean requiresLocationPermission = requiresLocationPermission(label, category);
features.add(new Feature(info.name, label, description, category, requiresLocationPermission));
}
}
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addOnItemTouchListener(new RecyclerView.SimpleOnItemTouchListener());
recyclerView.setHasFixedSize(true);
ItemClickSupport.addTo(recyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
@Override
public void onItemClicked(RecyclerView recyclerView, int position, View view) {
if (!sectionAdapter.isSectionHeaderPosition(position)) {
int itemPosition = sectionAdapter.getConvertedPosition(position);
Feature feature = features.get(itemPosition);
if (feature.isRequiresLocationPermission()) {
if (requestLocationPermission(itemPosition)) {
return;
}
}
startFeature(feature);
}
if (!features.isEmpty()) {
Comparator<Feature> comparator = new Comparator<Feature>() {
@Override
public int compare(Feature lhs, Feature rhs) {
int result = lhs.getCategory().compareToIgnoreCase(rhs.getCategory());
if (result == 0) {
result = lhs.getLabel().compareToIgnoreCase(rhs.getLabel());
}
});
return result;
}
};
Collections.sort(features, comparator);
}
if (savedInstanceState == null) {
loadFeatures();
} else {
features = savedInstanceState.getParcelableArrayList(KEY_STATE_FEATURES);
onFeaturesLoaded(features);
}
return features;
}
private void loadFeatures() {
try {
new LoadFeatureTask().execute(
getPackageManager().getPackageInfo(getPackageName(),
PackageManager.GET_ACTIVITIES | PackageManager.GET_META_DATA));
} catch (PackageManager.NameNotFoundException exception) {
Timber.e("Could not resolve package info", exception);
}
private String resolveMetaData(Bundle bundle, String key) {
String category = null;
if (bundle != null) {
category = bundle.getString(key);
}
return category;
}
private void onFeaturesLoaded(List<Feature> featuresList) {
features = featuresList;
List<FeatureSectionAdapter.Section> sections = new ArrayList<>();
String currentCat = "";
for (int i = 0; i < features.size(); i++) {
String category = features.get(i).getCategory();
if (!currentCat.equals(category)) {
sections.add(new FeatureSectionAdapter.Section(i, category));
currentCat = category;
}
}
FeatureSectionAdapter.Section[] dummy = new FeatureSectionAdapter.Section[sections.size()];
sectionAdapter = new FeatureSectionAdapter(
this, R.layout.section_main_layout, R.id.section_text, new FeatureAdapter(features));
sectionAdapter.setSections(sections.toArray(dummy));
recyclerView.setAdapter(sectionAdapter);
private String resolveString(@StringRes int stringRes) {
try {
return getString(stringRes);
} catch (Resources.NotFoundException exception) {
return "-";
}
}
private void startFeature(Feature feature) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(getPackageName(), feature.getName()));
startActivity(intent);
}
private boolean requiresLocationPermission(String name, String category) {
final Resources resources = getResources();
private boolean requestLocationPermission(final int positionInList) {
if ((ContextCompat.checkSelfPermission(FeatureOverviewActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
|| (ContextCompat.checkSelfPermission(FeatureOverviewActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(FeatureOverviewActivity.this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, positionInList);
return true;
} else {
return false;
List<String> requiresPermissionCategories = new ArrayList<String>() {
{
add(resources.getString(R.string.category_userlocation));
}
};
List<String> requiresPermissionActvities = new ArrayList<String>() {
{
add(resources.getString(R.string.activity_double_map));
add(getString(R.string.activity_location_picker));
add(getString(R.string.activity_car_driving));
}
};
return requiresPermissionCategories.contains(category) || requiresPermissionActvities.contains(name);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startFeature(features.get(requestCode));
} else {
Snackbar.make(
findViewById(android.R.id.content),
"Can't open without accepting the location permission.",
Snackbar.LENGTH_SHORT).show();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(KEY_STATE_FEATURES, (ArrayList<Feature>) features);
}
private class LoadFeatureTask extends AsyncTask<PackageInfo, Void, List<Feature>> {
@Override
protected List<Feature> doInBackground(PackageInfo... params) {
List<Feature> features = new ArrayList<>();
PackageInfo app = params[0];
String packageName = getApplicationContext().getPackageName();
String metaDataKey = getString(R.string.category);
for (ActivityInfo info : app.activities) {
if (info.labelRes != 0 && info.name.startsWith(packageName)
&& !info.name.equals(FeatureOverviewActivity.class.getName())) {
String label = getString(info.labelRes);
String description = resolveString(info.descriptionRes);
String category = resolveMetaData(info.metaData, metaDataKey);
boolean requiresLocationPermission = requiresLocationPermission(label, category);
features.add(new Feature(info.name, label, description, category, requiresLocationPermission));
}
}
if (!features.isEmpty()) {
Comparator<Feature> comparator = new Comparator<Feature>() {
@Override
public int compare(Feature lhs, Feature rhs) {
int result = lhs.getCategory().compareToIgnoreCase(rhs.getCategory());
if (result == 0) {
result = lhs.getLabel().compareToIgnoreCase(rhs.getLabel());
}
return result;
}
};
Collections.sort(features, comparator);
}
return features;
}
private String resolveMetaData(Bundle bundle, String key) {
String category = null;
if (bundle != null) {
category = bundle.getString(key);
}
return category;
}
private String resolveString(@StringRes int stringRes) {
try {
return getString(stringRes);
} catch (Resources.NotFoundException exception) {
return "-";
}
}
private boolean requiresLocationPermission(String name, String category) {
final Resources resources = getResources();
List<String> requiresPermissionCategories = new ArrayList<String>() {
{
add(resources.getString(R.string.category_userlocation));
}
};
List<String> requiresPermissionActvities = new ArrayList<String>() {
{
add(resources.getString(R.string.activity_double_map));
add(getString(R.string.activity_location_picker));
add(getString(R.string.activity_car_driving));
}
};
return requiresPermissionCategories.contains(category) || requiresPermissionActvities.contains(name);
}
@Override
protected void onPostExecute(List<Feature> features) {
super.onPostExecute(features);
onFeaturesLoaded(features);
}
protected void onPostExecute(List<Feature> features) {
super.onPostExecute(features);
onFeaturesLoaded(features);
}
}
}

View File

@@ -4,7 +4,9 @@ import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.MenuItem;
import com.mapbox.mapboxsdk.annotations.Icon;
@@ -21,161 +23,161 @@ import com.mapbox.mapboxsdk.testapp.R;
public class AddRemoveMarkerActivity extends AppCompatActivity {
public static final double THRESHOLD = 5.0;
public static final double THRESHOLD = 5.0;
private MapView mapView;
private MapboxMap mapboxMap;
private double lastZoom;
private boolean isShowingHighThresholdMarker;
private boolean isShowingLowThresholdMarker;
private MapView mapView;
private MapboxMap mapboxMap;
private double lastZoom;
private boolean isShowingHighThresholdMarker;
private boolean isShowingLowThresholdMarker;
private MarkerOptions lowThresholdMarker;
private MarkerOptions highThresholdMarker;
private Marker activeMarker;
private MarkerOptions lowThresholdMarker;
private MarkerOptions highThresholdMarker;
private Marker activeMarker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_remove_marker);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_remove_marker);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
final Icon icon1 = IconFactory.getInstance(this).fromResource(R.drawable.ic_arsenal);
final Icon icon2 = IconFactory.getInstance(this).fromResource(R.drawable.ic_chelsea);
final Icon icon1 = IconFactory.getInstance(this).fromResource(R.drawable.ic_arsenal);
final Icon icon2 = IconFactory.getInstance(this).fromResource(R.drawable.ic_chelsea);
lowThresholdMarker = new MarkerOptions()
.icon(icon1)
.position(new LatLng(-0.1, 0));
lowThresholdMarker = new MarkerOptions()
.icon(icon1)
.position(new LatLng(-0.1, 0));
highThresholdMarker = new MarkerOptions()
.icon(icon2)
.position(new LatLng(0.1, 0));
highThresholdMarker = new MarkerOptions()
.icon(icon2)
.position(new LatLng(0.1, 0));
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap mapboxMap) {
AddRemoveMarkerActivity.this.mapboxMap = mapboxMap;
updateZoom(mapboxMap.getCameraPosition().zoom);
mapboxMap.moveCamera(CameraUpdateFactory.zoomTo(4.9f));
mapboxMap.setOnCameraChangeListener(new MapboxMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition position) {
updateZoom(position.zoom);
}
});
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap mapboxMap) {
AddRemoveMarkerActivity.this.mapboxMap = mapboxMap;
updateZoom(mapboxMap.getCameraPosition().zoom);
mapboxMap.moveCamera(CameraUpdateFactory.zoomTo(4.9f));
mapboxMap.setOnCameraChangeListener(new MapboxMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition position) {
updateZoom(position.zoom);
}
});
}
});
}
private void updateZoom(double zoom) {
if (lastZoom == zoom) {
return;
}
private void updateZoom(double zoom) {
if (lastZoom == zoom) {
return;
}
lastZoom = zoom;
if (zoom > THRESHOLD) {
showHighThresholdMarker();
} else {
showLowThresholdMarker();
}
}
lastZoom = zoom;
if (zoom > THRESHOLD) {
showHighThresholdMarker();
} else {
showLowThresholdMarker();
}
private void showLowThresholdMarker() {
if (isShowingLowThresholdMarker) {
return;
}
private void showLowThresholdMarker() {
if (isShowingLowThresholdMarker) {
return;
}
isShowingLowThresholdMarker = true;
isShowingHighThresholdMarker = false;
isShowingLowThresholdMarker = true;
isShowingHighThresholdMarker = false;
if (activeMarker != null) {
Timber.d("Remove marker with " + activeMarker.getId());
mapboxMap.removeMarker(activeMarker);
} else {
Timber.e("active marker is null");
}
activeMarker = mapboxMap.addMarker(lowThresholdMarker);
Timber.d("showLowThresholdMarker() " + activeMarker.getId());
if (activeMarker != null) {
Timber.d("Remove marker with " + activeMarker.getId());
mapboxMap.removeMarker(activeMarker);
} else {
Timber.e("active marker is null");
}
private void showHighThresholdMarker() {
if (isShowingHighThresholdMarker) {
return;
}
activeMarker = mapboxMap.addMarker(lowThresholdMarker);
Timber.d("showLowThresholdMarker() " + activeMarker.getId());
}
isShowingLowThresholdMarker = false;
isShowingHighThresholdMarker = true;
if (activeMarker != null) {
Timber.d("Remove marker with " + activeMarker.getId());
mapboxMap.removeMarker(activeMarker);
} else {
Timber.e("active marker is null");
}
activeMarker = mapboxMap.addMarker(highThresholdMarker);
Timber.d("showHighThresholdMarker() " + activeMarker.getId());
private void showHighThresholdMarker() {
if (isShowingHighThresholdMarker) {
return;
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
isShowingLowThresholdMarker = false;
isShowingHighThresholdMarker = true;
if (activeMarker != null) {
Timber.d("Remove marker with " + activeMarker.getId());
mapboxMap.removeMarker(activeMarker);
} else {
Timber.e("active marker is null");
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
activeMarker = mapboxMap.addMarker(highThresholdMarker);
Timber.d("showHighThresholdMarker() " + activeMarker.getId());
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}

View File

@@ -27,249 +27,245 @@ import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.testapp.R;
import com.mapbox.services.commons.models.Position;
import com.mapbox.services.commons.turf.TurfMeasurement;
import java.util.Random;
public class AnimatedMarkerActivity extends AppCompatActivity {
private MapView mapView;
private MapboxMap mapboxMap;
private MapView mapView;
private MapboxMap mapboxMap;
private LatLng dupontCircle = new LatLng(38.90962, -77.04341);
private LatLng dupontCircle = new LatLng(38.90962, -77.04341);
private Marker passengerMarker = null;
private MarkerView carMarker = null;
private Marker passengerMarker = null;
private MarkerView carMarker = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_animated_marker);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_animated_marker);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull final MapboxMap mapboxMap) {
AnimatedMarkerActivity.this.mapboxMap = mapboxMap;
setupMap();
mapView.post(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
addRandomCar();
}
addPassenger();
addMainCar();
}
});
@Override
public void onMapReady(@NonNull final MapboxMap mapboxMap) {
AnimatedMarkerActivity.this.mapboxMap = mapboxMap;
setupMap();
mapView.post(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
addRandomCar();
}
addPassenger();
addMainCar();
}
});
}
});
}
private void setupMap() {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(dupontCircle)
.zoom(15)
.build();
mapboxMap.setCameraPosition(cameraPosition);
}
private void addPassenger() {
LatLng randomLatLng = getLatLngInBounds();
if (passengerMarker == null) {
Icon icon = IconFactory.getInstance(AnimatedMarkerActivity.this)
.fromResource(R.drawable.ic_directions_run_black_24dp);
passengerMarker = mapboxMap.addMarker(new MarkerViewOptions()
.position(randomLatLng)
.icon(icon));
} else {
passengerMarker.setPosition(randomLatLng);
}
}
private void setupMap() {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(dupontCircle)
.zoom(15)
.build();
mapboxMap.setCameraPosition(cameraPosition);
}
private void addMainCar() {
LatLng randomLatLng = getLatLngInBounds();
private void addPassenger() {
LatLng randomLatLng = getLatLngInBounds();
if (passengerMarker == null) {
Icon icon = IconFactory.getInstance(AnimatedMarkerActivity.this)
.fromResource(R.drawable.ic_directions_run_black_24dp);
passengerMarker = mapboxMap.addMarker(new MarkerViewOptions()
.position(randomLatLng)
.icon(icon));
} else {
passengerMarker.setPosition(randomLatLng);
}
}
private void addMainCar() {
LatLng randomLatLng = getLatLngInBounds();
if (carMarker == null) {
carMarker = createCarMarker(randomLatLng, R.drawable.ic_taxi_top, new MarkerViewManager.OnMarkerViewAddedListener() {
@Override
public void onViewAdded(@NonNull MarkerView markerView) {
// Make sure the car marker is selected so that it's always brought to the front (#5285)
mapboxMap.selectMarker(carMarker);
animateMoveToPassenger(carMarker);
}
});
} else {
carMarker.setPosition(randomLatLng);
}
}
private void animateMoveToPassenger(final MarkerView car) {
ValueAnimator animator = animateMoveMarker(car, passengerMarker.getPosition());
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
addPassenger();
animateMoveToPassenger(car);
}
if (carMarker == null) {
carMarker = createCarMarker(randomLatLng, R.drawable.ic_taxi_top,
new MarkerViewManager.OnMarkerViewAddedListener() {
@Override
public void onViewAdded(@NonNull MarkerView markerView) {
// Make sure the car marker is selected so that it's always brought to the front (#5285)
mapboxMap.selectMarker(carMarker);
animateMoveToPassenger(carMarker);
}
});
} else {
carMarker.setPosition(randomLatLng);
}
}
protected void addRandomCar() {
createCarMarker(getLatLngInBounds(), R.drawable.ic_car_top, new MarkerViewManager.OnMarkerViewAddedListener() {
@Override
public void onViewAdded(@NonNull MarkerView markerView) {
randomlyMoveMarker(markerView);
}
});
}
private void animateMoveToPassenger(final MarkerView car) {
ValueAnimator animator = animateMoveMarker(car, passengerMarker.getPosition());
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
addPassenger();
animateMoveToPassenger(car);
}
});
}
private void randomlyMoveMarker(final MarkerView marker) {
ValueAnimator animator = animateMoveMarker(marker, getLatLngInBounds());
protected void addRandomCar() {
createCarMarker(getLatLngInBounds(), R.drawable.ic_car_top, new MarkerViewManager.OnMarkerViewAddedListener() {
@Override
public void onViewAdded(@NonNull MarkerView markerView) {
randomlyMoveMarker(markerView);
}
});
}
//Add listener to restart animation on end
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
randomlyMoveMarker(marker);
}
});
}
private void randomlyMoveMarker(final MarkerView marker) {
ValueAnimator animator = animateMoveMarker(marker, getLatLngInBounds());
private ValueAnimator animateMoveMarker(final MarkerView marker, LatLng to) {
marker.setRotation((float) getBearing(marker.getPosition(), to));
//Add listener to restart animation on end
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
randomlyMoveMarker(marker);
}
});
}
final ValueAnimator markerAnimator = ObjectAnimator.ofObject(
marker, "position", new LatLngEvaluator(), marker.getPosition(), to);
markerAnimator.setDuration((long) (10 * marker.getPosition().distanceTo(to)));
markerAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
private ValueAnimator animateMoveMarker(final MarkerView marker, LatLng to) {
marker.setRotation((float) getBearing(marker.getPosition(), to));
// Start
markerAnimator.start();
final ValueAnimator markerAnimator = ObjectAnimator.ofObject(
marker, "position", new LatLngEvaluator(), marker.getPosition(), to);
markerAnimator.setDuration((long) (10 * marker.getPosition().distanceTo(to)));
markerAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
return markerAnimator;
}
// Start
markerAnimator.start();
private MarkerView createCarMarker(LatLng start, @DrawableRes int carResource, MarkerViewManager.OnMarkerViewAddedListener listener) {
Icon icon = IconFactory.getInstance(AnimatedMarkerActivity.this)
.fromResource(carResource);
return markerAnimator;
}
//View Markers
return mapboxMap.addMarker(new MarkerViewOptions()
.position(start)
.icon(icon), listener);
private MarkerView createCarMarker(LatLng start, @DrawableRes int carResource,
MarkerViewManager.OnMarkerViewAddedListener listener) {
Icon icon = IconFactory.getInstance(AnimatedMarkerActivity.this)
.fromResource(carResource);
//GL Markers
//View Markers
return mapboxMap.addMarker(new MarkerViewOptions()
.position(start)
.icon(icon), listener);
//GL Markers
// return mapboxMap.addMarker(new MarkerOptions()
// .position(start)
// .icon(icon));
}
}
private LatLng getLatLngInBounds() {
LatLngBounds bounds = mapboxMap.getProjection().getVisibleRegion().latLngBounds;
Random generator = new Random();
double randomLat = bounds.getLatSouth() + generator.nextDouble()
* (bounds.getLatNorth() - bounds.getLatSouth());
double randomLon = bounds.getLonWest() + generator.nextDouble()
* (bounds.getLonEast() - bounds.getLonWest());
return new LatLng(randomLat, randomLon);
private LatLng getLatLngInBounds() {
LatLngBounds bounds = mapboxMap.getProjection().getVisibleRegion().latLngBounds;
Random generator = new Random();
double randomLat = bounds.getLatSouth() + generator.nextDouble()
* (bounds.getLatNorth() - bounds.getLatSouth());
double randomLon = bounds.getLonWest() + generator.nextDouble()
* (bounds.getLonEast() - bounds.getLonWest());
return new LatLng(randomLat, randomLon);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
/**
* Evaluator for LatLng pairs
*/
private static class LatLngEvaluator implements TypeEvaluator<LatLng> {
private LatLng latLng = new LatLng();
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
public LatLng evaluate(float fraction, LatLng startValue, LatLng endValue) {
latLng.setLatitude(startValue.getLatitude()
+ ((endValue.getLatitude() - startValue.getLatitude()) * fraction));
latLng.setLongitude(startValue.getLongitude()
+ ((endValue.getLongitude() - startValue.getLongitude()) * fraction));
return latLng;
}
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
/**
* Evaluator for LatLng pairs
*/
private static class LatLngEvaluator implements TypeEvaluator<LatLng> {
private LatLng latLng = new LatLng();
@Override
public LatLng evaluate(float fraction, LatLng startValue, LatLng endValue) {
latLng.setLatitude(startValue.getLatitude()
+ ((endValue.getLatitude() - startValue.getLatitude()) * fraction));
latLng.setLongitude(startValue.getLongitude()
+ ((endValue.getLongitude() - startValue.getLongitude()) * fraction));
return latLng;
}
}
private double getBearing(LatLng from, LatLng to) {
double degrees2radians = Math.PI / 180;
double radians2degrees = 180 / Math.PI;
double lon1 = degrees2radians * from.getLongitude();
double lon2 = degrees2radians * to.getLongitude();
double lat1 = degrees2radians * from.getLatitude();
double lat2 = degrees2radians * to.getLatitude();
double a = Math.sin(lon2 - lon1) * Math.cos(lat2);
double b = Math.cos(lat1) * Math.sin(lat2)
- Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);
return radians2degrees * Math.atan2(a, b);
}
private double getBearing(LatLng from, LatLng to) {
return TurfMeasurement.bearing(
Position.fromCoordinates(from.getLongitude(), from.getLatitude()),
Position.fromCoordinates(to.getLongitude(), to.getLatitude())
);
}
}

View File

@@ -8,11 +8,14 @@ import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
@@ -43,258 +46,259 @@ import java.util.Random;
public class BulkMarkerActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private MapboxMap mapboxMap;
private MapView mapView;
private boolean customMarkerView;
private List<LatLng> locations;
private MapboxMap mapboxMap;
private MapView mapView;
private boolean customMarkerView;
private List<LatLng> locations;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_marker_bulk);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_marker_bulk);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
BulkMarkerActivity.this.mapboxMap = mapboxMap;
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(
actionBar.getThemedContext(), R.array.bulk_marker_list, android.R.layout.simple_spinner_item);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(BulkMarkerActivity.this);
}
}
});
final View fab = findViewById(R.id.fab);
if (fab != null) {
fab.setOnClickListener(new FabClickListener());
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int amount = Integer.valueOf(getResources().getStringArray(R.array.bulk_marker_list)[position]);
if (locations == null) {
new LoadLocationTask(this, amount).execute();
} else {
showMarkers(amount);
}
}
private void onLatLngListLoaded(List<LatLng> latLngs, int amount) {
locations = latLngs;
showMarkers(amount);
}
private void showMarkers(int amount) {
mapboxMap.clear();
if (locations.size() < amount) {
amount = locations.size();
}
if (customMarkerView) {
showViewMarkers(amount);
} else {
showGlMarkers(amount);
}
}
private void showViewMarkers(int amount) {
DecimalFormat formatter = new DecimalFormat("#.#####");
Random random = new Random();
int randomIndex;
Drawable drawable = ContextCompat.getDrawable(BulkMarkerActivity.this, R.drawable.ic_droppin_24dp);
int redColor = ResourcesCompat.getColor(getResources(), android.R.color.holo_red_dark, getTheme());
drawable.setColorFilter(redColor, PorterDuff.Mode.SRC_IN);
Icon icon = IconFactory.getInstance(this).fromDrawable(drawable);
List<MarkerViewOptions> markerOptionsList = new ArrayList<>();
for (int i = 0; i < amount; i++) {
randomIndex = random.nextInt(locations.size());
LatLng latLng = locations.get(randomIndex);
MarkerViewOptions markerOptions = new MarkerViewOptions()
.position(latLng)
.icon(icon)
.title(String.valueOf(i))
.snippet(formatter.format(latLng.getLatitude()) + ", " + formatter.format(latLng.getLongitude()));
markerOptionsList.add(markerOptions);
}
mapboxMap.addMarkerViews(markerOptionsList);
}
private void showGlMarkers(int amount) {
List<MarkerOptions> markerOptionsList = new ArrayList<>();
DecimalFormat formatter = new DecimalFormat("#.#####");
Random random = new Random();
int randomIndex;
for (int i = 0; i < amount; i++) {
randomIndex = random.nextInt(locations.size());
LatLng latLng = locations.get(randomIndex);
markerOptionsList.add(new MarkerOptions()
.position(latLng)
.title(String.valueOf(i))
.snippet(formatter.format(latLng.getLatitude()) + ", " + formatter.format(latLng.getLongitude())));
}
mapboxMap.addMarkers(markerOptionsList);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// nothing selected, nothing to do!
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class FabClickListener implements View.OnClickListener {
@Override
public void onClick(final View view) {
if (mapboxMap != null) {
customMarkerView = true;
// remove fab
view.animate().alpha(0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
view.setVisibility(View.GONE);
}
}).start();
// reload markers
Spinner spinner = (Spinner) findViewById(R.id.spinner);
if (spinner != null) {
int amount = Integer.valueOf(
getResources().getStringArray(R.array.bulk_marker_list)[spinner.getSelectedItemPosition()]);
showMarkers(amount);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
BulkMarkerActivity.this.mapboxMap = mapboxMap;
if (actionBar != null) {
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(
actionBar.getThemedContext(), R.array.bulk_marker_list, android.R.layout.simple_spinner_item);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(BulkMarkerActivity.this);
}
mapView.addOnMapChangedListener(new MapView.OnMapChangedListener() {
@Override
public void onMapChanged(@MapView.MapChange int change) {
if (change == MapView.REGION_IS_CHANGING || change == MapView.REGION_DID_CHANGE) {
if (!mapboxMap.getMarkerViewManager().getMarkerViewAdapters().isEmpty()) {
TextView viewCountView = (TextView) findViewById(R.id.countView);
viewCountView.setText("ViewCache size " + (mapView.getChildCount() - 5));
}
}
}
});
final View fab = findViewById(R.id.fab);
if (fab != null) {
fab.setOnClickListener(new FabClickListener());
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int amount = Integer.valueOf(getResources().getStringArray(R.array.bulk_marker_list)[position]);
if (locations == null) {
new LoadLocationTask(this, amount).execute();
} else {
showMarkers(amount);
}
}
private void onLatLngListLoaded(List<LatLng> latLngs, int amount) {
locations = latLngs;
showMarkers(amount);
}
private void showMarkers(int amount) {
mapboxMap.clear();
if (locations.size() < amount) {
amount = locations.size();
}
if (customMarkerView) {
showViewMarkers(amount);
} else {
showGlMarkers(amount);
}
}
private void showViewMarkers(int amount) {
DecimalFormat formatter = new DecimalFormat("#.#####");
Random random = new Random();
int randomIndex;
Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_droppin_24dp, getTheme());
int redColor = ResourcesCompat.getColor(getResources(), android.R.color.holo_red_dark, getTheme());
drawable.setColorFilter(redColor, PorterDuff.Mode.SRC_IN);
Icon icon = IconFactory.getInstance(this).fromDrawable(drawable);
List<MarkerViewOptions> markerOptionsList = new ArrayList<>();
for (int i = 0; i < amount; i++) {
randomIndex = random.nextInt(locations.size());
LatLng latLng = locations.get(randomIndex);
MarkerViewOptions markerOptions = new MarkerViewOptions()
.position(latLng)
.icon(icon)
.title(String.valueOf(i))
.snippet(formatter.format(latLng.getLatitude()) + ", " + formatter.format(latLng.getLongitude()));
markerOptionsList.add(markerOptions);
}
mapboxMap.addMarkerViews(markerOptionsList);
}
private void showGlMarkers(int amount) {
List<MarkerOptions> markerOptionsList = new ArrayList<>();
DecimalFormat formatter = new DecimalFormat("#.#####");
Random random = new Random();
int randomIndex;
for (int i = 0; i < amount; i++) {
randomIndex = random.nextInt(locations.size());
LatLng latLng = locations.get(randomIndex);
markerOptionsList.add(new MarkerOptions()
.position(latLng)
.title(String.valueOf(i))
.snippet(formatter.format(latLng.getLatitude()) + ", " + formatter.format(latLng.getLongitude())));
}
mapboxMap.addMarkers(markerOptionsList);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// nothing selected, nothing to do!
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class FabClickListener implements View.OnClickListener {
@Override
public void onClick(final View v) {
if (mapboxMap != null) {
customMarkerView = true;
// remove fab
v.animate().alpha(0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
v.setVisibility(View.GONE);
}
}).start();
// reload markers
Spinner spinner = (Spinner) findViewById(R.id.spinner);
if (spinner != null) {
int amount = Integer.valueOf(
getResources().getStringArray(R.array.bulk_marker_list)[spinner.getSelectedItemPosition()]);
showMarkers(amount);
}
mapView.addOnMapChangedListener(new MapView.OnMapChangedListener() {
@Override
public void onMapChanged(@MapView.MapChange int change) {
if (change == MapView.REGION_IS_CHANGING || change == MapView.REGION_DID_CHANGE) {
if (!mapboxMap.getMarkerViewManager().getMarkerViewAdapters().isEmpty()) {
TextView viewCountView = (TextView) findViewById(R.id.countView);
viewCountView.setText("ViewCache size " + (mapView.getChildCount() - 5));
}
}
}
});
mapboxMap.getMarkerViewManager().setOnMarkerViewClickListener(
new MapboxMap.OnMarkerViewClickListener() {
@Override
public boolean onMarkerClick(
@NonNull Marker marker, @NonNull View view, @NonNull MapboxMap.MarkerViewAdapter adapter) {
Toast.makeText(
BulkMarkerActivity.this,
"Hello " + marker.getId(),
Toast.LENGTH_SHORT).show();
return false;
}
});
mapboxMap.getMarkerViewManager().setOnMarkerViewClickListener(
new MapboxMap.OnMarkerViewClickListener() {
@Override
public boolean onMarkerClick(
@NonNull Marker marker, @NonNull View view, @NonNull MapboxMap.MarkerViewAdapter adapter) {
Toast.makeText(
BulkMarkerActivity.this,
"Hello " + marker.getId(),
Toast.LENGTH_SHORT).show();
return false;
}
}
});
}
}
}
private static class LoadLocationTask extends AsyncTask<Void, Integer, List<LatLng>> {
private BulkMarkerActivity activity;
private ProgressDialog progressDialog;
private int amount;
private LoadLocationTask(BulkMarkerActivity activity, int amount) {
this.amount = amount;
this.activity = activity;
progressDialog = ProgressDialog.show(activity, "Loading", "Fetching markers", false);
}
private static class LoadLocationTask extends AsyncTask<Void, Integer, List<LatLng>> {
private BulkMarkerActivity activity;
private ProgressDialog progressDialog;
private int amount;
public LoadLocationTask(BulkMarkerActivity activity, int amount) {
this.amount = amount;
this.activity = activity;
progressDialog = ProgressDialog.show(activity, "Loading", "Fetching markers", false);
}
@Override
protected List<LatLng> doInBackground(Void... params) {
try {
String json = GeoParseUtil.loadStringFromAssets(activity.getApplicationContext(), "points.geojson");
return GeoParseUtil.parseGeoJSONCoordinates(json);
} catch (IOException | JSONException exception) {
Timber.e("Could not add markers,", exception);
return null;
}
}
@Override
protected void onPostExecute(List<LatLng> locations) {
super.onPostExecute(locations);
activity.onLatLngListLoaded(locations, amount);
progressDialog.hide();
}
@Override
protected List<LatLng> doInBackground(Void... params) {
try {
String json = GeoParseUtil.loadStringFromAssets(activity.getApplicationContext(), "points.geojson");
return GeoParseUtil.parseGeoJsonCoordinates(json);
} catch (IOException | JSONException exception) {
Timber.e("Could not add markers,", exception);
return null;
}
}
@Override
protected void onPostExecute(List<LatLng> locations) {
super.onPostExecute(locations);
activity.onLatLngListLoaded(locations, amount);
progressDialog.hide();
}
}
}

View File

@@ -21,123 +21,123 @@ import com.mapbox.mapboxsdk.testapp.R;
public class DynamicMarkerChangeActivity extends AppCompatActivity {
private static final LatLng LAT_LNG_CHELSEA = new LatLng(51.481670, -0.190849);
private static final LatLng LAT_LNG_ARSENAL = new LatLng(51.555062, -0.108417);
private static final LatLng LAT_LNG_CHELSEA = new LatLng(51.481670, -0.190849);
private static final LatLng LAT_LNG_ARSENAL = new LatLng(51.555062, -0.108417);
private MapView mapView;
private MapboxMap mapboxMap;
private IconFactory iconFactory;
private Marker marker;
private MapView mapView;
private MapboxMap mapboxMap;
private IconFactory iconFactory;
private Marker marker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_marker);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_marker);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
iconFactory = IconFactory.getInstance(this);
mapView = (MapView) findViewById(R.id.mapView);
mapView.setTag(false);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
DynamicMarkerChangeActivity.this.mapboxMap = mapboxMap;
// Create marker
MarkerOptions markerOptions = new MarkerOptions()
.position(LAT_LNG_CHELSEA)
.icon(iconFactory.fromResource(R.drawable.ic_chelsea))
.title(getString(R.string.dynamic_marker_chelsea_title))
.snippet(getString(R.string.dynamic_marker_chelsea_snippet));
marker = mapboxMap.addMarker(markerOptions);
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setColorFilter(ContextCompat.getColor(this, R.color.primary));
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mapboxMap != null) {
updateMarker();
}
}
});
}
iconFactory = IconFactory.getInstance(this);
private void updateMarker() {
// update model
boolean first = (boolean) mapView.getTag();
mapView.setTag(!first);
mapView = (MapView) findViewById(R.id.mapView);
mapView.setTag(false);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
DynamicMarkerChangeActivity.this.mapboxMap = mapboxMap;
// Create marker
MarkerOptions markerOptions = new MarkerOptions()
.position(LAT_LNG_CHELSEA)
.icon(iconFactory.fromResource(R.drawable.ic_chelsea))
.title(getString(R.string.dynamic_marker_chelsea_title))
.snippet(getString(R.string.dynamic_marker_chelsea_snippet));
marker = mapboxMap.addMarker(markerOptions);
}
});
// update marker
marker.setPosition(first ? LAT_LNG_CHELSEA : LAT_LNG_ARSENAL);
marker.setIcon(iconFactory.fromResource(first ? R.drawable.ic_chelsea : R.drawable.ic_arsenal));
marker.setTitle(first
? getString(R.string.dynamic_marker_chelsea_title) : getString(R.string.dynamic_marker_arsenal_title));
marker.setSnippet(first
? getString(R.string.dynamic_marker_chelsea_snippet) : getString(R.string.dynamic_marker_arsenal_snippet));
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setColorFilter(ContextCompat.getColor(this, R.color.primary));
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mapboxMap != null) {
updateMarker();
}
}
});
}
private void updateMarker() {
// update model
boolean first = (boolean) mapView.getTag();
mapView.setTag(!first);
// update marker
marker.setPosition(first ? LAT_LNG_CHELSEA : LAT_LNG_ARSENAL);
marker.setIcon(iconFactory.fromResource(first ? R.drawable.ic_chelsea : R.drawable.ic_arsenal));
marker.setTitle(first
? getString(R.string.dynamic_marker_chelsea_title) : getString(R.string.dynamic_marker_arsenal_title));
marker.setSnippet(first
? getString(R.string.dynamic_marker_chelsea_snippet) : getString(R.string.dynamic_marker_arsenal_snippet));
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -41,456 +41,458 @@ import java.util.Random;
public class MarkerViewActivity extends AppCompatActivity {
private static final LatLng[] LAT_LNGS = new LatLng[]{
new LatLng(38.897424, -77.036508),
new LatLng(38.909698, -77.029642),
new LatLng(38.907227, -77.036530),
new LatLng(38.905607, -77.031916),
new LatLng(38.889441, -77.050134),
new LatLng(38.888000, -77.050000) //Slight overlap to show re-ordering on selection
private static final LatLng[] LAT_LNGS = new LatLng[] {
new LatLng(38.897424, -77.036508),
new LatLng(38.909698, -77.029642),
new LatLng(38.907227, -77.036530),
new LatLng(38.905607, -77.031916),
new LatLng(38.889441, -77.050134),
new LatLng(38.888000, -77.050000) //Slight overlap to show re-ordering on selection
};
private MapboxMap mapboxMap;
private MapView mapView;
// MarkerView location updates
private MarkerView movingMarkerOne;
private MarkerView movingMarkerTwo;
private Random randomAnimator = new Random();
private Handler locationUpdateHandler = new Handler();
private Runnable moveMarkerRunnable = new MoveMarkerRunnable();
// MarkerView rotate updates
private MarkerView rotateMarker;
private Handler rotateUpdateHandler = new Handler();
private Runnable rotateMarkerRunnable = new RotateMarkerRunnable();
private int rotation = 360;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_marker_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
final TextView viewCountView = (TextView) findViewById(R.id.countView);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
MarkerViewActivity.this.mapboxMap = mapboxMap;
final MarkerViewManager markerViewManager = mapboxMap.getMarkerViewManager();
Icon usFlag = IconFactory.getInstance(MarkerViewActivity.this)
.fromResource(R.drawable.ic_us);
// add default ViewMarker markers
for (int i = 0; i < LAT_LNGS.length; i++) {
MarkerViewActivity.this.mapboxMap.addMarker(new MarkerViewOptions()
.position(LAT_LNGS[i])
.title(String.valueOf(i))
.alpha(0.5f)
.icon(usFlag)
);
}
// add custom ViewMarker
CountryMarkerViewOptions options = new CountryMarkerViewOptions();
options.flagRes(R.drawable.icon_burned);
options.abbrevName("Mapbox");
options.title("Hello");
options.position(new LatLng(38.899774, -77.023237));
options.flat(true);
mapboxMap.addMarker(options);
MarkerViewActivity.this.mapboxMap.addMarker(new MarkerOptions()
.title("United States")
.position(new LatLng(38.902580, -77.050102))
);
rotateMarker = MarkerViewActivity.this.mapboxMap.addMarker(new TextMarkerViewOptions()
.text("A")
.rotation(rotation = 270)
.position(new LatLng(38.889876, -77.008849))
);
loopMarkerRotate();
MarkerViewActivity.this.mapboxMap.addMarker(new TextMarkerViewOptions()
.text("B")
.position(new LatLng(38.907327, -77.041293))
);
MarkerViewActivity.this.mapboxMap.addMarker(new TextMarkerViewOptions()
.text("C")
.position(new LatLng(38.897642, -77.041980))
);
// if you want to customise a ViewMarker you need to extend ViewMarker and provide an adapter implementation
// set adapters for child classes of ViewMarker
markerViewManager.addMarkerViewAdapter(new CountryAdapter(MarkerViewActivity.this, mapboxMap));
markerViewManager.addMarkerViewAdapter(new TextAdapter(MarkerViewActivity.this, mapboxMap));
final ViewGroup markerViewContainer = markerViewManager.getMarkerViewContainer();
// add a change listener to validate the size of amount of child views
mapView.addOnMapChangedListener(new MapView.OnMapChangedListener() {
@Override
public void onMapChanged(@MapView.MapChange int change) {
if (change == MapView.REGION_IS_CHANGING || change == MapView.REGION_DID_CHANGE) {
if (!markerViewManager.getMarkerViewAdapters().isEmpty() && viewCountView != null) {
viewCountView.setText("ViewCache size " + markerViewContainer.getChildCount());
}
}
}
});
// add a OnMarkerView click listener
MarkerViewActivity.this.mapboxMap.getMarkerViewManager().setOnMarkerViewClickListener(
new MapboxMap.OnMarkerViewClickListener() {
@Override
public boolean onMarkerClick(@NonNull Marker marker, @NonNull View view,
@NonNull MapboxMap.MarkerViewAdapter adapter) {
Toast.makeText(MarkerViewActivity.this, "Hello " + marker.getId(), Toast.LENGTH_SHORT).show();
return false;
}
});
movingMarkerOne = MarkerViewActivity.this.mapboxMap.addMarker(new MarkerViewOptions()
.position(CarLocation.CAR_0_LNGS[0])
.icon(IconFactory.getInstance(mapView.getContext())
.fromResource(R.drawable.ic_chelsea))
);
movingMarkerTwo = mapboxMap.addMarker(new MarkerViewOptions()
.position(CarLocation.CAR_1_LNGS[0])
.icon(IconFactory.getInstance(mapView.getContext())
.fromResource(R.drawable.ic_arsenal))
);
// allow more open infowindows at the same time
mapboxMap.setAllowConcurrentMultipleOpenInfoWindows(true);
// add offscreen markers
Marker markerRightOffScreen = mapboxMap.addMarker(new MarkerOptions()
.setPosition(new LatLng(38.892846, -76.909399))
.title("InfoWindow")
.snippet("Offscreen, to the right of the Map."));
Marker markerRightBottomOffScreen = mapboxMap.addMarker(new MarkerOptions()
.setPosition(new LatLng(38.791645, -77.039006))
.title("InfoWindow")
.snippet("Offscreen, to the bottom of the Map"));
// open infowindow offscreen markers
mapboxMap.selectMarker(markerRightOffScreen);
mapboxMap.selectMarker(markerRightBottomOffScreen);
}
});
}
private void loopMarkerRotate() {
rotateUpdateHandler.postDelayed(rotateMarkerRunnable, 800);
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
loopMarkerMove();
}
private void loopMarkerMove() {
locationUpdateHandler.postDelayed(moveMarkerRunnable, randomAnimator.nextInt(3000) + 1000);
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
locationUpdateHandler.removeCallbacks(moveMarkerRunnable);
rotateUpdateHandler.removeCallbacks(rotateMarkerRunnable);
}
/**
* Updates the position of a Marker
*/
private class MoveMarkerRunnable implements Runnable {
@Override
public void run() {
int randomInteger = randomAnimator.nextInt(9);
if (randomAnimator.nextInt() % 2 == 0) {
movingMarkerOne.setPosition(CarLocation.CAR_0_LNGS[randomInteger]);
} else {
movingMarkerTwo.setPosition(CarLocation.CAR_1_LNGS[randomInteger]);
}
loopMarkerMove();
}
}
/**
* Updates the rotation of a Marker
*/
private class RotateMarkerRunnable implements Runnable {
private static final int ROTATION_INCREASE_VALUE = 9;
@Override
public void run() {
rotation -= ROTATION_INCREASE_VALUE;
if (rotation >= 0) {
rotation += 360;
}
rotateMarker.setRotation(rotation);
loopMarkerRotate();
}
}
/**
* Adapts a MarkerView to display an abbreviated name in a TextView and a flag in an ImageView.
*/
private static class CountryAdapter extends MapboxMap.MarkerViewAdapter<CountryMarkerView> {
private LayoutInflater inflater;
private MapboxMap mapboxMap;
CountryAdapter(@NonNull Context context, @NonNull MapboxMap mapboxMap) {
super(context);
this.inflater = LayoutInflater.from(context);
this.mapboxMap = mapboxMap;
}
@Nullable
@Override
public View getView(@NonNull CountryMarkerView marker, @Nullable View convertView, @NonNull ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.view_custom_marker, parent, false);
viewHolder.flag = (ImageView) convertView.findViewById(R.id.imageView);
viewHolder.abbrev = (TextView) convertView.findViewById(R.id.textView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.flag.setImageResource(marker.getFlagRes());
viewHolder.abbrev.setText(marker.getAbbrevName());
return convertView;
}
@Override
public boolean onSelect(
@NonNull final CountryMarkerView marker, @NonNull final View convertView, boolean reselectionForViewReuse) {
convertView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
ObjectAnimator rotateAnimator = ObjectAnimator.ofFloat(convertView, View.ROTATION, 0, 360);
rotateAnimator.setDuration(reselectionForViewReuse ? 0 : 350);
rotateAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
convertView.setLayerType(View.LAYER_TYPE_NONE, null);
mapboxMap.selectMarker(marker);
}
});
rotateAnimator.start();
// false indicates that we are calling selectMarker after our animation ourselves
// true will let the system call it for you, which will result in showing an InfoWindow instantly
return false;
}
@Override
public void onDeselect(@NonNull CountryMarkerView marker, @NonNull final View convertView) {
convertView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
ObjectAnimator rotateAnimator = ObjectAnimator.ofFloat(convertView, View.ROTATION, 360, 0);
rotateAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
convertView.setLayerType(View.LAYER_TYPE_NONE, null);
}
});
rotateAnimator.start();
}
private static class ViewHolder {
ImageView flag;
TextView abbrev;
}
}
/**
* Adapts a MarkerView to display text in a TextView.
*/
public static class TextAdapter extends MapboxMap.MarkerViewAdapter<TextMarkerView> {
private LayoutInflater inflater;
private MapboxMap mapboxMap;
public TextAdapter(@NonNull Context context, @NonNull MapboxMap mapboxMap) {
super(context);
this.inflater = LayoutInflater.from(context);
this.mapboxMap = mapboxMap;
}
@Nullable
@Override
public View getView(@NonNull TextMarkerView marker, @Nullable View convertView, @NonNull ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.view_text_marker, parent, false);
viewHolder.textView = (TextView) convertView.findViewById(R.id.textView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.textView.setText(marker.getText());
return convertView;
}
@Override
public boolean onSelect(
@NonNull final TextMarkerView marker, @NonNull final View convertView, boolean reselectionForViewReuse) {
animateGrow(marker, convertView, 0);
// false indicates that we are calling selectMarker after our animation ourselves
// true will let the system call it for you, which will result in showing an InfoWindow instantly
return false;
}
@Override
public void onDeselect(@NonNull TextMarkerView marker, @NonNull final View convertView) {
animateShrink(convertView, 350);
}
@Override
public boolean prepareViewForReuse(@NonNull MarkerView marker, @NonNull View convertView) {
// this method is called before a view will be reused, we need to restore view state
// as we have scaled the view in onSelect. If not correctly applied other MarkerView will
// become large since these have been recycled
// cancel ongoing animation
convertView.animate().cancel();
if (marker.isSelected()) {
// shrink view to be able to be reused
animateShrink(convertView, 0);
}
// true if you want reuse to occur automatically, false if you want to manage this yourself
return true;
}
private void animateGrow(@NonNull final MarkerView marker, @NonNull final View convertView, int duration) {
convertView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
Animator animator = AnimatorInflater.loadAnimator(convertView.getContext(), R.animator.scale_up);
animator.setDuration(duration);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
convertView.setLayerType(View.LAYER_TYPE_NONE, null);
mapboxMap.selectMarker(marker);
}
});
animator.setTarget(convertView);
animator.start();
}
private void animateShrink(@NonNull final View convertView, int duration) {
convertView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
Animator animator = AnimatorInflater.loadAnimator(convertView.getContext(), R.animator.scale_down);
animator.setDuration(duration);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
convertView.setLayerType(View.LAYER_TYPE_NONE, null);
}
});
animator.setTarget(convertView);
animator.start();
}
private static class ViewHolder {
TextView textView;
}
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private static class CarLocation {
static LatLng[] CAR_0_LNGS = new LatLng[] {
new LatLng(38.92334425495122, -77.0533673443786),
new LatLng(38.9234737236897, -77.05389484528261),
new LatLng(38.9257094658146, -76.98819752280579),
new LatLng(38.8324328369647, -77.00690648325929),
new LatLng(38.87540698725855, -77.0093148713099),
new LatLng(38.96499498141065, -77.07707916040054),
new LatLng(38.90794910679896, -76.99695304153806),
new LatLng(38.86234025281626, -76.9950528034839),
new LatLng(38.862930274733635, -76.99647808241964)
};
private MapboxMap mapboxMap;
private MapView mapView;
// MarkerView location updates
private MarkerView movingMarkerOne;
private MarkerView movingMarkerTwo;
private Random randomAnimator = new Random();
private Handler locationUpdateHandler = new Handler();
private Runnable moveMarkerRunnable = new MoveMarkerRunnable();
// MarkerView rotate updates
private MarkerView rotateMarker;
private Handler rotateUpdateHandler = new Handler();
private Runnable rotateMarkerRunnable = new RotateMarkerRunnable();
private int rotation = 360;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_marker_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
final TextView viewCountView = (TextView) findViewById(R.id.countView);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
MarkerViewActivity.this.mapboxMap = mapboxMap;
final MarkerViewManager markerViewManager = mapboxMap.getMarkerViewManager();
Icon usFlag = IconFactory.getInstance(MarkerViewActivity.this)
.fromResource(R.drawable.ic_us);
// add default ViewMarker markers
for (int i = 0; i < LAT_LNGS.length; i++) {
MarkerViewActivity.this.mapboxMap.addMarker(new MarkerViewOptions()
.position(LAT_LNGS[i])
.title(String.valueOf(i))
.alpha(0.5f)
.icon(usFlag)
);
}
// add custom ViewMarker
CountryMarkerViewOptions options = new CountryMarkerViewOptions();
options.flagRes(R.drawable.icon_burned);
options.abbrevName("Mapbox");
options.title("Hello");
options.position(new LatLng(38.899774, -77.023237));
options.flat(true);
mapboxMap.addMarker(options);
MarkerViewActivity.this.mapboxMap.addMarker(new MarkerOptions()
.title("United States")
.position(new LatLng(38.902580, -77.050102))
);
rotateMarker = MarkerViewActivity.this.mapboxMap.addMarker(new TextMarkerViewOptions()
.text("A")
.rotation(rotation = 270)
.position(new LatLng(38.889876, -77.008849))
);
loopMarkerRotate();
MarkerViewActivity.this.mapboxMap.addMarker(new TextMarkerViewOptions()
.text("B")
.position(new LatLng(38.907327, -77.041293))
);
MarkerViewActivity.this.mapboxMap.addMarker(new TextMarkerViewOptions()
.text("C")
.position(new LatLng(38.897642, -77.041980))
);
// if you want to customise a ViewMarker you need to extend ViewMarker and provide an adapter implementation
// set adapters for child classes of ViewMarker
markerViewManager.addMarkerViewAdapter(new CountryAdapter(MarkerViewActivity.this, mapboxMap));
markerViewManager.addMarkerViewAdapter(new TextAdapter(MarkerViewActivity.this, mapboxMap));
final ViewGroup markerViewContainer = markerViewManager.getMarkerViewContainer();
// add a change listener to validate the size of amount of child views
mapView.addOnMapChangedListener(new MapView.OnMapChangedListener() {
@Override
public void onMapChanged(@MapView.MapChange int change) {
if (change == MapView.REGION_IS_CHANGING || change == MapView.REGION_DID_CHANGE) {
if (!markerViewManager.getMarkerViewAdapters().isEmpty() && viewCountView != null) {
viewCountView.setText("ViewCache size " + markerViewContainer.getChildCount());
}
}
}
});
// add a OnMarkerView click listener
MarkerViewActivity.this.mapboxMap.getMarkerViewManager().setOnMarkerViewClickListener(new MapboxMap.OnMarkerViewClickListener() {
@Override
public boolean onMarkerClick(@NonNull Marker marker, @NonNull View view, @NonNull MapboxMap.MarkerViewAdapter adapter) {
Toast.makeText(MarkerViewActivity.this, "Hello " + marker.getId(), Toast.LENGTH_SHORT).show();
return false;
}
});
movingMarkerOne = MarkerViewActivity.this.mapboxMap.addMarker(new MarkerViewOptions()
.position(CarLocation.CAR_0_LNGS[0])
.icon(IconFactory.getInstance(mapView.getContext())
.fromResource(R.drawable.ic_chelsea))
);
movingMarkerTwo = mapboxMap.addMarker(new MarkerViewOptions()
.position(CarLocation.CAR_1_LNGS[0])
.icon(IconFactory.getInstance(mapView.getContext())
.fromResource(R.drawable.ic_arsenal))
);
// allow more open infowindows at the same time
mapboxMap.setAllowConcurrentMultipleOpenInfoWindows(true);
// add offscreen markers
Marker markerRightOffScreen = mapboxMap.addMarker(new MarkerOptions()
.setPosition(new LatLng(38.892846, -76.909399))
.title("InfoWindow")
.snippet("Offscreen, to the right of the Map."));
Marker markerRightBottomOffScreen = mapboxMap.addMarker(new MarkerOptions()
.setPosition(new LatLng(38.791645, -77.039006))
.title("InfoWindow")
.snippet("Offscreen, to the bottom of the Map"));
// open infowindow offscreen markers
mapboxMap.selectMarker(markerRightOffScreen);
mapboxMap.selectMarker(markerRightBottomOffScreen);
}
});
}
private void loopMarkerRotate() {
rotateUpdateHandler.postDelayed(rotateMarkerRunnable, 800);
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
loopMarkerMove();
}
private void loopMarkerMove() {
locationUpdateHandler.postDelayed(moveMarkerRunnable, randomAnimator.nextInt(3000) + 1000);
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
locationUpdateHandler.removeCallbacks(moveMarkerRunnable);
rotateUpdateHandler.removeCallbacks(rotateMarkerRunnable);
}
/**
* Updates the position of a Marker
*/
private class MoveMarkerRunnable implements Runnable {
@Override
public void run() {
int i = randomAnimator.nextInt(9);
if (randomAnimator.nextInt() % 2 == 0) {
movingMarkerOne.setPosition(CarLocation.CAR_0_LNGS[i]);
} else {
movingMarkerTwo.setPosition(CarLocation.CAR_1_LNGS[i]);
}
loopMarkerMove();
}
}
/**
* Updates the rotation of a Marker
*/
private class RotateMarkerRunnable implements Runnable {
private final static int ROTATION_INCREASE_VALUE = 9;
@Override
public void run() {
rotation -= ROTATION_INCREASE_VALUE;
if (rotation >= 0) {
rotation += 360;
}
rotateMarker.setRotation(rotation);
loopMarkerRotate();
}
}
/**
* Adapts a MarkerView to display an abbreviated name in a TextView and a flag in an ImageView.
*/
private static class CountryAdapter extends MapboxMap.MarkerViewAdapter<CountryMarkerView> {
private LayoutInflater inflater;
private MapboxMap mapboxMap;
CountryAdapter(@NonNull Context context, @NonNull MapboxMap mapboxMap) {
super(context);
this.inflater = LayoutInflater.from(context);
this.mapboxMap = mapboxMap;
}
@Nullable
@Override
public View getView(@NonNull CountryMarkerView marker, @Nullable View convertView, @NonNull ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.view_custom_marker, parent, false);
viewHolder.flag = (ImageView) convertView.findViewById(R.id.imageView);
viewHolder.abbrev = (TextView) convertView.findViewById(R.id.textView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.flag.setImageResource(marker.getFlagRes());
viewHolder.abbrev.setText(marker.getAbbrevName());
return convertView;
}
@Override
public boolean onSelect(
@NonNull final CountryMarkerView marker, @NonNull final View convertView, boolean reselectionForViewReuse) {
convertView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
ObjectAnimator rotateAnimator = ObjectAnimator.ofFloat(convertView, View.ROTATION, 0, 360);
rotateAnimator.setDuration(reselectionForViewReuse ? 0 : 350);
rotateAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
convertView.setLayerType(View.LAYER_TYPE_NONE, null);
mapboxMap.selectMarker(marker);
}
});
rotateAnimator.start();
// false indicates that we are calling selectMarker after our animation ourselves
// true will let the system call it for you, which will result in showing an InfoWindow instantly
return false;
}
@Override
public void onDeselect(@NonNull CountryMarkerView marker, @NonNull final View convertView) {
convertView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
ObjectAnimator rotateAnimator = ObjectAnimator.ofFloat(convertView, View.ROTATION, 360, 0);
rotateAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
convertView.setLayerType(View.LAYER_TYPE_NONE, null);
}
});
rotateAnimator.start();
}
private static class ViewHolder {
ImageView flag;
TextView abbrev;
}
}
/**
* Adapts a MarkerView to display text in a TextView.
*/
public static class TextAdapter extends MapboxMap.MarkerViewAdapter<TextMarkerView> {
private LayoutInflater inflater;
private MapboxMap mapboxMap;
public TextAdapter(@NonNull Context context, @NonNull MapboxMap mapboxMap) {
super(context);
this.inflater = LayoutInflater.from(context);
this.mapboxMap = mapboxMap;
}
@Nullable
@Override
public View getView(@NonNull TextMarkerView marker, @Nullable View convertView, @NonNull ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.view_text_marker, parent, false);
viewHolder.textView = (TextView) convertView.findViewById(R.id.textView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.textView.setText(marker.getText());
return convertView;
}
@Override
public boolean onSelect(
@NonNull final TextMarkerView marker, @NonNull final View convertView, boolean reselectionForViewReuse) {
animateGrow(marker, convertView, 0);
// false indicates that we are calling selectMarker after our animation ourselves
// true will let the system call it for you, which will result in showing an InfoWindow instantly
return false;
}
@Override
public void onDeselect(@NonNull TextMarkerView marker, @NonNull final View convertView) {
animateShrink(convertView, 350);
}
@Override
public boolean prepareViewForReuse(@NonNull MarkerView marker, @NonNull View convertView) {
// this method is called before a view will be reused, we need to restore view state
// as we have scaled the view in onSelect. If not correctly applied other MarkerView will
// become large since these have been recycled
// cancel ongoing animation
convertView.animate().cancel();
if (marker.isSelected()) {
// shrink view to be able to be reused
animateShrink(convertView, 0);
}
// true if you want reuse to occur automatically, false if you want to manage this yourself
return true;
}
private void animateGrow(@NonNull final MarkerView marker, @NonNull final View convertView, int duration) {
convertView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
Animator animator = AnimatorInflater.loadAnimator(convertView.getContext(), R.animator.scale_up);
animator.setDuration(duration);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
convertView.setLayerType(View.LAYER_TYPE_NONE, null);
mapboxMap.selectMarker(marker);
}
});
animator.setTarget(convertView);
animator.start();
}
private void animateShrink(@NonNull final View convertView, int duration) {
convertView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
Animator animator = AnimatorInflater.loadAnimator(convertView.getContext(), R.animator.scale_down);
animator.setDuration(duration);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
convertView.setLayerType(View.LAYER_TYPE_NONE, null);
}
});
animator.setTarget(convertView);
animator.start();
}
private static class ViewHolder {
TextView textView;
}
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private static class CarLocation {
static LatLng[] CAR_0_LNGS = new LatLng[]{
new LatLng(38.92334425495122, -77.0533673443786),
new LatLng(38.9234737236897, -77.05389484528261),
new LatLng(38.9257094658146, -76.98819752280579),
new LatLng(38.8324328369647, -77.00690648325929),
new LatLng(38.87540698725855, -77.0093148713099),
new LatLng(38.96499498141065, -77.07707916040054),
new LatLng(38.90794910679896, -76.99695304153806),
new LatLng(38.86234025281626, -76.9950528034839),
new LatLng(38.862930274733635, -76.99647808241964)
};
static LatLng[] CAR_1_LNGS = new LatLng[]{
new LatLng(38.94237975070426, -76.98324549005675),
new LatLng(38.941520236084486, -76.98234257804742),
new LatLng(38.85972219720714, -76.98955808483929),
new LatLng(38.944289166113776, -76.98584257252891),
new LatLng(38.94375860578053, -76.98470344318412),
new LatLng(38.943167431929645, -76.98373163938666),
new LatLng(38.882834728904605, -77.02862535635137),
new LatLng(38.882869724926245, -77.02992539231113),
new LatLng(38.9371988177896, -76.97786740676564)
};
}
static LatLng[] CAR_1_LNGS = new LatLng[] {
new LatLng(38.94237975070426, -76.98324549005675),
new LatLng(38.941520236084486, -76.98234257804742),
new LatLng(38.85972219720714, -76.98955808483929),
new LatLng(38.944289166113776, -76.98584257252891),
new LatLng(38.94375860578053, -76.98470344318412),
new LatLng(38.943167431929645, -76.98373163938666),
new LatLng(38.882834728904605, -77.02862535635137),
new LatLng(38.882869724926245, -77.02992539231113),
new LatLng(38.9371988177896, -76.97786740676564)
};
}
}

View File

@@ -25,155 +25,155 @@ import java.util.Locale;
public class MarkerViewScaleActivity extends AppCompatActivity implements OnMapReadyCallback {
private MapboxMap mapboxMap;
private MapView mapView;
private MapboxMap mapboxMap;
private MapView mapView;
private MarkerView markerView;
private MarkerViewManager markerViewManager;
private MarkerView markerView;
private MarkerViewManager markerViewManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_marker_view_scale);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_marker_view_scale);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
markerViewManager = map.getMarkerViewManager();
final SeekBar xBar = (SeekBar) findViewById(R.id.seekbar_factor);
final TextView textView = (TextView) findViewById(R.id.textview_factor);
// We need to listen to a render event to be sure
// the View of the Marker has been added to the map
mapView.addOnMapChangedListener(new MapView.OnMapChangedListener() {
@Override
public void onMapChanged(@MapView.MapChange int change) {
if (isMarkerRendered()) {
Toast.makeText(MarkerViewScaleActivity.this, "MarkerView is ready", Toast.LENGTH_SHORT).show();
View view = markerViewManager.getView(markerView);
xBar.setOnSeekBarChangeListener(new FactorChangeListener(view, textView));
xBar.setClickable(true);
mapView.removeOnMapChangedListener(this);
}
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
private boolean isMarkerRendered() {
return markerView != null && markerViewManager.getView(markerView) != null;
}
});
Icon icon = IconFactory.getInstance(MarkerViewScaleActivity.this)
.fromResource(R.drawable.ic_circle);
markerView = mapboxMap.addMarker(new MarkerViewOptions()
.position(new LatLng(38.907192, -77.036871))
.icon(icon)
.flat(true));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onStart() {
super.onResume();
mapView.onStart();
}
@Override
public void onStop() {
super.onStop();
mapView.onStop();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
private static class FactorChangeListener implements SeekBar.OnSeekBarChangeListener {
private TextView textView;
private View view;
FactorChangeListener(View view, TextView textView) {
this.view = view;
this.textView = textView;
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
markerViewManager = map.getMarkerViewManager();
final SeekBar xBar = (SeekBar) findViewById(R.id.seekbar_factor);
final TextView textView = (TextView) findViewById(R.id.textview_factor);
// We need to listen to a render event to be sure
// the View of the Marker has been added to the map
mapView.addOnMapChangedListener(new MapView.OnMapChangedListener() {
@Override
public void onMapChanged(@MapView.MapChange int change) {
if (isMarkerRendered()) {
Toast.makeText(MarkerViewScaleActivity.this, "MarkerView is ready", Toast.LENGTH_SHORT).show();
View view = markerViewManager.getView(markerView);
xBar.setOnSeekBarChangeListener(new FactorChangeListener(view, textView));
xBar.setClickable(true);
mapView.removeOnMapChangedListener(this);
}
}
private boolean isMarkerRendered() {
return markerView != null && markerViewManager.getView(markerView) != null;
}
});
Icon icon = IconFactory.getInstance(MarkerViewScaleActivity.this)
.fromResource(R.drawable.ic_circle);
markerView = mapboxMap.addMarker(new MarkerViewOptions()
.position(new LatLng(38.907192, -77.036871))
.icon(icon)
.flat(true));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
float newScale = getScale(progress);
textView.setText(String.format(Locale.US, "Scale: %.1f", newScale));
if (view != null) {
view.setScaleX(newScale);
view.setScaleY(newScale);
}
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
public void onStartTrackingTouch(SeekBar seekBar) {
// Not used
}
@Override
public void onStart() {
super.onResume();
mapView.onStart();
public void onStopTrackingTouch(SeekBar seekBar) {
// Not used
}
@Override
public void onStop(){
super.onStop();
mapView.onStop();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
private static class FactorChangeListener implements SeekBar.OnSeekBarChangeListener {
private TextView textView;
private View view;
FactorChangeListener(View view, TextView textView) {
this.view = view;
this.textView = textView;
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
float newScale = getScale(progress);
textView.setText(String.format(Locale.US, "Scale: %.1f", newScale));
if (view != null) {
view.setScaleX(newScale);
view.setScaleY(newScale);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Not used
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// Not used
}
private float getScale(int progress) {
float scale = 1.0f * progress / 25;
return scale < 1.0 ? 1.0f : scale;
}
private float getScale(int progress) {
float scale = 1.0f * progress / 25;
return scale < 1.0 ? 1.0f : scale;
}
}
}

View File

@@ -5,7 +5,6 @@ import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
@@ -18,116 +17,117 @@ import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.testapp.R;
import com.mapbox.mapboxsdk.testapp.activity.feature.QueryRenderedFeaturesBoxCountActivity;
import java.util.List;
import timber.log.Timber;
public class MarkerViewsInRectangleActivity extends AppCompatActivity implements OnMapReadyCallback,
View.OnClickListener {
View.OnClickListener {
public MapView mapView;
private MapboxMap mapboxMap;
private View selectionBox;
public MapView mapView;
private MapboxMap mapboxMap;
private View selectionBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_marker_view_in_rect);
setupActionBar();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_marker_view_in_rect);
setupActionBar();
selectionBox = findViewById(R.id.selection_box);
selectionBox = findViewById(R.id.selection_box);
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
@Override
public void onMapReady(MapboxMap mapboxMap) {
MarkerViewsInRectangleActivity.this.mapboxMap = mapboxMap;
selectionBox.setOnClickListener(this);
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(52.0907, 5.1214), 16));
mapboxMap.addMarker(new MarkerViewOptions().position(new LatLng(52.0907, 5.1214)));
}
@Override
public void onClick(View view) {
//Query
int top = selectionBox.getTop() - mapView.getTop();
int left = selectionBox.getLeft() - mapView.getLeft();
RectF box = new RectF(left, top, left + selectionBox.getWidth(), top + selectionBox.getHeight());
Timber.i(String.format("Querying box %s", box));
List<MarkerView> markers = mapboxMap.getMarkerViewsInRect(box);
//Show count
Toast.makeText(
MarkerViewsInRectangleActivity.this,
String.format("%s markers inside box", markers.size()),
Toast.LENGTH_SHORT).show();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onMapReady(MapboxMap mapboxMap) {
MarkerViewsInRectangleActivity.this.mapboxMap = mapboxMap;
selectionBox.setOnClickListener(this);
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(52.0907, 5.1214), 16));
mapboxMap.addMarker(new MarkerViewOptions().position(new LatLng(52.0907, 5.1214)));
}
@Override
public void onClick(View view) {
//Query
int top = selectionBox.getTop() - mapView.getTop();
int left = selectionBox.getLeft() - mapView.getLeft();
RectF box = new RectF(left, top, left + selectionBox.getWidth(), top + selectionBox.getHeight());
Timber.i(String.format("Querying box %s", box));
List<MarkerView> markers = mapboxMap.getMarkerViewsInRect(box);
//Show count
Toast.makeText(
MarkerViewsInRectangleActivity.this,
String.format("%s markers inside box", markers.size()),
Toast.LENGTH_SHORT).show();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
}
}

View File

@@ -38,160 +38,161 @@ import static com.mapbox.mapboxsdk.testapp.activity.annotation.PolygonActivity.C
*/
public class PolygonActivity extends AppCompatActivity implements OnMapReadyCallback {
private MapView mapView;
private MapboxMap mapboxMap;
private MapView mapView;
private MapboxMap mapboxMap;
private Polygon polygon;
private boolean fullAlpha = true;
private boolean visible = true;
private boolean color = true;
private boolean allPoints;
private Polygon polygon;
private boolean fullAlpha = true;
private boolean visible = true;
private boolean color = true;
private boolean allPoints;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_polygon);
ToolbarComposer.initDefaultUpToolbar(this, R.id.toolbar);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_polygon);
ToolbarComposer.initDefaultUpToolbar(this, R.id.toolbar);
// configure inital map state
MapboxMapOptions options = new MapboxMapOptions()
.attributionTintColor(RED_COLOR)
// deprecated feature!
.textureMode(true)
.compassFadesWhenFacingNorth(false)
.styleUrl(Style.MAPBOX_STREETS)
.camera(new CameraPosition.Builder()
.target(new LatLng(45.520486, -122.673541))
.zoom(12)
.tilt(40)
.build());
// configure inital map state
MapboxMapOptions options = new MapboxMapOptions()
.attributionTintColor(RED_COLOR)
// deprecated feature!
.textureMode(true)
.compassFadesWhenFacingNorth(false)
.styleUrl(Style.MAPBOX_STREETS)
.camera(new CameraPosition.Builder()
.target(new LatLng(45.520486, -122.673541))
.zoom(12)
.tilt(40)
.build());
// create map
mapView = new MapView(this, options);
mapView.setId(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
// create map
mapView = new MapView(this, options);
mapView.setId(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
// add to layout
ViewGroup container = (ViewGroup) findViewById(R.id.container);
if (container != null) {
container.addView(mapView);
}
// add to layout
ViewGroup container = (ViewGroup) findViewById(R.id.container);
if (container != null) {
container.addView(mapView);
}
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
polygon = mapboxMap.addPolygon(new PolygonOptions()
.addAll(STAR_SHAPE_POINTS)
.fillColor(BLUE_COLOR));
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
polygon = mapboxMap.addPolygon(new PolygonOptions()
.addAll(STAR_SHAPE_POINTS)
.fillColor(BLUE_COLOR));
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
case R.id.action_id_alpha:
fullAlpha = !fullAlpha;
polygon.setAlpha(fullAlpha ? FULL_ALPHA : PARTIAL_ALPHA);
return true;
case R.id.action_id_visible:
visible = !visible;
polygon.setAlpha(visible ? (fullAlpha ? FULL_ALPHA : PARTIAL_ALPHA) : NO_ALPHA);
return true;
case R.id.action_id_points:
allPoints = !allPoints;
polygon.setPoints(allPoints ? STAR_SHAPE_POINTS : BROKEN_SHAPE_POINTS);
return true;
case R.id.action_id_color:
color = !color;
polygon.setFillColor(color ? BLUE_COLOR : RED_COLOR);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_polygon, menu);
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.action_id_alpha:
fullAlpha = !fullAlpha;
polygon.setAlpha(fullAlpha ? FULL_ALPHA : PARTIAL_ALPHA);
return true;
case R.id.action_id_visible:
visible = !visible;
polygon.setAlpha(visible ? (fullAlpha ? FULL_ALPHA : PARTIAL_ALPHA) : NO_ALPHA);
return true;
case R.id.action_id_points:
allPoints = !allPoints;
polygon.setPoints(allPoints ? STAR_SHAPE_POINTS : BROKEN_SHAPE_POINTS);
return true;
case R.id.action_id_color:
color = !color;
polygon.setFillColor(color ? BLUE_COLOR : RED_COLOR);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
final static class Config {
static final int BLUE_COLOR = Color.parseColor("#3bb2d0");
static final int RED_COLOR = Color.parseColor("#AF0000");
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_polygon, menu);
return true;
}
static final float FULL_ALPHA = 1.0f;
static final float PARTIAL_ALPHA = 0.5f;
static final float NO_ALPHA = 0.0f;
static final class Config {
static final int BLUE_COLOR = Color.parseColor("#3bb2d0");
static final int RED_COLOR = Color.parseColor("#AF0000");
static final List<LatLng> STAR_SHAPE_POINTS = new ArrayList<LatLng>() {
{
add(new LatLng(45.522585, -122.685699));
add(new LatLng(45.534611, -122.708873));
add(new LatLng(45.530883, -122.678833));
add(new LatLng(45.547115, -122.667503));
add(new LatLng(45.530643, -122.660121));
add(new LatLng(45.533529, -122.636260));
add(new LatLng(45.521743, -122.659091));
add(new LatLng(45.510677, -122.648792));
add(new LatLng(45.515008, -122.664070));
add(new LatLng(45.502496, -122.669048));
add(new LatLng(45.515369, -122.678489));
add(new LatLng(45.506346, -122.702007));
add(new LatLng(45.522585, -122.685699));
}
};
static final float FULL_ALPHA = 1.0f;
static final float PARTIAL_ALPHA = 0.5f;
static final float NO_ALPHA = 0.0f;
static final List<LatLng> BROKEN_SHAPE_POINTS =
STAR_SHAPE_POINTS.subList(0, STAR_SHAPE_POINTS.size() - 3);
}
static final List<LatLng> STAR_SHAPE_POINTS = new ArrayList<LatLng>() {
{
add(new LatLng(45.522585, -122.685699));
add(new LatLng(45.534611, -122.708873));
add(new LatLng(45.530883, -122.678833));
add(new LatLng(45.547115, -122.667503));
add(new LatLng(45.530643, -122.660121));
add(new LatLng(45.533529, -122.636260));
add(new LatLng(45.521743, -122.659091));
add(new LatLng(45.510677, -122.648792));
add(new LatLng(45.515008, -122.664070));
add(new LatLng(45.502496, -122.669048));
add(new LatLng(45.515369, -122.678489));
add(new LatLng(45.506346, -122.702007));
add(new LatLng(45.522585, -122.685699));
}
};
static final List<LatLng> BROKEN_SHAPE_POINTS =
STAR_SHAPE_POINTS.subList(0, STAR_SHAPE_POINTS.size() - 3);
}
}

View File

@@ -24,205 +24,205 @@ import java.util.List;
public class PolylineActivity extends AppCompatActivity {
private static final String STATE_POLYLINE_OPTIONS = "polylineOptions";
private static final String STATE_POLYLINE_OPTIONS = "polylineOptions";
private static final LatLng ANDORRA = new LatLng(42.505777, 1.52529);
private static final LatLng LUXEMBOURG = new LatLng(49.815273, 6.129583);
private static final LatLng MONACO = new LatLng(43.738418, 7.424616);
private static final LatLng VATICAN_CITY = new LatLng(41.902916, 12.453389);
private static final LatLng SAN_MARINO = new LatLng(43.942360, 12.457777);
private static final LatLng LIECHTENSTEIN = new LatLng(47.166000, 9.555373);
private static final LatLng ANDORRA = new LatLng(42.505777, 1.52529);
private static final LatLng LUXEMBOURG = new LatLng(49.815273, 6.129583);
private static final LatLng MONACO = new LatLng(43.738418, 7.424616);
private static final LatLng VATICAN_CITY = new LatLng(41.902916, 12.453389);
private static final LatLng SAN_MARINO = new LatLng(43.942360, 12.457777);
private static final LatLng LIECHTENSTEIN = new LatLng(47.166000, 9.555373);
private static final float FULL_ALPHA = 1.0f;
private static final float PARTIAL_ALPHA = 0.5f;
private static final float NO_ALPHA = 0.0f;
private static final float FULL_ALPHA = 1.0f;
private static final float PARTIAL_ALPHA = 0.5f;
private static final float NO_ALPHA = 0.0f;
private List<Polyline> polylines;
private ArrayList<PolylineOptions> polylineOptions = new ArrayList<>();
private MapView mapView;
private MapboxMap mapboxMap;
private List<Polyline> polylines;
private ArrayList<PolylineOptions> polylineOptions = new ArrayList<>();
private MapView mapView;
private MapboxMap mapboxMap;
private boolean fullAlpha = true;
private boolean visible = true;
private boolean width = true;
private boolean color = true;
private boolean fullAlpha = true;
private boolean visible = true;
private boolean width = true;
private boolean color = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_polyline);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_polyline);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
if (savedInstanceState != null) {
polylineOptions = savedInstanceState.getParcelableArrayList(STATE_POLYLINE_OPTIONS);
} else {
polylineOptions.addAll(getAllPolylines());
}
if (savedInstanceState != null) {
polylineOptions = savedInstanceState.getParcelableArrayList(STATE_POLYLINE_OPTIONS);
} else {
polylineOptions.addAll(getAllPolylines());
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
PolylineActivity.this.mapboxMap = mapboxMap;
polylines = mapboxMap.addPolylines(polylineOptions);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
PolylineActivity.this.mapboxMap = mapboxMap;
polylines = mapboxMap.addPolylines(polylineOptions);
}
});
View fab = findViewById(R.id.fab);
if (fab != null) {
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mapboxMap != null) {
if (polylines != null && polylines.size() > 0) {
if (polylines.size() == 1) {
// test for removing annotation
mapboxMap.removeAnnotation(polylines.get(0));
} else {
// test for removing annotations
mapboxMap.removeAnnotations(polylines);
}
}
});
polylineOptions.clear();
polylineOptions.addAll(getRandomLine());
polylines = mapboxMap.addPolylines(polylineOptions);
View fab = findViewById(R.id.fab);
if (fab != null) {
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mapboxMap != null) {
if (polylines != null && polylines.size() > 0) {
if (polylines.size() == 1) {
// test for removing annotation
mapboxMap.removeAnnotation(polylines.get(0));
} else {
// test for removing annotations
mapboxMap.removeAnnotations(polylines);
}
}
polylineOptions.clear();
polylineOptions.addAll(getRandomLine());
polylines = mapboxMap.addPolylines(polylineOptions);
}
}
});
}
}
});
}
}
private List<PolylineOptions> getAllPolylines() {
List<PolylineOptions> options = new ArrayList<>();
options.add(generatePolyline(ANDORRA, LUXEMBOURG, "#F44336"));
options.add(generatePolyline(ANDORRA, MONACO, "#FF5722"));
options.add(generatePolyline(MONACO, VATICAN_CITY, "#673AB7"));
options.add(generatePolyline(VATICAN_CITY, SAN_MARINO, "#009688"));
options.add(generatePolyline(SAN_MARINO, LIECHTENSTEIN, "#795548"));
options.add(generatePolyline(LIECHTENSTEIN, LUXEMBOURG, "#3F51B5"));
return options;
}
private List<PolylineOptions> getAllPolylines() {
List<PolylineOptions> options = new ArrayList<>();
options.add(generatePolyline(ANDORRA, LUXEMBOURG, "#F44336"));
options.add(generatePolyline(ANDORRA, MONACO, "#FF5722"));
options.add(generatePolyline(MONACO, VATICAN_CITY, "#673AB7"));
options.add(generatePolyline(VATICAN_CITY, SAN_MARINO, "#009688"));
options.add(generatePolyline(SAN_MARINO, LIECHTENSTEIN, "#795548"));
options.add(generatePolyline(LIECHTENSTEIN, LUXEMBOURG, "#3F51B5"));
return options;
}
private PolylineOptions generatePolyline(LatLng start, LatLng end, String color) {
PolylineOptions line = new PolylineOptions();
line.add(start);
line.add(end);
line.color(Color.parseColor(color));
return line;
}
private PolylineOptions generatePolyline(LatLng start, LatLng end, String color) {
PolylineOptions line = new PolylineOptions();
line.add(start);
line.add(end);
line.color(Color.parseColor(color));
return line;
}
public List<PolylineOptions> getRandomLine() {
final List<PolylineOptions> randomLines = getAllPolylines();
Collections.shuffle(randomLines);
return new ArrayList<PolylineOptions>() {
{
add(randomLines.get(0));
}
};
}
public List<PolylineOptions> getRandomLine() {
final List<PolylineOptions> randomLines = getAllPolylines();
Collections.shuffle(randomLines);
return new ArrayList<PolylineOptions>() {
{
add(randomLines.get(0));
}
};
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_POLYLINE_OPTIONS, polylineOptions);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_POLYLINE_OPTIONS, polylineOptions);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_polyline, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_polyline, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_id_remove:
// test to remove all annotations
polylineOptions.clear();
mapboxMap.clear();
return true;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_id_remove:
// test to remove all annotations
polylineOptions.clear();
mapboxMap.clear();
return true;
case R.id.action_id_alpha:
fullAlpha = !fullAlpha;
for (Polyline p : polylines) {
p.setAlpha(fullAlpha ? FULL_ALPHA : PARTIAL_ALPHA);
}
return true;
case R.id.action_id_color:
color = !color;
for (Polyline p : polylines) {
p.setColor(color ? Color.RED : Color.BLUE);
}
return true;
case R.id.action_id_width:
width = !width;
for (Polyline p : polylines) {
p.setWidth(width ? 3.0f : 5.0f);
}
return true;
case R.id.action_id_visible:
visible = !visible;
for (Polyline p : polylines) {
p.setAlpha(visible ? (fullAlpha ? FULL_ALPHA : PARTIAL_ALPHA) : NO_ALPHA);
}
return true;
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
case R.id.action_id_alpha:
fullAlpha = !fullAlpha;
for (Polyline p : polylines) {
p.setAlpha(fullAlpha ? FULL_ALPHA : PARTIAL_ALPHA);
}
return true;
case R.id.action_id_color:
color = !color;
for (Polyline p : polylines) {
p.setColor(color ? Color.RED : Color.BLUE);
}
return true;
case R.id.action_id_width:
width = !width;
for (Polyline p : polylines) {
p.setWidth(width ? 3.0f : 5.0f);
}
return true;
case R.id.action_id_visible:
visible = !visible;
for (Polyline p : polylines) {
p.setAlpha(visible ? (fullAlpha ? FULL_ALPHA : PARTIAL_ALPHA) : NO_ALPHA);
}
return true;
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -22,130 +22,131 @@ import java.util.ArrayList;
public class PressForMarkerActivity extends AppCompatActivity {
private MapView mapView;
private MapboxMap mapboxMap;
private ArrayList<MarkerOptions> markerList = new ArrayList<>();
private MapView mapView;
private MapboxMap mapboxMap;
private ArrayList<MarkerOptions> markerList = new ArrayList<>();
private static final DecimalFormat LAT_LON_FORMATTER = new DecimalFormat("#.#####");
private static final DecimalFormat LAT_LON_FORMATTER = new DecimalFormat("#.#####");
private static String STATE_MARKER_LIST = "markerList";
private static String STATE_MARKER_LIST = "markerList";
@Override
protected void onCreate(@Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_press_for_marker);
@Override
protected void onCreate(@Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_press_for_marker);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(final MapboxMap map) {
mapboxMap = map;
resetMap();
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(final MapboxMap map) {
mapboxMap = map;
resetMap();
mapboxMap.setOnMapLongClickListener(new MapboxMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(@NonNull LatLng point) {
final PointF pixel = mapboxMap.getProjection().toScreenLocation(point);
mapboxMap.setOnMapLongClickListener(new MapboxMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(@NonNull LatLng point) {
final PointF pixel = mapboxMap.getProjection().toScreenLocation(point);
String title = LAT_LON_FORMATTER.format(point.getLatitude()) + ", " + LAT_LON_FORMATTER.format(point.getLongitude());
String snippet = "X = " + (int) pixel.x + ", Y = " + (int) pixel.y;
String title = LAT_LON_FORMATTER.format(point.getLatitude()) + ", "
+ LAT_LON_FORMATTER.format(point.getLongitude());
String snippet = "X = " + (int) pixel.x + ", Y = " + (int) pixel.y;
MarkerOptions marker = new MarkerOptions()
.position(point)
.title(title)
.snippet(snippet);
MarkerOptions marker = new MarkerOptions()
.position(point)
.title(title)
.snippet(snippet);
markerList.add(marker);
mapboxMap.addMarker(marker);
}
});
if (savedInstanceState != null) {
markerList = savedInstanceState.getParcelableArrayList(STATE_MARKER_LIST);
mapboxMap.addMarkers(markerList);
}
}
markerList.add(marker);
mapboxMap.addMarker(marker);
}
});
}
private void resetMap() {
if (mapboxMap == null) {
return;
if (savedInstanceState != null) {
markerList = savedInstanceState.getParcelableArrayList(STATE_MARKER_LIST);
mapboxMap.addMarkers(markerList);
}
mapboxMap.removeAnnotations();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_press_for_marker, menu);
private void resetMap() {
if (mapboxMap == null) {
return;
}
mapboxMap.removeAnnotations();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_press_for_marker, menu);
return true;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_MARKER_LIST, markerList);
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.menuItemReset:
resetMap();
return true;
default:
return super.onOptionsItemSelected(item);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_MARKER_LIST, markerList);
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.menuItemReset:
resetMap();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
}

View File

@@ -20,194 +20,194 @@ import timber.log.Timber;
public class CameraAnimationTypeActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final LatLng LAT_LNG_LONDON_EYE = new LatLng(51.50325, -0.11968);
private static final LatLng LAT_LNG_TOWER_BRIDGE = new LatLng(51.50550, -0.07520);
private static final LatLng LAT_LNG_LONDON_EYE = new LatLng(51.50325, -0.11968);
private static final LatLng LAT_LNG_TOWER_BRIDGE = new LatLng(51.50550, -0.07520);
private MapboxMap mapboxMap;
private MapView mapView;
private boolean cameraState;
private MapboxMap mapboxMap;
private MapView mapView;
private boolean cameraState;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_animation_types);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_animation_types);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
if (mapView != null) {
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
mapboxMap.getUiSettings().setAttributionEnabled(false);
mapboxMap.getUiSettings().setLogoEnabled(false);
mapboxMap.setOnCameraChangeListener(new MapboxMap.OnCameraChangeListener() {
mapView = (MapView) findViewById(R.id.mapView);
if (mapView != null) {
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
mapboxMap.getUiSettings().setAttributionEnabled(false);
mapboxMap.getUiSettings().setLogoEnabled(false);
mapboxMap.setOnCameraChangeListener(new MapboxMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition position) {
Timber.w(position.toString());
}
});
// handle move button clicks
View moveButton = findViewById(R.id.cameraMoveButton);
if (moveButton != null) {
moveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(getNextLatLng())
.zoom(14)
.tilt(30)
.tilt(0)
.build();
mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
}
// handle ease button clicks
View easeButton = findViewById(R.id.cameraEaseButton);
if (easeButton != null) {
easeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(getNextLatLng())
.zoom(15)
.bearing(180)
.tilt(30)
.build();
MapboxMap.CancelableCallback callback = new MapboxMap.CancelableCallback() {
@Override
public void onCameraChange(CameraPosition position) {
Timber.w(position.toString());
public void onCancel() {
Timber.i("Duration onCancel Callback called.");
Toast.makeText(
CameraAnimationTypeActivity.this,
"Ease onCancel Callback called.",
Toast.LENGTH_LONG).show();
}
});
// handle move button clicks
View moveButton = findViewById(R.id.cameraMoveButton);
if (moveButton != null) {
moveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(getNextLatLng())
.zoom(14)
.tilt(30)
.tilt(0)
.build();
mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
@Override
public void onFinish() {
Timber.i("Duration onFinish Callback called.");
Toast.makeText(
CameraAnimationTypeActivity.this,
"Ease onFinish Callback called.",
Toast.LENGTH_LONG).show();
}
};
mapboxMap.easeCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), 7500, callback);
}
});
}
// handle ease button clicks
View easeButton = findViewById(R.id.cameraEaseButton);
if (easeButton != null) {
easeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(getNextLatLng())
.zoom(15)
.bearing(180)
.tilt(30)
.build();
// handle animate button clicks
View animateButton = findViewById(R.id.cameraAnimateButton);
if (animateButton != null) {
animateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(getNextLatLng())
.bearing(270)
.tilt(20)
.build();
MapboxMap.CancelableCallback callback = new MapboxMap.CancelableCallback() {
@Override
public void onCancel() {
Timber.i("Duration onCancel Callback called.");
Toast.makeText(
CameraAnimationTypeActivity.this,
"Ease onCancel Callback called.",
Toast.LENGTH_LONG).show();
}
MapboxMap.CancelableCallback callback = new MapboxMap.CancelableCallback() {
@Override
public void onCancel() {
Timber.i("Duration onCancel Callback called.");
Toast.makeText(
CameraAnimationTypeActivity.this,
"Duration onCancel Callback called.",
Toast.LENGTH_LONG).show();
}
@Override
public void onFinish() {
Timber.i("Duration onFinish Callback called.");
Toast.makeText(
CameraAnimationTypeActivity.this,
"Ease onFinish Callback called.",
Toast.LENGTH_LONG).show();
}
};
@Override
public void onFinish() {
Timber.i("Duration onFinish Callback called.");
Toast.makeText(
CameraAnimationTypeActivity.this,
"Duration onFinish Callback called.",
Toast.LENGTH_LONG).show();
}
};
mapboxMap.easeCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), 7500, callback);
}
});
}
// handle animate button clicks
View animateButton = findViewById(R.id.cameraAnimateButton);
if (animateButton != null) {
animateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(getNextLatLng())
.bearing(270)
.tilt(20)
.build();
MapboxMap.CancelableCallback callback = new MapboxMap.CancelableCallback() {
@Override
public void onCancel() {
Timber.i("Duration onCancel Callback called.");
Toast.makeText(
CameraAnimationTypeActivity.this,
"Duration onCancel Callback called.",
Toast.LENGTH_LONG).show();
}
@Override
public void onFinish() {
Timber.i("Duration onFinish Callback called.");
Toast.makeText(
CameraAnimationTypeActivity.this,
"Duration onFinish Callback called.",
Toast.LENGTH_LONG).show();
}
};
mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), 7500, callback);
}
});
mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), 7500, callback);
}
});
}
}
private LatLng getNextLatLng() {
cameraState = !cameraState;
return cameraState ? LAT_LNG_TOWER_BRIDGE : LAT_LNG_LONDON_EYE;
}
private LatLng getNextLatLng() {
cameraState = !cameraState;
return cameraState ? LAT_LNG_TOWER_BRIDGE : LAT_LNG_LONDON_EYE;
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -11,7 +11,9 @@ import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
@@ -28,187 +30,188 @@ import com.mapbox.mapboxsdk.testapp.R;
public class CameraPositionActivity extends AppCompatActivity implements OnMapReadyCallback {
private MapView mapView;
private MapboxMap mapboxMap;
private MapView mapView;
private MapboxMap mapboxMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_position);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_position);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
@Override
public void onMapReady(@NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
mapboxMap.setOnCameraChangeListener(new MapboxMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition position) {
Timber.w("OnCameraChange: " + position);
}
@Override
public void onMapReady(@NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
mapboxMap.setOnCameraChangeListener(new MapboxMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition position) {
Timber.w("OnCameraChange: " + position);
}
});
// add a listener to FAB
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setColorFilter(ContextCompat.getColor(CameraPositionActivity.this, R.color.primary));
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Context context = view.getContext();
final View dialogContent = LayoutInflater.from(context).inflate(R.layout.dialog_camera_position, null);
AlertDialog.Builder builder = new AlertDialog.Builder(
context, com.mapbox.mapboxsdk.R.style.mapbox_AlertDialogStyle);
builder.setTitle(R.string.dialog_camera_position);
builder.setView(onInflateDialogContent(dialogContent));
builder.setPositiveButton("Animate", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
double latitude = Double.parseDouble(
((TextView) dialogContent.findViewById(R.id.value_lat)).getText().toString());
double longitude = Double.parseDouble(
((TextView) dialogContent.findViewById(R.id.value_lon)).getText().toString());
double zoom = Double.parseDouble(
((TextView) dialogContent.findViewById(R.id.value_zoom)).getText().toString());
double bearing = Double.parseDouble(
((TextView) dialogContent.findViewById(R.id.value_bearing)).getText().toString());
double tilt = Double.parseDouble(
((TextView) dialogContent.findViewById(R.id.value_tilt)).getText().toString());
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude))
.zoom(zoom)
.bearing(bearing)
.tilt(tilt)
.build();
mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), 5000,
new MapboxMap.CancelableCallback() {
@Override
public void onCancel() {
Timber.v("OnCancel called");
}
@Override
public void onFinish() {
Timber.v("OnFinish called");
}
});
Timber.v(cameraPosition.toString());
}
});
builder.setNegativeButton("Cancel", null);
builder.setCancelable(false);
builder.show();
}
});
}
// add a listener to FAB
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setColorFilter(ContextCompat.getColor(CameraPositionActivity.this, R.color.primary));
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Context context = v.getContext();
final View dialogContent = LayoutInflater.from(context).inflate(R.layout.dialog_camera_position, null);
AlertDialog.Builder builder = new AlertDialog.Builder(
context, com.mapbox.mapboxsdk.R.style.mapbox_AlertDialogStyle);
builder.setTitle(R.string.dialog_camera_position);
builder.setView(onInflateDialogContent(dialogContent));
builder.setPositiveButton("Animate", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
double latitude = Double.parseDouble(
((TextView) dialogContent.findViewById(R.id.value_lat)).getText().toString());
double longitude = Double.parseDouble(
((TextView) dialogContent.findViewById(R.id.value_lon)).getText().toString());
double zoom = Double.parseDouble(
((TextView) dialogContent.findViewById(R.id.value_zoom)).getText().toString());
double bearing = Double.parseDouble(
((TextView) dialogContent.findViewById(R.id.value_bearing)).getText().toString());
double tilt = Double.parseDouble(
((TextView) dialogContent.findViewById(R.id.value_tilt)).getText().toString());
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude))
.zoom(zoom)
.bearing(bearing)
.tilt(tilt)
.build();
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), 5000, new MapboxMap.CancelableCallback() {
@Override
public void onCancel() {
Timber.v("OnCancel called");
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onFinish() {
Timber.v("OnFinish called");
}
});
Timber.v(cameraPosition.toString());
}
});
builder.setNegativeButton("Cancel", null);
builder.setCancelable(false);
builder.show();
}
});
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private View onInflateDialogContent(View view) {
linkTextView(view, R.id.value_lat, R.id.seekbar_lat, new LatLngChangeListener(), 180 + 38);
linkTextView(view, R.id.value_lon, R.id.seekbar_lon, new LatLngChangeListener(), 180 - 77);
linkTextView(view, R.id.value_zoom, R.id.seekbar_zoom, new ValueChangeListener(), 6);
linkTextView(view, R.id.value_bearing, R.id.seekbar_bearing, new ValueChangeListener(), 90);
linkTextView(view, R.id.value_tilt, R.id.seekbar_tilt, new ValueChangeListener(), 40);
return view;
}
private void linkTextView(
View view, @IdRes int textViewRes, @IdRes int seekBarRes, ValueChangeListener listener, int defaultValue) {
final TextView value = (TextView) view.findViewById(textViewRes);
SeekBar seekBar = (SeekBar) view.findViewById(seekBarRes);
listener.setLinkedValueView(value);
seekBar.setOnSeekBarChangeListener(listener);
seekBar.setProgress(defaultValue);
}
private class ValueChangeListener implements SeekBar.OnSeekBarChangeListener {
protected TextView textView;
public void setLinkedValueView(TextView textView) {
this.textView = textView;
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textView.setText(String.valueOf(progress));
}
}
private class LatLngChangeListener extends ValueChangeListener {
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
super.onProgressChanged(seekBar, progress - 180, fromUser);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private View onInflateDialogContent(View view) {
linkTextView(view, R.id.value_lat, R.id.seekbar_lat, new LatLngChangeListener(), 180 + 38);
linkTextView(view, R.id.value_lon, R.id.seekbar_lon, new LatLngChangeListener(), 180 - 77);
linkTextView(view, R.id.value_zoom, R.id.seekbar_zoom, new ValueChangeListener(), 6);
linkTextView(view, R.id.value_bearing, R.id.seekbar_bearing, new ValueChangeListener(), 90);
linkTextView(view, R.id.value_tilt, R.id.seekbar_tilt, new ValueChangeListener(), 40);
return view;
}
private void linkTextView(
View view, @IdRes int textViewRes, @IdRes int seekBarRes, ValueChangeListener listener, int defaultValue) {
final TextView value = (TextView) view.findViewById(textViewRes);
SeekBar seekBar = (SeekBar) view.findViewById(seekBarRes);
listener.setLinkedValueView(value);
seekBar.setOnSeekBarChangeListener(listener);
seekBar.setProgress(defaultValue);
}
private class ValueChangeListener implements SeekBar.OnSeekBarChangeListener {
protected TextView textView;
public void setLinkedValueView(TextView textView) {
this.textView = textView;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textView.setText(String.valueOf(progress));
}
}
private class LatLngChangeListener extends ValueChangeListener {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
super.onProgressChanged(seekBar, progress - 180, fromUser);
}
}
}
}
}

View File

@@ -4,7 +4,9 @@ import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.MenuItem;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
@@ -23,120 +25,120 @@ import java.util.List;
public class LatLngBoundsActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final LatLng LOS_ANGELES = new LatLng(34.053940, -118.242622);
private static final LatLng NEW_YORK = new LatLng(40.712730, -74.005953);
private static final LatLng LOS_ANGELES = new LatLng(34.053940, -118.242622);
private static final LatLng NEW_YORK = new LatLng(40.712730, -74.005953);
private MapView mapView;
private MapboxMap mapboxMap;
private MapView mapView;
private MapboxMap mapboxMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visible_bounds);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visible_bounds);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.setStyleUrl(Style.DARK);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
UiSettings uiSettings = mapboxMap.getUiSettings();
uiSettings.setAllGesturesEnabled(false);
mapView = (MapView) findViewById(R.id.mapView);
mapView.setStyleUrl(Style.DARK);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
mapboxMap.addMarker(new MarkerOptions()
.title("Los Angeles")
.snippet("City Hall")
.position(LOS_ANGELES));
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
UiSettings uiSettings = mapboxMap.getUiSettings();
uiSettings.setAllGesturesEnabled(false);
mapboxMap.addMarker(new MarkerOptions()
.title("New York")
.snippet("City Hall")
.position(NEW_YORK));
mapboxMap.addMarker(new MarkerOptions()
.title("Los Angeles")
.snippet("City Hall")
.position(LOS_ANGELES));
List<LatLng> points = new ArrayList<>();
points.add(NEW_YORK);
points.add(LOS_ANGELES);
mapboxMap.addMarker(new MarkerOptions()
.title("New York")
.snippet("City Hall")
.position(NEW_YORK));
// Create Bounds
final LatLngBounds bounds = new LatLngBounds.Builder()
.includes(points)
.build();
List<LatLng> points = new ArrayList<>();
points.add(NEW_YORK);
points.add(LOS_ANGELES);
// Add map padding
int mapPadding = (int) getResources().getDimension(R.dimen.fab_margin);
mapboxMap.setPadding(mapPadding, mapPadding, mapPadding, mapPadding);
// Create Bounds
final LatLngBounds bounds = new LatLngBounds.Builder()
.includes(points)
.build();
// Move camera to the bounds with added padding
int padding = (int) getResources().getDimension(R.dimen.coordinatebounds_margin);
mapboxMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, padding));
// Add map padding
int mapPadding = (int) getResources().getDimension(R.dimen.fab_margin);
mapboxMap.setPadding(mapPadding, mapPadding, mapPadding, mapPadding);
// Log data
Timber.e("Move to bounds: " + bounds.toString());
Timber.e("Resulting bounds:" + mapboxMap.getProjection().getVisibleRegion().latLngBounds.toString());
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
// Move camera to the bounds with added padding
int padding = (int) getResources().getDimension(R.dimen.coordinatebounds_margin);
mapboxMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, padding));
// Log data
Timber.e("Move to bounds: " + bounds.toString());
Timber.e("Resulting bounds:" + mapboxMap.getProjection().getVisibleRegion().latLngBounds.toString());
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -20,116 +20,116 @@ import com.mapbox.mapboxsdk.testapp.R;
public class ManualZoomActivity extends AppCompatActivity {
private MapboxMap mapboxMap;
private MapView mapView;
private MapboxMap mapboxMap;
private MapView mapView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual_zoom);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual_zoom);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.setStyleUrl(Style.SATELLITE);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull final MapboxMap mapboxMap) {
ManualZoomActivity.this.mapboxMap = mapboxMap;
UiSettings uiSettings = ManualZoomActivity.this.mapboxMap.getUiSettings();
uiSettings.setAllGesturesEnabled(false);
}
});
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_zoom, menu);
mapView = (MapView) findViewById(R.id.mapView);
mapView.setStyleUrl(Style.SATELLITE);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull final MapboxMap mapboxMap) {
ManualZoomActivity.this.mapboxMap = mapboxMap;
UiSettings uiSettings = ManualZoomActivity.this.mapboxMap.getUiSettings();
uiSettings.setAllGesturesEnabled(false);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_zoom, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.action_zoom_in:
mapboxMap.animateCamera(CameraUpdateFactory.zoomIn());
return true;
case R.id.action_zoom_out:
mapboxMap.animateCamera(CameraUpdateFactory.zoomOut());
return true;
case R.id.action_zoom_by:
mapboxMap.animateCamera(CameraUpdateFactory.zoomBy(2));
return true;
case R.id.action_zoom_to:
mapboxMap.animateCamera(CameraUpdateFactory.zoomTo(2));
return true;
case R.id.action_zoom_to_point:
View view = getWindow().getDecorView();
mapboxMap.animateCamera(
CameraUpdateFactory.zoomBy(1, new Point(view.getMeasuredWidth() / 4, view.getMeasuredHeight() / 4)));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
case android.R.id.home:
onBackPressed();
return true;
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
case R.id.action_zoom_in:
mapboxMap.animateCamera(CameraUpdateFactory.zoomIn());
return true;
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
case R.id.action_zoom_out:
mapboxMap.animateCamera(CameraUpdateFactory.zoomOut());
return true;
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
case R.id.action_zoom_by:
mapboxMap.animateCamera(CameraUpdateFactory.zoomBy(2));
return true;
case R.id.action_zoom_to:
mapboxMap.animateCamera(CameraUpdateFactory.zoomTo(2));
return true;
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
case R.id.action_zoom_to_point:
View view = getWindow().getDecorView();
mapboxMap.animateCamera(
CameraUpdateFactory.zoomBy(1, new Point(view.getMeasuredWidth() / 4, view.getMeasuredHeight() / 4)));
return true;
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}

View File

@@ -13,86 +13,86 @@ import com.mapbox.mapboxsdk.testapp.R;
public class MaxMinZoomActivity extends AppCompatActivity implements OnMapReadyCallback {
private MapView mapView;
private MapboxMap mapboxMap;
private MapView mapView;
private MapboxMap mapboxMap;
@Override
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maxmin_zoom);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maxmin_zoom);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
mapboxMap.setMinZoomPreference(3);
mapboxMap.setMaxZoomPreference(5);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return false;
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
mapboxMap.setMinZoomPreference(3);
mapboxMap.setMaxZoomPreference(5);
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return false;
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}

View File

@@ -22,139 +22,139 @@ import com.mapbox.mapboxsdk.testapp.R;
public class ScrollByActivity extends AppCompatActivity implements OnMapReadyCallback {
public static final int MULTIPLIER_PER_PIXEL = 50;
public static final int MULTIPLIER_PER_PIXEL = 50;
private MapView mapView;
private MapboxMap mapboxMap;
private SeekBar xBar;
private SeekBar yBar;
private MapView mapView;
private MapboxMap mapboxMap;
private SeekBar seekBarX;
private SeekBar seekBarY;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scroll_by);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scroll_by);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
xBar = (SeekBar) findViewById(R.id.seekbar_move_x);
TextView xText = (TextView) findViewById(R.id.textview_x);
xBar.setOnSeekBarChangeListener(new PixelBarChangeListener(xText, R.string.scrollby_x_value));
seekBarX = (SeekBar) findViewById(R.id.seekbar_move_x);
TextView textViewX = (TextView) findViewById(R.id.textview_x);
seekBarX.setOnSeekBarChangeListener(new PixelBarChangeListener(textViewX, R.string.scrollby_x_value));
yBar = (SeekBar) findViewById(R.id.seekbar_move_y);
TextView yText = (TextView) findViewById(R.id.textview_y);
yBar.setOnSeekBarChangeListener(new PixelBarChangeListener(yText, R.string.scrollby_y_value));
seekBarY = (SeekBar) findViewById(R.id.seekbar_move_y);
TextView textViewY = (TextView) findViewById(R.id.textview_y);
seekBarY.setOnSeekBarChangeListener(new PixelBarChangeListener(textViewY, R.string.scrollby_y_value));
mapView = (MapView) findViewById(R.id.mapView);
mapView.setTag(true);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
mapView = (MapView) findViewById(R.id.mapView);
mapView.setTag(true);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
UiSettings uiSettings = mapboxMap.getUiSettings();
uiSettings.setLogoEnabled(false);
uiSettings.setAttributionEnabled(false);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setColorFilter(ContextCompat.getColor(ScrollByActivity.this, R.color.primary));
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mapboxMap.easeCamera(CameraUpdateFactory.scrollBy(
seekBarX.getProgress() * MULTIPLIER_PER_PIXEL,
seekBarY.getProgress() * MULTIPLIER_PER_PIXEL)
);
}
});
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private static class PixelBarChangeListener implements SeekBar.OnSeekBarChangeListener {
@StringRes
private int prefixTextResource;
private TextView valueView;
public PixelBarChangeListener(@NonNull TextView textView, @StringRes int textRes) {
valueView = textView;
prefixTextResource = textRes;
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
UiSettings uiSettings = mapboxMap.getUiSettings();
uiSettings.setLogoEnabled(false);
uiSettings.setAttributionEnabled(false);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setColorFilter(ContextCompat.getColor(ScrollByActivity.this, R.color.primary));
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mapboxMap.easeCamera(CameraUpdateFactory.scrollBy(
xBar.getProgress() * MULTIPLIER_PER_PIXEL,
yBar.getProgress() * MULTIPLIER_PER_PIXEL)
);
}
});
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int value = progress * ScrollByActivity.MULTIPLIER_PER_PIXEL;
valueView.setText(String.format(seekBar.getResources().getString(prefixTextResource), value));
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private static class PixelBarChangeListener implements SeekBar.OnSeekBarChangeListener {
@StringRes
private int prefixTextResource;
private TextView valueView;
public PixelBarChangeListener(@NonNull TextView textView, @StringRes int textRes) {
valueView = textView;
prefixTextResource = textRes;
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int value = progress * ScrollByActivity.MULTIPLIER_PER_PIXEL;
valueView.setText(String.format(seekBar.getResources().getString(prefixTextResource), value));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
}

View File

@@ -6,7 +6,9 @@ import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
@@ -23,147 +25,147 @@ import com.mapbox.mapboxsdk.testapp.model.customlayer.ExampleCustomLayer;
public class CustomLayerActivity extends AppCompatActivity {
private MapboxMap mapboxMap;
private MapView mapView;
private CustomLayer customLayer;
private MapboxMap mapboxMap;
private MapView mapView;
private CustomLayer customLayer;
private FloatingActionButton fab;
private FloatingActionButton fab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_layer);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_layer);
setupActionBar();
setupActionBar();
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(39.91448, -243.60947), 10));
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(39.91448, -243.60947), 10));
}
});
}
});
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setColorFilter(ContextCompat.getColor(this, R.color.primary));
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mapboxMap != null) {
swapCustomLayer();
}
}
});
}
private void swapCustomLayer() {
if (customLayer != null) {
try {
mapboxMap.removeLayer(customLayer.getId());
customLayer = null;
} catch (NoSuchLayerException noSuchLayerException) {
Timber.e("No custom layer to remove");
}
fab.setImageResource(R.drawable.ic_layers_24dp);
} else {
customLayer = new CustomLayer("custom",
ExampleCustomLayer.createContext(),
ExampleCustomLayer.InitializeFunction,
ExampleCustomLayer.RenderFunction,
ExampleCustomLayer.DeinitializeFunction);
mapboxMap.addLayer(customLayer, "building");
fab.setImageResource(R.drawable.ic_layers_clear_24dp);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setColorFilter(ContextCompat.getColor(this, R.color.primary));
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mapboxMap != null) {
swapCustomLayer();
}
}
}
});
}
private void updateLayer() {
if (customLayer != null) {
customLayer.update();
}
private void swapCustomLayer() {
if (customLayer != null) {
try {
mapboxMap.removeLayer(customLayer.getId());
customLayer = null;
} catch (NoSuchLayerException noSuchLayerException) {
Timber.e("No custom layer to remove");
}
fab.setImageResource(R.drawable.ic_layers_24dp);
} else {
customLayer = new CustomLayer("custom",
ExampleCustomLayer.createContext(),
ExampleCustomLayer.InitializeFunction,
ExampleCustomLayer.RenderFunction,
ExampleCustomLayer.DeinitializeFunction);
mapboxMap.addLayer(customLayer, "building");
fab.setImageResource(R.drawable.ic_layers_clear_24dp);
}
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
private void updateLayer() {
if (customLayer != null) {
customLayer.update();
}
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_custom_layer, menu);
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_custom_layer, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.action_update_layer:
updateLayer();
return true;
case R.id.action_set_color_red:
ExampleCustomLayer.setColor(1, 0, 0, 1);
return true;
case R.id.action_set_color_green:
ExampleCustomLayer.setColor(0, 1, 0, 1);
return true;
case R.id.action_set_color_blue:
ExampleCustomLayer.setColor(0, 0, 1, 1);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.action_update_layer:
updateLayer();
return true;
case R.id.action_set_color_red:
ExampleCustomLayer.setColor(1, 0, 0, 1);
return true;
case R.id.action_set_color_green:
ExampleCustomLayer.setColor(0, 1, 0, 1);
return true;
case R.id.action_set_color_blue:
ExampleCustomLayer.setColor(0, 0, 1, 1);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
}
}

View File

@@ -6,8 +6,11 @@ import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.MenuItem;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
import com.mapbox.mapboxsdk.annotations.PolylineOptions;
import com.mapbox.mapboxsdk.camera.CameraPosition;
@@ -35,176 +38,176 @@ import retrofit2.Response;
public class DirectionsActivity extends AppCompatActivity {
private MapView mapView;
private MapboxMap mapboxMap;
private MapView mapView;
private MapboxMap mapboxMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_directions);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_directions);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
DirectionsActivity.this.mapboxMap = mapboxMap;
loadRoute();
}
});
}
private void loadRoute() {
// Dupont Circle (Washington, DC)
Position origin = Position.fromCoordinates(-77.04341, 38.90962);
// The White House (Washington, DC)
Position destination = Position.fromCoordinates(-77.0365, 38.8977);
// Set map at centroid
LatLng centroid = new LatLng(
(origin.getLatitude() + destination.getLatitude()) / 2,
(origin.getLongitude() + destination.getLongitude()) / 2);
mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder()
.target(centroid)
.zoom(14)
.build()));
// Add origin and destination to the map
mapboxMap.addMarker(new MarkerOptions()
.position(new LatLng(origin.getLatitude(), origin.getLongitude()))
.title("Origin")
.snippet("Dupont Circle"));
mapboxMap.addMarker(new MarkerOptions()
.position(new LatLng(destination.getLatitude(), destination.getLongitude()))
.title("Destination")
.snippet("The White House"));
// Get route from API
getRoute(origin, destination);
}
private void getRoute(Position origin, Position destination) {
try {
MapboxDirections md = new MapboxDirections.Builder()
.setAccessToken(getString(R.string.mapbox_access_token))
.setOrigin(origin)
.setOverview(DirectionsCriteria.OVERVIEW_FULL)
.setDestination(destination)
.setProfile(DirectionsCriteria.PROFILE_WALKING)
.build();
md.enqueueCall(new Callback<DirectionsResponse>() {
@Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Timber.e("Error: " + throwable.getMessage());
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
DirectionsActivity.this.mapboxMap = mapboxMap;
loadRoute();
}
});
}
@Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get generic HTTP info about the response
Timber.d("Response code: " + response.code());
private void loadRoute() {
// Dupont Circle (Washington, DC)
Position origin = Position.fromCoordinates(-77.04341, 38.90962);
// Print some info about the route
DirectionsRoute currentRoute = response.body().getRoutes().get(0);
Timber.d("Distance: " + currentRoute.getDistance());
// The White House (Washington, DC)
Position destination = Position.fromCoordinates(-77.0365, 38.8977);
// Set map at centroid
LatLng centroid = new LatLng(
(origin.getLatitude() + destination.getLatitude()) / 2,
(origin.getLongitude() + destination.getLongitude()) / 2);
mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder()
.target(centroid)
.zoom(14)
.build()));
// Add origin and destination to the map
mapboxMap.addMarker(new MarkerOptions()
.position(new LatLng(origin.getLatitude(), origin.getLongitude()))
.title("Origin")
.snippet("Dupont Circle"));
mapboxMap.addMarker(new MarkerOptions()
.position(new LatLng(destination.getLatitude(), destination.getLongitude()))
.title("Destination")
.snippet("The White House"));
// Get route from API
getRoute(origin, destination);
}
private void getRoute(Position origin, Position destination) {
try {
MapboxDirections md = new MapboxDirections.Builder()
.setAccessToken(getString(R.string.mapbox_access_token))
.setOrigin(origin)
.setOverview(DirectionsCriteria.OVERVIEW_FULL)
.setDestination(destination)
.setProfile(DirectionsCriteria.PROFILE_WALKING)
.build();
md.enqueueCall(new Callback<DirectionsResponse>() {
@Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Timber.e("Error: " + throwable.getMessage());
}
@Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get generic HTTP info about the response
Timber.d("Response code: " + response.code());
// Print some info about the route
DirectionsRoute currentRoute = response.body().getRoutes().get(0);
Timber.d("Distance: " + currentRoute.getDistance());
// Draw the route on the map
drawRoute(currentRoute);
}
});
} catch (ServicesException servicesException) {
Timber.e("Error displaying route: " + servicesException.toString());
servicesException.printStackTrace();
}
}
private void drawRoute(DirectionsRoute route) {
PolylineOptions builder = new PolylineOptions();
builder.color(Color.parseColor("#3887be"));
builder.alpha(0.5f);
builder.width(5);
builder.width(5);
LineString lineString = LineString.fromPolyline(route.getGeometry(), Constants.OSRM_PRECISION_V5);
List<Position> coordinates = lineString.getCoordinates();
List<LatLng> points = new ArrayList<>();
for (int i = 0; i < coordinates.size(); i++) {
points.add(new LatLng(
coordinates.get(i).getLatitude(),
coordinates.get(i).getLongitude()));
// Draw the route on the map
drawRoute(currentRoute);
}
builder.addAll(points);
});
} catch (ServicesException servicesException) {
Timber.e("Error displaying route: " + servicesException.toString());
servicesException.printStackTrace();
}
}
// Draw Points on MapView
mapboxMap.addPolyline(builder);
private void drawRoute(DirectionsRoute route) {
PolylineOptions builder = new PolylineOptions();
builder.color(Color.parseColor("#3887be"));
builder.alpha(0.5f);
builder.width(5);
builder.width(5);
LineString lineString = LineString.fromPolyline(route.getGeometry(), Constants.OSRM_PRECISION_V5);
List<Position> coordinates = lineString.getCoordinates();
List<LatLng> points = new ArrayList<>();
for (int i = 0; i < coordinates.size(); i++) {
points.add(new LatLng(
coordinates.get(i).getLatitude(),
coordinates.get(i).getLongitude()));
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
builder.addAll(points);
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
// Draw Points on MapView
mapboxMap.addPolyline(builder);
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -13,68 +13,68 @@ import com.mapbox.mapboxsdk.testapp.R;
*/
public class EspressoTestActivity extends AppCompatActivity implements OnMapReadyCallback {
public MapView mapView;
protected MapboxMap mapboxMap;
public MapView mapView;
protected MapboxMap mapboxMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_test);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_test);
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
}
public MapboxMap getMapboxMap() {
return mapboxMap;
}
public MapboxMap getMapboxMap() {
return mapboxMap;
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}

View File

@@ -5,15 +5,11 @@ import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.google.gson.JsonElement;
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
@@ -23,143 +19,143 @@ import com.mapbox.services.commons.geojson.Feature;
import java.util.List;
import java.util.Map;
import timber.log.Timber;
/**
* Demo's query rendered features
*/
public class QueryRenderedFeaturesBoxCountActivity extends AppCompatActivity {
public MapView mapView;
private MapboxMap mapboxMap;
public MapView mapView;
private MapboxMap mapboxMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query_features_box);
setupActionBar();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query_features_box);
setupActionBar();
final float density = getResources().getDisplayMetrics().density;
final View selectionBox = findViewById(R.id.selection_box);
final View selectionBox = findViewById(R.id.selection_box);
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@SuppressWarnings("ConstantConditions")
@Override
public void onMapReady(final MapboxMap mapboxMap) {
QueryRenderedFeaturesBoxCountActivity.this.mapboxMap = mapboxMap;
selectionBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Query
int top = selectionBox.getTop() - mapView.getTop();
int left = selectionBox.getLeft() - mapView.getLeft();
RectF box = new RectF(left, top, left + selectionBox.getWidth(), top + selectionBox.getHeight());
Timber.i(String.format("Querying box %s", box));
List<Feature> features = mapboxMap.queryRenderedFeatures(box);
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@SuppressWarnings("ConstantConditions")
@Override
public void onMapReady(final MapboxMap mapboxMap) {
QueryRenderedFeaturesBoxCountActivity.this.mapboxMap = mapboxMap;
selectionBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Query
int top = selectionBox.getTop() - mapView.getTop();
int left = selectionBox.getLeft() - mapView.getLeft();
RectF box = new RectF(left, top, left + selectionBox.getWidth(), top + selectionBox.getHeight());
Timber.i(String.format("Querying box %s", box));
List<Feature> features = mapboxMap.queryRenderedFeatures(box);
//Show count
Toast.makeText(
QueryRenderedFeaturesBoxCountActivity.this,
String.format("%s features in box", features.size()),
Toast.LENGTH_SHORT).show();
//Show count
Toast.makeText(
QueryRenderedFeaturesBoxCountActivity.this,
String.format("%s features in box", features.size()),
Toast.LENGTH_SHORT).show();
//Debug output
debugOutput(features);
}
});
}
//Debug output
debugOutput(features);
}
});
}
}
});
}
private void debugOutput(List<Feature> features) {
Timber.i(String.format("Got %s features", features.size()));
for (Feature feature : features) {
if (feature != null) {
Timber.i(String.format("Got feature %s with %s properties and Geometry %s",
feature.getId(),
feature.getProperties() != null ? feature.getProperties().entrySet().size() : "<null>",
feature.getGeometry() != null ? feature.getGeometry().getClass().getSimpleName() : "<null>")
);
if (feature.getProperties() != null) {
for (Map.Entry<String, JsonElement> entry : feature.getProperties().entrySet()) {
Timber.i(String.format("Prop %s - %s", entry.getKey(), entry.getValue()));
}
}
} else {
// TODO Question: Why not formatting here??
Timber.i("Got NULL feature %s");
}
private void debugOutput(List<Feature> features) {
Timber.i(String.format("Got %s features", features.size()));
for (Feature feature : features) {
if (feature != null) {
Timber.i(String.format("Got feature %s with %s properties and Geometry %s",
feature.getId(),
feature.getProperties() != null ? feature.getProperties().entrySet().size() : "<null>",
feature.getGeometry() != null ? feature.getGeometry().getClass().getSimpleName() : "<null>")
);
if (feature.getProperties() != null) {
for (Map.Entry<String, JsonElement> entry : feature.getProperties().entrySet()) {
Timber.i(String.format("Prop %s - %s", entry.getKey(), entry.getValue()));
}
}
} else {
// TODO Question: Why not formatting here??
Timber.i("Got NULL feature %s");
}
}
}
public MapboxMap getMapboxMap() {
return mapboxMap;
public MapboxMap getMapboxMap() {
return mapboxMap;
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
}
}

View File

@@ -6,14 +6,10 @@ import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
@@ -25,6 +21,8 @@ import com.mapbox.services.commons.geojson.FeatureCollection;
import java.util.List;
import timber.log.Timber;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillColor;
/**
@@ -32,126 +30,129 @@ import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillColor;
*/
public class QueryRenderedFeaturesBoxHighlightActivity extends AppCompatActivity {
public MapView mapView;
private MapboxMap mapboxMap;
public MapView mapView;
private MapboxMap mapboxMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query_features_box);
setupActionBar();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query_features_box);
setupActionBar();
final View selectionBox = findViewById(R.id.selection_box);
final View selectionBox = findViewById(R.id.selection_box);
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@SuppressWarnings("ConstantConditions")
@Override
public void onMapReady(final MapboxMap mapboxMap) {
QueryRenderedFeaturesBoxHighlightActivity.this.mapboxMap = mapboxMap;
selectionBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Query
int top = selectionBox.getTop() - mapView.getTop();
int left = selectionBox.getLeft() - mapView.getLeft();
RectF box = new RectF(left, top, left + selectionBox.getWidth(), top + selectionBox.getHeight());
Timber.i(String.format("Querying box %s for buildings", box));
List<Feature> features = mapboxMap.queryRenderedFeatures(box, "building");
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@SuppressWarnings("ConstantConditions")
@Override
public void onMapReady(final MapboxMap mapboxMap) {
QueryRenderedFeaturesBoxHighlightActivity.this.mapboxMap = mapboxMap;
selectionBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Query
int top = selectionBox.getTop() - mapView.getTop();
int left = selectionBox.getLeft() - mapView.getLeft();
RectF box = new RectF(left, top, left + selectionBox.getWidth(), top + selectionBox.getHeight());
Timber.i(String.format("Querying box %s for buildings", box));
List<Feature> features = mapboxMap.queryRenderedFeatures(box, "building");
//Show count
Toast.makeText(
QueryRenderedFeaturesBoxHighlightActivity.this,
String.format("%s features in box", features.size()),
Toast.LENGTH_SHORT).show();
//Show count
Toast.makeText(
QueryRenderedFeaturesBoxHighlightActivity.this,
String.format("%s features in box", features.size()),
Toast.LENGTH_SHORT).show();
//remove layer / source if already added
try {
mapboxMap.removeSource("highlighted-shapes-source");
mapboxMap.removeLayer("highlighted-shapes-layer");
} catch (Exception exception) {
//that's ok
}
//Add layer / source
mapboxMap.addSource(new GeoJsonSource("highlighted-shapes-source", FeatureCollection.fromFeatures(features)));
mapboxMap.addLayer(new FillLayer("highlighted-shapes-layer", "highlighted-shapes-source")
.withProperties(fillColor(Color.RED)));
}
});
//remove layer / source if already added
try {
mapboxMap.removeSource("highlighted-shapes-source");
mapboxMap.removeLayer("highlighted-shapes-layer");
} catch (Exception exception) {
//that's ok
}
//Add layer / source
mapboxMap.addSource(
new GeoJsonSource("highlighted-shapes-source",
FeatureCollection.fromFeatures(features))
);
mapboxMap.addLayer(new FillLayer("highlighted-shapes-layer", "highlighted-shapes-source")
.withProperties(fillColor(Color.RED)));
}
});
}
});
}
public MapboxMap getMapboxMap() {
return mapboxMap;
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public MapboxMap getMapboxMap() {
return mapboxMap;
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
}
}

View File

@@ -7,7 +7,6 @@ import android.support.annotation.RawRes;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
@@ -29,6 +28,8 @@ import java.io.StringWriter;
import java.io.Writer;
import java.util.List;
import timber.log.Timber;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;
/**
@@ -36,148 +37,150 @@ import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;
*/
public class QueryRenderedFeaturesBoxSymbolCountActivity extends AppCompatActivity {
public MapView mapView;
private MapboxMap mapboxMap;
public MapView mapView;
private MapboxMap mapboxMap;
private Toast toast;
private Toast toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query_features_box);
setupActionBar();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query_features_box);
setupActionBar();
final float density = getResources().getDisplayMetrics().density;
final View selectionBox = findViewById(R.id.selection_box);
final View selectionBox = findViewById(R.id.selection_box);
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@SuppressWarnings("ConstantConditions")
@Override
public void onMapReady(final MapboxMap mapboxMap) {
QueryRenderedFeaturesBoxSymbolCountActivity.this.mapboxMap = mapboxMap;
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@SuppressWarnings("ConstantConditions")
@Override
public void onMapReady(final MapboxMap mapboxMap) {
QueryRenderedFeaturesBoxSymbolCountActivity.this.mapboxMap = mapboxMap;
//Add a symbol layer (also works with annotations)
try {
mapboxMap.addSource(new GeoJsonSource("symbols-source", readRawResource(R.raw.test_points_utrecht)));
} catch (IOException e) {
Timber.e("Could not load geojson: " + e.getMessage());
return;
}
mapboxMap.addImage("test-icon", BitmapFactory.decodeResource(getResources(), R.drawable.mapbox_marker_icon_default));
mapboxMap.addLayer(new SymbolLayer("symbols-layer", "symbols-source").withProperties(iconImage("test-icon")));
selectionBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Query
int top = selectionBox.getTop() - mapView.getTop();
int left = selectionBox.getLeft() - mapView.getLeft();
RectF box = new RectF(left, top, left + selectionBox.getWidth(), top + selectionBox.getHeight());
Timber.i(String.format("Querying box %s", box));
List<Feature> features = mapboxMap.queryRenderedFeatures(box, "symbols-layer");
//Show count
if (toast != null) {
toast.cancel();
}
toast = Toast.makeText(
QueryRenderedFeaturesBoxSymbolCountActivity.this,
String.format("%s features in box", features.size()),
Toast.LENGTH_SHORT);
toast.show();
}
});
}
});
}
private String readRawResource(@RawRes int rawResource) throws IOException {
InputStream is = getResources().openRawResource(rawResource);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
//Add a symbol layer (also works with annotations)
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
mapboxMap.addSource(new GeoJsonSource("symbols-source", readRawResource(R.raw.test_points_utrecht)));
} catch (IOException ioException) {
Timber.e("Could not load geojson: " + ioException.getMessage());
return;
}
mapboxMap.addImage(
"test-icon",
BitmapFactory.decodeResource(getResources(),
R.drawable.mapbox_marker_icon_default)
);
mapboxMap.addLayer(new SymbolLayer("symbols-layer", "symbols-source").withProperties(iconImage("test-icon")));
selectionBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Query
int top = selectionBox.getTop() - mapView.getTop();
int left = selectionBox.getLeft() - mapView.getLeft();
RectF box = new RectF(left, top, left + selectionBox.getWidth(), top + selectionBox.getHeight());
Timber.i(String.format("Querying box %s", box));
List<Feature> features = mapboxMap.queryRenderedFeatures(box, "symbols-layer");
//Show count
if (toast != null) {
toast.cancel();
}
} finally {
is.close();
}
toast = Toast.makeText(
QueryRenderedFeaturesBoxSymbolCountActivity.this,
String.format("%s features in box", features.size()),
Toast.LENGTH_SHORT);
toast.show();
}
});
}
});
}
return writer.toString();
private String readRawResource(@RawRes int rawResource) throws IOException {
InputStream is = getResources().openRawResource(rawResource);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int numRead;
while ((numRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, numRead);
}
} finally {
is.close();
}
public MapboxMap getMapboxMap() {
return mapboxMap;
}
return writer.toString();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
public MapboxMap getMapboxMap() {
return mapboxMap;
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
}
}

View File

@@ -9,7 +9,9 @@ import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
@@ -33,237 +35,235 @@ import java.util.Map;
*/
public class QueryRenderedFeaturesPropertiesActivity extends AppCompatActivity {
public MapView mapView;
private MapboxMap mapboxMap;
private Marker marker;
public MapView mapView;
private MapboxMap mapboxMap;
private Marker marker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query_features_point);
setupActionBar();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query_features_point);
setupActionBar();
final float density = getResources().getDisplayMetrics().density;
final float density = getResources().getDisplayMetrics().density;
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(final MapboxMap mapboxMap) {
QueryRenderedFeaturesPropertiesActivity.this.mapboxMap = mapboxMap;
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(final MapboxMap mapboxMap) {
QueryRenderedFeaturesPropertiesActivity.this.mapboxMap = mapboxMap;
//Add custom window adapter
addCustomInfoWindowAdapter(mapboxMap);
//Add custom window adapter
addCustomInfoWindowAdapter(mapboxMap);
//Add a click listener
mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() {
@Override
public void onMapClick(@NonNull LatLng point) {
//Query
final PointF pixel = mapboxMap.getProjection().toScreenLocation(point);
Timber.i(String.format(
"Requesting features for %sx%s (%sx%s adjusted for density)",
pixel.x, pixel.y, pixel.x / density, pixel.y / density)
);
List<Feature> features = mapboxMap.queryRenderedFeatures(pixel);
//Add a click listener
mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() {
@Override
public void onMapClick(@NonNull LatLng point) {
//Query
final PointF pixel = mapboxMap.getProjection().toScreenLocation(point);
Timber.i(String.format(
"Requesting features for %sx%s (%sx%s adjusted for density)",
pixel.x, pixel.y, pixel.x / density, pixel.y / density)
);
List<Feature> features = mapboxMap.queryRenderedFeatures(pixel);
//Debug output
debugOutput(features);
//Debug output
debugOutput(features);
//Remove any previous markers
if (marker != null) {
mapboxMap.removeMarker(marker);
}
//Add a marker on the clicked point
marker = mapboxMap.addMarker(new CustomMarkerOptions().position(point).features(features));
mapboxMap.selectMarker(marker);
}
});
//Remove any previous markers
if (marker != null) {
mapboxMap.removeMarker(marker);
}
//Add a marker on the clicked point
marker = mapboxMap.addMarker(new CustomMarkerOptions().position(point).features(features));
mapboxMap.selectMarker(marker);
}
});
}
});
}
}
private void debugOutput(List<Feature> features) {
Timber.i(String.format("Got %s features", features.size()));
for (Feature feature : features) {
if (feature != null) {
Timber.i(String.format("Got feature %s with %s properties and Geometry %s",
feature.getId(),
feature.getProperties() != null ? feature.getProperties().entrySet().size() : "<null>",
feature.getGeometry() != null ? feature.getGeometry().getClass().getSimpleName() : "<null>")
);
if (feature.getProperties() != null) {
for (Map.Entry<String, JsonElement> entry : feature.getProperties().entrySet()) {
Timber.i(String.format("Prop %s - %s", entry.getKey(), entry.getValue()));
}
}
} else {
// TODO Question: Why not formatting here??
Timber.i("Got NULL feature %s");
}
private void debugOutput(List<Feature> features) {
Timber.i(String.format("Got %s features", features.size()));
for (Feature feature : features) {
if (feature != null) {
Timber.i(String.format("Got feature %s with %s properties and Geometry %s",
feature.getId(),
feature.getProperties() != null ? feature.getProperties().entrySet().size() : "<null>",
feature.getGeometry() != null ? feature.getGeometry().getClass().getSimpleName() : "<null>")
);
if (feature.getProperties() != null) {
for (Map.Entry<String, JsonElement> entry : feature.getProperties().entrySet()) {
Timber.i(String.format("Prop %s - %s", entry.getKey(), entry.getValue()));
}
}
} else {
// TODO Question: Why not formatting here??
Timber.i("Got NULL feature %s");
}
}
}
private void addCustomInfoWindowAdapter(MapboxMap mapboxMap) {
mapboxMap.setInfoWindowAdapter(new MapboxMap.InfoWindowAdapter() {
private TextView row(String text) {
TextView view = new TextView(QueryRenderedFeaturesPropertiesActivity.this);
view.setText(text);
return view;
}
@Override
public View getInfoWindow(@NonNull Marker marker) {
CustomMarker customMarker = (CustomMarker) marker;
LinearLayout view = new LinearLayout(QueryRenderedFeaturesPropertiesActivity.this);
view.setOrientation(LinearLayout.VERTICAL);
view.setBackgroundColor(Color.WHITE);
if (customMarker.features.size() > 0) {
view.addView(row(String.format("Found %s features", customMarker.features.size())));
Feature feature = customMarker.features.get(0);
for (Map.Entry<String, JsonElement> prop : feature.getProperties().entrySet()) {
view.addView(row(String.format("%s: %s", prop.getKey(), prop.getValue())));
}
} else {
view.addView(row("No features here"));
}
return view;
}
});
}
public MapboxMap getMapboxMap() {
return mapboxMap;
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
}
private static class CustomMarker extends Marker {
private final List<Feature> features;
public CustomMarker(BaseMarkerOptions baseMarkerOptions, List<Feature> features) {
super(baseMarkerOptions);
this.features = features;
}
}
private static class CustomMarkerOptions extends BaseMarkerOptions<CustomMarker, CustomMarkerOptions> {
private List<Feature> features;
public CustomMarkerOptions features(List<Feature> features) {
this.features = features;
return this;
}
private void addCustomInfoWindowAdapter(MapboxMap mapboxMap) {
mapboxMap.setInfoWindowAdapter(new MapboxMap.InfoWindowAdapter() {
private TextView row(String text) {
TextView view = new TextView(QueryRenderedFeaturesPropertiesActivity.this);
view.setText(text);
return view;
}
private int tenDp = (int) getResources().getDimension(R.dimen.attr_margin);
@Override
public View getInfoWindow(@NonNull Marker marker) {
CustomMarker customMarker = (CustomMarker) marker;
LinearLayout view = new LinearLayout(QueryRenderedFeaturesPropertiesActivity.this);
view.setOrientation(LinearLayout.VERTICAL);
view.setBackgroundColor(Color.WHITE);
if (customMarker.features.size() > 0) {
view.addView(row(String.format("Found %s features", customMarker.features.size())));
Feature feature = customMarker.features.get(0);
for (Map.Entry<String, JsonElement> prop : feature.getProperties().entrySet()) {
view.addView(row(String.format("%s: %s", prop.getKey(), prop.getValue())));
}
} else {
view.addView(row("No features here"));
}
return view;
}
});
public CustomMarkerOptions() {
}
public MapboxMap getMapboxMap() {
return mapboxMap;
private CustomMarkerOptions(Parcel in) {
//Should implement this
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
public CustomMarkerOptions getThis() {
return this;
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
public CustomMarker getMarker() {
return new CustomMarker(this, features);
}
public static final Parcelable.Creator<CustomMarkerOptions> CREATOR
= new Parcelable.Creator<CustomMarkerOptions>() {
public CustomMarkerOptions createFromParcel(Parcel in) {
return new CustomMarkerOptions(in);
}
public CustomMarkerOptions[] newArray(int size) {
return new CustomMarkerOptions[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
}
private static class CustomMarker extends Marker {
private final List<Feature> features;
public CustomMarker(BaseMarkerOptions baseMarkerOptions, List<Feature> features) {
super(baseMarkerOptions);
this.features = features;
}
}
private static class CustomMarkerOptions extends BaseMarkerOptions<CustomMarker, CustomMarkerOptions> {
private List<Feature> features;
public CustomMarkerOptions features(List<Feature> features) {
this.features = features;
return this;
}
public CustomMarkerOptions() {
}
private CustomMarkerOptions(Parcel in) {
//Should implement this
}
@Override
public CustomMarkerOptions getThis() {
return this;
}
@Override
public CustomMarker getMarker() {
return new CustomMarker(this, features);
}
public static final Parcelable.Creator<CustomMarkerOptions> CREATOR
= new Parcelable.Creator<CustomMarkerOptions>() {
public CustomMarkerOptions createFromParcel(Parcel in) {
return new CustomMarkerOptions(in);
}
public CustomMarkerOptions[] newArray(int size) {
return new CustomMarkerOptions[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
//Should implement this
}
public void writeToParcel(Parcel out, int flags) {
//Should implement this
}
}
}

View File

@@ -19,71 +19,71 @@ import com.mapbox.mapboxsdk.testapp.R;
public class MapFragmentActivity extends AppCompatActivity implements OnMapReadyCallback {
private MapboxMap mapboxMap;
private MapboxMap mapboxMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_fragment);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_fragment);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
MapFragment mapFragment;
if (savedInstanceState == null) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
MapboxMapOptions options = new MapboxMapOptions();
options.styleUrl(Style.OUTDOORS);
options.scrollGesturesEnabled(false);
options.zoomGesturesEnabled(false);
options.tiltGesturesEnabled(false);
options.rotateGesturesEnabled(false);
options.debugActive(false);
LatLng dc = new LatLng(38.90252, -77.02291);
options.minZoomPreference(9);
options.maxZoomPreference(11);
options.camera(new CameraPosition.Builder()
.target(dc)
.zoom(11)
.build());
mapFragment = MapFragment.newInstance(options);
transaction.add(R.id.fragment_container, mapFragment, "com.mapbox.map");
transaction.commit();
} else {
mapFragment = (MapFragment) getFragmentManager().findFragmentByTag("com.mapbox.map");
}
mapFragment.getMapAsync(this);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
mapboxMap.animateCamera(
CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder().tilt(45.0).build()), 10000);
MapFragment mapFragment;
if (savedInstanceState == null) {
final FragmentTransaction transaction = getFragmentManager().beginTransaction();
MapboxMapOptions options = new MapboxMapOptions();
options.styleUrl(Style.OUTDOORS);
options.scrollGesturesEnabled(false);
options.zoomGesturesEnabled(false);
options.tiltGesturesEnabled(false);
options.rotateGesturesEnabled(false);
options.debugActive(false);
LatLng dc = new LatLng(38.90252, -77.02291);
options.minZoomPreference(9);
options.maxZoomPreference(11);
options.camera(new CameraPosition.Builder()
.target(dc)
.zoom(11)
.build());
mapFragment = MapFragment.newInstance(options);
transaction.add(R.id.fragment_container, mapFragment, "com.mapbox.map");
transaction.commit();
} else {
mapFragment = (MapFragment) getFragmentManager().findFragmentByTag("com.mapbox.map");
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
mapboxMap.animateCamera(
CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder().tilt(45.0).build()), 10000);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -7,9 +7,9 @@ import com.mapbox.mapboxsdk.testapp.R;
public class MultiMapActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multi_map);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multi_map);
}
}

View File

@@ -19,74 +19,69 @@ import com.mapbox.mapboxsdk.testapp.R;
public class SupportMapFragmentActivity extends AppCompatActivity implements OnMapReadyCallback {
private MapboxMap mapboxMap;
private MapboxMap mapboxMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_fragment);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_fragment);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
SupportMapFragment mapFragment;
if (savedInstanceState == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
MapboxMapOptions options = new MapboxMapOptions();
options.styleUrl(Style.SATELLITE_STREETS);
options.scrollGesturesEnabled(false);
options.zoomGesturesEnabled(false);
options.tiltGesturesEnabled(false);
options.rotateGesturesEnabled(false);
options.debugActive(false);
options.compassEnabled(false);
options.attributionEnabled(false);
options.logoEnabled(false);
LatLng dc = new LatLng(38.90252, -77.02291);
options.minZoomPreference(9);
options.maxZoomPreference(11);
options.camera(new CameraPosition.Builder()
.target(dc)
.zoom(11)
.build());
mapFragment = SupportMapFragment.newInstance(options);
transaction.add(R.id.fragment_container, mapFragment, "com.mapbox.map");
transaction.commit();
} else {
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentByTag("com.mapbox.map");
}
mapFragment.getMapAsync(this);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
mapboxMap.animateCamera(
CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder().tilt(45.0).build()), 10000);
SupportMapFragment mapFragment;
if (savedInstanceState == null) {
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
MapboxMapOptions options = new MapboxMapOptions();
options.styleUrl(Style.SATELLITE_STREETS);
options.debugActive(false);
options.compassEnabled(false);
options.attributionEnabled(false);
options.logoEnabled(false);
LatLng dc = new LatLng(38.90252, -77.02291);
options.minZoomPreference(9);
options.maxZoomPreference(11);
options.camera(new CameraPosition.Builder()
.target(dc)
.zoom(11)
.build());
mapFragment = SupportMapFragment.newInstance(options);
transaction.add(R.id.fragment_container, mapFragment, "com.mapbox.map");
transaction.commit();
} else {
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentByTag("com.mapbox.map");
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
mapboxMap.animateCamera(
CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder().tilt(45.0).build()), 10000);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -19,81 +19,81 @@ import com.mapbox.mapboxsdk.testapp.R;
public class ViewPagerActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewpager);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewpager);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null) {
MapFragmentAdapter adapter = new MapFragmentAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
public static class MapFragmentAdapter extends FragmentPagerAdapter {
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null) {
MapFragmentAdapter adapter = new MapFragmentAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
}
}
private static int NUM_ITEMS = 3;
public static class MapFragmentAdapter extends FragmentPagerAdapter {
public MapFragmentAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
private static int NUM_ITEMS = 3;
@Override
public int getCount() {
return NUM_ITEMS;
}
@Override
public Fragment getItem(int position) {
SupportMapFragment fragment = null;
MapboxMapOptions options = new MapboxMapOptions();
switch (position) {
case 0:
options.styleUrl(Style.MAPBOX_STREETS);
options.camera(new CameraPosition.Builder().target(new LatLng(34.920526, 102.634774)).zoom(3).build());
fragment = SupportMapFragment.newInstance(options);
break;
case 1:
options.styleUrl(Style.DARK);
options.camera(new CameraPosition.Builder().target(new LatLng(62.326440, 92.764913)).zoom(3).build());
fragment = SupportMapFragment.newInstance(options);
break;
case 2:
options.styleUrl(Style.SATELLITE);
options.camera(new CameraPosition.Builder().target(new LatLng(-25.007786, 133.623852)).zoom(3).build());
fragment = SupportMapFragment.newInstance(options);
break;
}
return fragment;
}
@Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
public MapFragmentAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
public int getCount() {
return NUM_ITEMS;
}
@Override
public Fragment getItem(int position) {
SupportMapFragment fragment = null;
MapboxMapOptions options = new MapboxMapOptions();
switch (position) {
case 0:
options.styleUrl(Style.MAPBOX_STREETS);
options.camera(new CameraPosition.Builder().target(new LatLng(34.920526, 102.634774)).zoom(3).build());
fragment = SupportMapFragment.newInstance(options);
break;
case 1:
options.styleUrl(Style.DARK);
options.camera(new CameraPosition.Builder().target(new LatLng(62.326440, 92.764913)).zoom(3).build());
fragment = SupportMapFragment.newInstance(options);
break;
case 2:
options.styleUrl(Style.SATELLITE);
options.camera(new CameraPosition.Builder().target(new LatLng(-25.007786, 133.623852)).zoom(3).build());
fragment = SupportMapFragment.newInstance(options);
break;
}
return fragment;
}
@Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -6,7 +6,9 @@ import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.ViewGroup;
@@ -37,167 +39,167 @@ import retrofit2.Response;
public class GeocoderActivity extends AppCompatActivity implements OnMapReadyCallback {
private MapboxMap mapboxMap;
private MapView mapView;
private ImageView dropPinView;
private TextView textView;
private MapboxMap mapboxMap;
private MapView mapView;
private ImageView dropPinView;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geocoder);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geocoder);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
textView = (TextView) findViewById(R.id.message);
setMessage(getString(R.string.geocoder_instructions));
mapView = (MapView) findViewById(R.id.mapView);
mapView.setStyleUrl(Style.MAPBOX_STREETS);
mapView.onCreate(savedInstanceState);
dropPinView = new ImageView(this);
dropPinView.setImageResource(R.drawable.ic_droppin_24dp);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
dropPinView.setLayoutParams(params);
mapView.addView(dropPinView);
mapView.getMapAsync(this);
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
final Projection projection = mapboxMap.getProjection();
final int width = mapView.getMeasuredWidth();
final int height = mapView.getMeasuredHeight();
// Click listener
mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() {
@Override
public void onMapClick(@NonNull LatLng point) {
PointF centerPoint = new PointF(width / 2, (height + dropPinView.getHeight()) / 2);
LatLng centerLatLng = new LatLng(projection.fromScreenLocation(centerPoint));
setMessage("Geocoding...");
mapboxMap.removeAnnotations();
mapboxMap.addMarker(new MarkerOptions().position(centerLatLng));
geocode(centerLatLng);
}
});
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
/*
* Forward geocoding
*/
private void geocode(final LatLng point) {
try {
MapboxGeocoding client = new MapboxGeocoding.Builder()
.setAccessToken(getString(R.string.mapbox_access_token))
.setCoordinates(Position.fromCoordinates(point.getLongitude(), point.getLatitude()))
.setGeocodingType(GeocodingCriteria.TYPE_POI)
.build();
client.enqueueCall(new Callback<GeocodingResponse>() {
@Override
public void onResponse(Call<GeocodingResponse> call, Response<GeocodingResponse> response) {
List<CarmenFeature> results = response.body().getFeatures();
if (results.size() > 0) {
String placeName = results.get(0).getPlaceName();
setSuccess(placeName);
} else {
setMessage("No results.");
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
textView = (TextView) findViewById(R.id.message);
setMessage(getString(R.string.geocoder_instructions));
mapView = (MapView) findViewById(R.id.mapView);
mapView.setStyleUrl(Style.MAPBOX_STREETS);
mapView.onCreate(savedInstanceState);
dropPinView = new ImageView(this);
dropPinView.setImageResource(R.drawable.ic_droppin_24dp);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
dropPinView.setLayoutParams(params);
mapView.addView(dropPinView);
mapView.getMapAsync(this);
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
final Projection projection = mapboxMap.getProjection();
final int width = mapView.getMeasuredWidth();
final int height = mapView.getMeasuredHeight();
// Click listener
mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() {
@Override
public void onMapClick(@NonNull LatLng point) {
PointF centerPoint = new PointF(width / 2, (height + dropPinView.getHeight()) / 2);
LatLng centerLatLng = new LatLng(projection.fromScreenLocation(centerPoint));
setMessage("Geocoding...");
mapboxMap.removeAnnotations();
mapboxMap.addMarker(new MarkerOptions().position(centerLatLng));
geocode(centerLatLng);
}
});
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
/*
* Forward geocoding
*/
private void geocode(final LatLng point) {
try {
MapboxGeocoding client = new MapboxGeocoding.Builder()
.setAccessToken(getString(R.string.mapbox_access_token))
.setCoordinates(Position.fromCoordinates(point.getLongitude(), point.getLatitude()))
.setGeocodingType(GeocodingCriteria.TYPE_POI)
.build();
client.enqueueCall(new Callback<GeocodingResponse>() {
@Override
public void onResponse(Call<GeocodingResponse> call, Response<GeocodingResponse> response) {
List<CarmenFeature> results = response.body().getFeatures();
if (results.size() > 0) {
String placeName = results.get(0).getPlaceName();
setSuccess(placeName);
} else {
setMessage("No results.");
}
}
@Override
public void onFailure(Call<GeocodingResponse> call, Throwable throwable) {
setError(throwable.getMessage());
}
});
} catch (ServicesException servicesException) {
Timber.e("Error geocoding: " + servicesException.toString());
servicesException.printStackTrace();
setError(servicesException.getMessage());
@Override
public void onFailure(Call<GeocodingResponse> call, Throwable throwable) {
setError(throwable.getMessage());
}
});
} catch (ServicesException servicesException) {
Timber.e("Error geocoding: " + servicesException.toString());
servicesException.printStackTrace();
setError(servicesException.getMessage());
}
}
/*
* Update text view
*/
/*
* Update text view
*/
private void setMessage(String message) {
Timber.d("Message: " + message);
textView.setText(message);
}
private void setSuccess(String placeName) {
Timber.d("Place name: " + placeName);
textView.setText(placeName);
}
private void setError(String message) {
Timber.e("Error: " + message);
textView.setText("Error: " + message);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
private void setMessage(String message) {
Timber.d("Message: " + message);
textView.setText(message);
}
private void setSuccess(String placeName) {
Timber.d("Place name: " + placeName);
textView.setText(placeName);
}
private void setError(String message) {
Timber.e("Error: " + message);
textView.setText("Error: " + message);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -17,103 +17,103 @@ import com.mapbox.mapboxsdk.testapp.R;
public class PrintActivity extends AppCompatActivity implements MapboxMap.SnapshotReadyCallback {
private MapView mapView;
private MapboxMap mapboxMap;
private MapView mapView;
private MapboxMap mapboxMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_print);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_print);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
PrintActivity.this.mapboxMap = mapboxMap;
}
});
final View fab = findViewById(R.id.fab);
if (fab != null) {
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mapboxMap != null) {
mapboxMap.snapshot(PrintActivity.this);
}
}
});
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
PrintActivity.this.mapboxMap = mapboxMap;
}
});
final View fab = findViewById(R.id.fab);
if (fab != null) {
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mapboxMap != null) {
mapboxMap.snapshot(PrintActivity.this);
}
}
});
}
}
@Override
public void onSnapshotReady(Bitmap snapshot) {
PrintHelper photoPrinter = new PrintHelper(this);
photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);
photoPrinter.printBitmap("map.jpg - mapbox print job", snapshot);
}
@Override
public void onSnapshotReady(Bitmap snapshot) {
PrintHelper photoPrinter = new PrintHelper(this);
photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);
photoPrinter.printBitmap("map.jpg - mapbox print job", snapshot);
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -20,107 +20,107 @@ import com.mapbox.mapboxsdk.testapp.R;
public class SnapshotActivity extends AppCompatActivity implements OnMapReadyCallback, View.OnClickListener {
private MapView mapView;
private MapboxMap mapboxMap;
private MapView mapView;
private MapboxMap mapboxMap;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snapshot);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snapshot);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
mapboxMap.setStyleUrl(Style.OUTDOORS);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
if (fab != null) {
fab.setColorFilter(ContextCompat.getColor(SnapshotActivity.this, R.color.primary));
fab.setOnClickListener(this);
}
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
@Override
public void onClick(View view) {
final long startTime = System.nanoTime();
mapboxMap.snapshot(new MapboxMap.SnapshotReadyCallback() {
@Override
public void onSnapshotReady(Bitmap snapshot) {
long endTime = System.nanoTime();
long duration = (long) ((endTime - startTime) / 1e6);
ImageView snapshotView = (ImageView) findViewById(R.id.imageView);
snapshotView.setImageBitmap(snapshot);
Toast.makeText(
SnapshotActivity.this,
String.format("Snapshot taken in %d ms", duration),
Toast.LENGTH_LONG).show();
}
});
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
mapboxMap.setStyleUrl(Style.OUTDOORS);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
if (fab != null) {
fab.setColorFilter(ContextCompat.getColor(SnapshotActivity.this, R.color.primary));
fab.setOnClickListener(this);
}
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
public void onClick(View view) {
final long startTime = System.nanoTime();
mapboxMap.snapshot(new MapboxMap.SnapshotReadyCallback() {
@Override
public void onSnapshotReady(Bitmap snapshot) {
long endTime = System.nanoTime();
long duration = (long) ((endTime - startTime) / 1e6);
ImageView snapshotView = (ImageView) findViewById(R.id.imageView);
snapshotView.setImageBitmap(snapshot);
Toast.makeText(
SnapshotActivity.this,
String.format("Snapshot taken in %d ms", duration),
Toast.LENGTH_LONG).show();
}
});
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -31,154 +31,157 @@ import com.mapbox.mapboxsdk.testapp.R;
*/
public class DynamicInfoWindowAdapterActivity extends AppCompatActivity implements OnMapReadyCallback {
private MapboxMap mapboxMap;
private MapView mapView;
private MapboxMap mapboxMap;
private MapView mapView;
private LatLng paris = new LatLng(48.864716, 2.349014);
private LatLng paris = new LatLng(48.864716, 2.349014);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_infowindow_adapter);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_infowindow_adapter);
setupActionBar();
setupActionBar();
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
@Override
public void onMapReady(MapboxMap map) {
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
mapboxMap = map;
//Add info window adapter
addCustomInfoWindowAdapter(mapboxMap);
//Add info window adapter
addCustomInfoWindowAdapter(mapboxMap);
//Keep info windows open on click
mapboxMap.getUiSettings().setDeselectMarkersOnTap(false);
//Keep info windows open on click
mapboxMap.getUiSettings().setDeselectMarkersOnTap(false);
//Add a marker
final MarkerView marker = addMarker(mapboxMap);
mapboxMap.selectMarker(marker);
//Add a marker
final MarkerView marker = addMarker(mapboxMap);
mapboxMap.selectMarker(marker);
//On map click, change the info window contents
mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() {
@Override
public void onMapClick(@NonNull LatLng point) {
//Distance from click to marker
double distanceKm = marker.getPosition().distanceTo(point) / 1000;
//On map click, change the info window contents
mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() {
@Override
public void onMapClick(@NonNull LatLng point) {
//Distance from click to marker
double distanceKm = marker.getPosition().distanceTo(point) / 1000;
//Get the info window
InfoWindow infoWindow = marker.getInfoWindow();
//Get the info window
InfoWindow infoWindow = marker.getInfoWindow();
//Get the view from the info window
if (infoWindow != null && infoWindow.getView() != null) {
//Set the new text on the text view in the info window
((TextView) infoWindow.getView()).setText(String.format("%.2fkm", distanceKm));
//Get the view from the info window
if (infoWindow != null && infoWindow.getView() != null) {
//Set the new text on the text view in the info window
((TextView) infoWindow.getView()).setText(String.format("%.2fkm", distanceKm));
//Update the info window position (as the text length changes)
infoWindow.update();
}
}
});
//Focus on Paris
mapboxMap.animateCamera(CameraUpdateFactory.newLatLng(paris));
}
private MarkerView addMarker(MapboxMap mapboxMap) {
IconFactory iconFactory = IconFactory.getInstance(this);
Drawable iconDrawable = ContextCompat.getDrawable(this, R.drawable.ic_location_city_24dp);
iconDrawable.setColorFilter(getResources().getColor(R.color.mapbox_blue), PorterDuff.Mode.SRC_IN);
return mapboxMap.addMarker(
new MarkerViewOptions()
.position(paris)
.icon(iconFactory.fromDrawable(iconDrawable))
);
}
private void addCustomInfoWindowAdapter(final MapboxMap mapboxMap) {
final int padding = (int) getResources().getDimension(R.dimen.attr_margin);
mapboxMap.setInfoWindowAdapter(new MapboxMap.InfoWindowAdapter() {
@Nullable
@Override
public View getInfoWindow(@NonNull Marker marker) {
TextView textView = new TextView(DynamicInfoWindowAdapterActivity.this);
textView.setText(marker.getTitle());
textView.setBackgroundColor(Color.WHITE);
textView.setText("Click the map to calculate the distance");
textView.setPadding(padding, padding, padding, padding);
return textView;
}
});
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
//Update the info window position (as the text length changes)
infoWindow.update();
}
}
}
});
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Focus on Paris
mapboxMap.animateCamera(CameraUpdateFactory.newLatLng(paris));
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
private MarkerView addMarker(MapboxMap mapboxMap) {
IconFactory iconFactory = IconFactory.getInstance(this);
Drawable iconDrawable = ContextCompat.getDrawable(this, R.drawable.ic_location_city_24dp);
iconDrawable.setColorFilter(
ContextCompat.getColor(DynamicInfoWindowAdapterActivity.this, R.color.mapbox_blue),
PorterDuff.Mode.SRC_IN
);
return mapboxMap.addMarker(
new MarkerViewOptions()
.position(paris)
.icon(iconFactory.fromDrawable(iconDrawable))
);
}
private void addCustomInfoWindowAdapter(final MapboxMap mapboxMap) {
final int padding = (int) getResources().getDimension(R.dimen.attr_margin);
mapboxMap.setInfoWindowAdapter(new MapboxMap.InfoWindowAdapter() {
@Nullable
@Override
public View getInfoWindow(@NonNull Marker marker) {
TextView textView = new TextView(DynamicInfoWindowAdapterActivity.this);
textView.setText(marker.getTitle());
textView.setBackgroundColor(Color.WHITE);
textView.setText("Click the map to calculate the distance");
textView.setPadding(padding, padding, padding, padding);
return textView;
}
});
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
}
}

View File

@@ -8,6 +8,7 @@ import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
@@ -15,182 +16,183 @@ import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.testapp.R;
import com.mapbox.mapboxsdk.maps.MapView;
import java.text.DecimalFormat;
public class InfoWindowActivity extends AppCompatActivity
implements OnMapReadyCallback, MapboxMap.OnInfoWindowCloseListener, MapboxMap.OnMapLongClickListener,
MapboxMap.OnInfoWindowClickListener, MapboxMap.OnInfoWindowLongClickListener {
implements OnMapReadyCallback, MapboxMap.OnInfoWindowCloseListener, MapboxMap.OnMapLongClickListener,
MapboxMap.OnInfoWindowClickListener, MapboxMap.OnInfoWindowLongClickListener {
private MapboxMap mapboxMap;
private MapView mapView;
private Marker customMarker;
private MapboxMap mapboxMap;
private MapView mapView;
private Marker customMarker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_infowindow);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_infowindow);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
addMarkers();
addInfoWindowListeners();
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
addMarkers();
addInfoWindowListeners();
}
private void addMarkers() {
mapboxMap.addMarker(new MarkerOptions()
.title("Intersection")
.snippet("H St NW with 15th St NW")
.position(new LatLng(38.9002073, -77.03364419)));
mapboxMap.addMarker(new MarkerOptions().title("Intersection")
.snippet("E St NW with 17th St NW")
.position(new LatLng(38.8954236, -77.0394623)));
mapboxMap.addMarker(new MarkerOptions().title("The Ellipse").position(new LatLng(38.89393, -77.03654)));
mapboxMap.addMarker(new MarkerOptions().position(new LatLng(38.89596, -77.03434)));
mapboxMap.addMarker(new MarkerOptions().snippet("Lafayette Square").position(new LatLng(38.89949, -77.03656)));
Marker marker = mapboxMap.addMarker(new MarkerOptions()
.title("White House")
.snippet("The official residence and principal workplace of the President of the United States, "
+ "located at 1600 Pennsylvania Avenue NW in Washington, D.C. It has been the residence of every"
+ "U.S. president since John Adams in 1800.")
.position(new LatLng(38.897705003219784, -77.03655168667463)));
// open InfoWindow at startup
mapboxMap.selectMarker(marker);
}
private void addInfoWindowListeners() {
mapboxMap.setOnInfoWindowCloseListener(this);
mapboxMap.setOnMapLongClickListener(this);
mapboxMap.setOnInfoWindowClickListener(this);
mapboxMap.setOnInfoWindowLongClickListener(this);
}
private void toggleConcurrentInfoWindow(boolean allowConcurrentInfoWindow) {
mapboxMap.deselectMarkers();
mapboxMap.setAllowConcurrentMultipleOpenInfoWindows(allowConcurrentInfoWindow);
}
private void toggleDeselectMarkersOnTap(boolean deselectMarkersOnTap) {
mapboxMap.getUiSettings().setDeselectMarkersOnTap(deselectMarkersOnTap);
}
@Override
public boolean onInfoWindowClick(@NonNull Marker marker) {
Toast.makeText(getApplicationContext(), "OnClick: " + marker.getTitle(), Toast.LENGTH_LONG).show();
// returning true will leave the info window open
return false;
}
@Override
public void onInfoWindowClose(Marker marker) {
Toast.makeText(getApplicationContext(), "OnClose: " + marker.getTitle(), Toast.LENGTH_LONG).show();
}
@Override
public void onInfoWindowLongClick(Marker marker) {
Toast.makeText(getApplicationContext(), "OnLongClick: " + marker.getTitle(), Toast.LENGTH_LONG).show();
}
@Override
public void onMapLongClick(@NonNull LatLng point) {
if (customMarker != null) {
// Remove previous added marker
mapboxMap.removeAnnotation(customMarker);
customMarker = null;
}
private void addMarkers() {
mapboxMap.addMarker(new MarkerOptions()
.title("Intersection")
.snippet("H St NW with 15th St NW")
.position(new LatLng(38.9002073, -77.03364419)));
// Add marker on long click location with default marker image
customMarker = mapboxMap.addMarker(new MarkerOptions()
.title("Custom Marker")
.snippet(new DecimalFormat("#.#####").format(point.getLatitude()) + ", "
+ new DecimalFormat("#.#####").format(point.getLongitude()))
.position(point));
}
mapboxMap.addMarker(new MarkerOptions().title("Intersection")
.snippet("E St NW with 17th St NW")
.position(new LatLng(38.8954236, -77.0394623)));
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
mapboxMap.addMarker(new MarkerOptions().title("The Ellipse").position(new LatLng(38.89393, -77.03654)));
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
mapboxMap.addMarker(new MarkerOptions().position(new LatLng(38.89596, -77.03434)));
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
mapboxMap.addMarker(new MarkerOptions().snippet("Lafayette Square").position(new LatLng(38.89949, -77.03656)));
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
Marker marker = mapboxMap.addMarker(new MarkerOptions()
.title("White House")
.snippet("The official residence and principal workplace of the President of the United States, "
+ "located at 1600 Pennsylvania Avenue NW in Washington, D.C. It has been the residence of every"
+ "U.S. president since John Adams in 1800.")
.position(new LatLng(38.897705003219784, -77.03655168667463)));
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
// open InfoWindow at startup
mapboxMap.selectMarker(marker);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
private void addInfoWindowListeners() {
mapboxMap.setOnInfoWindowCloseListener(this);
mapboxMap.setOnMapLongClickListener(this);
mapboxMap.setOnInfoWindowClickListener(this);
mapboxMap.setOnInfoWindowLongClickListener(this);
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
private void toggleConcurrentInfoWindow(boolean allowConcurrentInfoWindow) {
mapboxMap.deselectMarkers();
mapboxMap.setAllowConcurrentMultipleOpenInfoWindows(allowConcurrentInfoWindow);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_infowindow, menu);
return true;
}
private void toggleDeselectMarkersOnTap(boolean deselectMarkersOnTap) {
mapboxMap.getUiSettings().setDeselectMarkersOnTap(deselectMarkersOnTap);
}
@Override
public boolean onInfoWindowClick(@NonNull Marker marker) {
Toast.makeText(getApplicationContext(), "OnClick: " + marker.getTitle(), Toast.LENGTH_LONG).show();
// returning true will leave the info window open
return false;
}
@Override
public void onInfoWindowClose(Marker marker) {
Toast.makeText(getApplicationContext(), "OnClose: " + marker.getTitle(), Toast.LENGTH_LONG).show();
}
@Override
public void onInfoWindowLongClick(Marker marker) {
Toast.makeText(getApplicationContext(), "OnLongClick: " + marker.getTitle(), Toast.LENGTH_LONG).show();
}
@Override
public void onMapLongClick(@NonNull LatLng point) {
if (customMarker != null) {
// Remove previous added marker
mapboxMap.removeAnnotation(customMarker);
customMarker = null;
}
// Add marker on long click location with default marker image
customMarker = mapboxMap.addMarker(new MarkerOptions()
.title("Custom Marker")
.snippet(new DecimalFormat("#.#####").format(point.getLatitude()) + ", "
+ new DecimalFormat("#.#####").format(point.getLongitude()))
.position(point));
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_infowindow, menu);
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_toggle_concurrent_infowindow:
toggleConcurrentInfoWindow(!item.isChecked());
item.setChecked(!item.isChecked());
return true;
case R.id.action_toggle_deselect_markers_on_tap:
toggleDeselectMarkersOnTap(!item.isChecked());
item.setChecked(!item.isChecked());
return true;
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_toggle_concurrent_infowindow:
toggleConcurrentInfoWindow(!item.isChecked());
item.setChecked(!item.isChecked());
return true;
case R.id.action_toggle_deselect_markers_on_tap:
toggleDeselectMarkersOnTap(!item.isChecked());
item.setChecked(!item.isChecked());
return true;
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
}

View File

@@ -26,133 +26,133 @@ import com.mapbox.mapboxsdk.testapp.model.annotations.CityStateMarkerOptions;
public class InfoWindowAdapterActivity extends AppCompatActivity {
private MapView mapView;
private MapboxMap mapboxMap;
private IconFactory iconFactory;
private Drawable iconDrawable;
private MapView mapView;
private MapboxMap mapboxMap;
private IconFactory iconFactory;
private Drawable iconDrawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_infowindow_adapter);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_infowindow_adapter);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
iconFactory = IconFactory.getInstance(this);
iconDrawable = ContextCompat.getDrawable(this, R.drawable.ic_location_city_24dp);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap map) {
mapboxMap = map;
addMarkers();
addCustomInfoWindowAdapter();
}
});
}
private void addMarkers() {
mapboxMap.addMarker(generateCityStateMarker("Andorra", 42.505777, 1.52529, "#F44336"));
mapboxMap.addMarker(generateCityStateMarker("Luxembourg", 49.815273, 6.129583, "#3F51B5"));
mapboxMap.addMarker(generateCityStateMarker("Monaco", 43.738418, 7.424616, "#673AB7"));
mapboxMap.addMarker(generateCityStateMarker("Vatican City", 41.902916, 12.453389, "#009688"));
mapboxMap.addMarker(generateCityStateMarker("San Marino", 43.942360, 12.457777, "#795548"));
mapboxMap.addMarker(generateCityStateMarker("Liechtenstein", 47.166000, 9.555373, "#FF5722"));
}
private CityStateMarkerOptions generateCityStateMarker(String title, double lat, double lng, String color) {
CityStateMarkerOptions marker = new CityStateMarkerOptions();
marker.title(title);
marker.position(new LatLng(lat, lng));
marker.infoWindowBackground(color);
iconDrawable.setColorFilter(Color.parseColor(color), PorterDuff.Mode.SRC_IN);
Icon icon = iconFactory.fromDrawable(iconDrawable);
marker.icon(icon);
return marker;
}
private void addCustomInfoWindowAdapter() {
mapboxMap.setInfoWindowAdapter(new MapboxMap.InfoWindowAdapter() {
private int tenDp = (int) getResources().getDimension(R.dimen.attr_margin);
@Override
public View getInfoWindow(@NonNull Marker marker) {
TextView textView = new TextView(InfoWindowAdapterActivity.this);
textView.setText(marker.getTitle());
textView.setTextColor(Color.WHITE);
if (marker instanceof CityStateMarker) {
CityStateMarker cityStateMarker = (CityStateMarker) marker;
textView.setBackgroundColor(Color.parseColor(cityStateMarker.getInfoWindowBackgroundColor()));
}
iconFactory = IconFactory.getInstance(this);
iconDrawable = ContextCompat.getDrawable(this, R.drawable.ic_location_city_24dp);
textView.setPadding(tenDp, tenDp, tenDp, tenDp);
return textView;
}
});
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap map) {
mapboxMap = map;
addMarkers();
addCustomInfoWindowAdapter();
}
});
}
private void addMarkers() {
mapboxMap.addMarker(generateCityStateMarker("Andorra", 42.505777, 1.52529, "#F44336"));
mapboxMap.addMarker(generateCityStateMarker("Luxembourg", 49.815273, 6.129583, "#3F51B5"));
mapboxMap.addMarker(generateCityStateMarker("Monaco", 43.738418, 7.424616, "#673AB7"));
mapboxMap.addMarker(generateCityStateMarker("Vatican City", 41.902916, 12.453389, "#009688"));
mapboxMap.addMarker(generateCityStateMarker("San Marino", 43.942360, 12.457777, "#795548"));
mapboxMap.addMarker(generateCityStateMarker("Liechtenstein", 47.166000, 9.555373, "#FF5722"));
}
private CityStateMarkerOptions generateCityStateMarker(String title, double lat, double lng, String color) {
CityStateMarkerOptions marker = new CityStateMarkerOptions();
marker.title(title);
marker.position(new LatLng(lat, lng));
marker.infoWindowBackground(color);
iconDrawable.setColorFilter(Color.parseColor(color), PorterDuff.Mode.SRC_IN);
Icon icon = iconFactory.fromDrawable(iconDrawable);
marker.icon(icon);
return marker;
}
private void addCustomInfoWindowAdapter() {
mapboxMap.setInfoWindowAdapter(new MapboxMap.InfoWindowAdapter() {
private int tenDp = (int) getResources().getDimension(R.dimen.attr_margin);
@Override
public View getInfoWindow(@NonNull Marker marker) {
TextView textView = new TextView(InfoWindowAdapterActivity.this);
textView.setText(marker.getTitle());
textView.setTextColor(Color.WHITE);
if (marker instanceof CityStateMarker) {
CityStateMarker cityStateMarker = (CityStateMarker) marker;
textView.setBackgroundColor(Color.parseColor(cityStateMarker.getInfoWindowBackgroundColor()));
}
textView.setPadding(tenDp, tenDp, tenDp, tenDp);
return textView;
}
});
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -6,7 +6,9 @@ import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.MenuItem;
import android.view.View;
@@ -18,123 +20,123 @@ import com.mapbox.mapboxsdk.testapp.R;
public class DebugModeActivity extends AppCompatActivity {
private MapView mapView;
private MapboxMap mapboxMap;
private MapView mapView;
private MapboxMap mapboxMap;
private int currentStyleIndex = 0;
private int currentStyleIndex = 0;
private static final String[] STYLES = new String[]{
Style.MAPBOX_STREETS,
Style.OUTDOORS,
Style.LIGHT,
Style.DARK,
Style.SATELLITE,
Style.SATELLITE_STREETS
};
private static final String[] STYLES = new String[] {
Style.MAPBOX_STREETS,
Style.OUTDOORS,
Style.LIGHT,
Style.DARK,
Style.SATELLITE,
Style.SATELLITE_STREETS
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_debug_mode);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_debug_mode);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.setTag(true);
mapView.setStyleUrl(STYLES[currentStyleIndex]);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap map) {
mapboxMap = map;
}
});
FloatingActionButton fabDebug = (FloatingActionButton) findViewById(R.id.fabDebug);
fabDebug.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mapboxMap != null) {
Timber.d("Debug FAB: isDebug Active? " + mapboxMap.isDebugActive());
mapboxMap.cycleDebugOptions();
}
}
});
mapView = (MapView) findViewById(R.id.mapView);
mapView.setTag(true);
mapView.setStyleUrl(STYLES[currentStyleIndex]);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap map) {
mapboxMap = map;
}
});
FloatingActionButton fabDebug = (FloatingActionButton) findViewById(R.id.fabDebug);
fabDebug.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mapboxMap != null) {
Timber.d("Debug FAB: isDebug Active? " + mapboxMap.isDebugActive());
mapboxMap.cycleDebugOptions();
}
}
});
FloatingActionButton fabStyles = (FloatingActionButton) findViewById(R.id.fabStyles);
fabStyles.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mapboxMap != null) {
currentStyleIndex++;
if (currentStyleIndex == STYLES.length) {
currentStyleIndex = 0;
}
mapboxMap.setStyleUrl(STYLES[currentStyleIndex]);
}
}
});
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
FloatingActionButton fabStyles = (FloatingActionButton) findViewById(R.id.fabStyles);
fabStyles.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mapboxMap != null) {
currentStyleIndex++;
if (currentStyleIndex == STYLES.length) {
currentStyleIndex = 0;
}
mapboxMap.setStyleUrl(STYLES[currentStyleIndex]);
}
}
});
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -28,165 +28,165 @@ import com.mapbox.mapboxsdk.testapp.R;
public class DoubleMapActivity extends AppCompatActivity {
private static final String TAG_FRAGMENT = "map";
private static final String TAG_FRAGMENT = "map";
// used for ui tests
private MapboxMap mapboxMap;
// used for ui tests
private MapboxMap mapboxMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_fragment);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_fragment);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
Fragment mapFragment;
if (savedInstanceState == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_container, mapFragment = new DoubleMapFragment(), TAG_FRAGMENT);
transaction.commit();
} else {
mapFragment = (DoubleMapFragment) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
public void setMapboxMap(MapboxMap map) {
// we need to set mapboxmap on the parent activity,
// for auto-generated ui tests
Fragment mapFragment;
if (savedInstanceState == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_container, mapFragment = new DoubleMapFragment(), TAG_FRAGMENT);
transaction.commit();
} else {
mapFragment = (DoubleMapFragment) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
}
}
mapboxMap = map;
mapboxMap.setStyleUrl(Style.DARK);
mapboxMap.moveCamera(CameraUpdateFactory.zoomTo(18));
try {
public void setMapboxMap(MapboxMap map) {
// we need to set mapboxmap on the parent activity,
// for auto-generated ui tests
mapboxMap = map;
mapboxMap.setStyleUrl(Style.DARK);
mapboxMap.moveCamera(CameraUpdateFactory.zoomTo(18));
try {
TrackingSettings settings = mapboxMap.getTrackingSettings();
settings.setMyLocationTrackingMode(MyLocationTracking.TRACKING_FOLLOW);
} catch (SecurityException securityException) {
// permission is handled in MainActivity
finish();
}
}
public static class DoubleMapFragment extends Fragment {
private DoubleMapActivity activity;
private MapView mapView;
private MapView mapViewMini;
@Override
public void onAttach(Context context) {
super.onAttach(context);
activity = (DoubleMapActivity) context;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_double_map, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// MapView large
mapView = (MapView) view.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
if (activity != null) {
activity.setMapboxMap(mapboxMap);
}
}
});
// MapView mini
mapViewMini = (MapView) view.findViewById(R.id.mini_map);
mapViewMini.onCreate(savedInstanceState);
mapViewMini.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
mapboxMap.setStyleUrl(Style.LIGHT);
mapboxMap.moveCamera(CameraUpdateFactory.zoomTo(4));
UiSettings uiSettings = mapboxMap.getUiSettings();
uiSettings.setAllGesturesEnabled(false);
uiSettings.setCompassEnabled(false);
uiSettings.setAttributionEnabled(false);
uiSettings.setLogoEnabled(false);
try {
TrackingSettings settings = mapboxMap.getTrackingSettings();
settings.setMyLocationTrackingMode(MyLocationTracking.TRACKING_FOLLOW);
} catch (SecurityException securityException) {
} catch (SecurityException securityException) {
// permission is handled in MainActivity
finish();
getActivity().finish();
}
mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() {
@Override
public void onMapClick(@NonNull LatLng point) {
// test if we can open 2 activities after each other
startActivity(new Intent(mapViewMini.getContext(), DoubleMapActivity.class));
}
});
}
}
});
public static class DoubleMapFragment extends Fragment {
private DoubleMapActivity activity;
private MapView mapView;
private MapView mapViewMini;
@Override
public void onAttach(Context context) {
super.onAttach(context);
activity = (DoubleMapActivity) context;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_double_map, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// MapView large
mapView = (MapView) view.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
if (activity != null) {
activity.setMapboxMap(mapboxMap);
}
}
});
// MapView mini
mapViewMini = (MapView) view.findViewById(R.id.mini_map);
mapViewMini.onCreate(savedInstanceState);
mapViewMini.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
mapboxMap.setStyleUrl(Style.LIGHT);
mapboxMap.moveCamera(CameraUpdateFactory.zoomTo(4));
UiSettings uiSettings = mapboxMap.getUiSettings();
uiSettings.setAllGesturesEnabled(false);
uiSettings.setCompassEnabled(false);
uiSettings.setAttributionEnabled(false);
uiSettings.setLogoEnabled(false);
try {
TrackingSettings settings = mapboxMap.getTrackingSettings();
settings.setMyLocationTrackingMode(MyLocationTracking.TRACKING_FOLLOW);
} catch (SecurityException securityException) {
// permission is handled in MainActivity
getActivity().finish();
}
mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() {
@Override
public void onMapClick(@NonNull LatLng point) {
// test if we can open 2 activities after each other
startActivity(new Intent(mapViewMini.getContext(), DoubleMapActivity.class));
}
});
}
});
SurfaceView surfaceViewMini = (SurfaceView) mapViewMini.findViewById(R.id.surfaceView);
surfaceViewMini.setZOrderMediaOverlay(true);
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
mapViewMini.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
mapViewMini.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
mapViewMini.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
mapViewMini.onLowMemory();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
mapViewMini.onSaveInstanceState(outState);
}
SurfaceView surfaceViewMini = (SurfaceView) mapViewMini.findViewById(R.id.surfaceView);
surfaceViewMini.setZOrderMediaOverlay(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
public void onResume() {
super.onResume();
mapView.onResume();
mapViewMini.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
mapViewMini.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
mapViewMini.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
mapViewMini.onLowMemory();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
mapViewMini.onSaveInstanceState(outState);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -14,115 +14,114 @@ import android.view.ViewGroup;
import android.widget.Button;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.testapp.R;
public class MapInDialogActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_in_dialog);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_in_dialog);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
Button button = (Button) findViewById(R.id.button_open_dialog);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentManager fm = getSupportFragmentManager();
MapDialogFragment editNameDialogFragment = MapDialogFragment.newInstance("Map Dialog");
editNameDialogFragment.show(fm, "fragment_dialog_map");
}
});
Button button = (Button) findViewById(R.id.button_open_dialog);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentManager fm = getSupportFragmentManager();
MapDialogFragment editNameDialogFragment = MapDialogFragment.newInstance("Map Dialog");
editNameDialogFragment.show(fm, "fragment_dialog_map");
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public static class MapDialogFragment extends DialogFragment {
private MapView mapView;
public MapDialogFragment() {
}
public static MapDialogFragment newInstance(String title) {
MapDialogFragment frag = new MapDialogFragment();
Bundle args = new Bundle();
args.putString("title", title);
frag.setArguments(args);
return frag;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_dialog_map, container);
}
public static class MapDialogFragment extends DialogFragment {
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
private MapView mapView;
public MapDialogFragment() {}
public static MapDialogFragment newInstance(String title) {
MapDialogFragment frag = new MapDialogFragment();
Bundle args = new Bundle();
args.putString("title", title);
frag.setArguments(args);
return frag;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_dialog_map, container);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mapView = (MapView) view.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
}
@Override
public void onStart() {
super.onStart();
mapView.onStart();
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onStop() {
super.onStop();
mapView.onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
mapView = (MapView) view.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
}
@Override
public void onStart() {
super.onStart();
mapView.onStart();
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onStop() {
super.onStop();
mapView.onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
}

View File

@@ -21,143 +21,143 @@ import com.mapbox.mapboxsdk.testapp.R;
public class MapPaddingActivity extends AppCompatActivity {
private MapView mapView;
private MapboxMap mapboxMap;
private MapView mapView;
private MapboxMap mapboxMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_padding);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_padding);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.setTag(true);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
MapPaddingActivity.this.mapboxMap = mapboxMap;
int paddingLeft = (int) getResources().getDimension(R.dimen.map_padding_left);
int paddingBottom = (int) getResources().getDimension(R.dimen.map_padding_bottom);
int paddingRight = (int) getResources().getDimension(R.dimen.map_padding_right);
mapboxMap.setPadding(paddingLeft, toolbar.getHeight(), paddingRight, paddingBottom);
moveToBangalore();
}
});
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.setTag(true);
mapView.onCreate(savedInstanceState);
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
MapPaddingActivity.this.mapboxMap = mapboxMap;
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
int paddingLeft = (int) getResources().getDimension(R.dimen.map_padding_left);
int paddingBottom = (int) getResources().getDimension(R.dimen.map_padding_bottom);
int paddingRight = (int) getResources().getDimension(R.dimen.map_padding_right);
mapboxMap.setPadding(paddingLeft, toolbar.getHeight(), paddingRight, paddingBottom);
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
moveToBangalore();
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_padding, menu);
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_padding, menu);
return true;
}
private void toggleGps(boolean enable) {
try {
// Enable user location
mapboxMap.setMyLocationEnabled(enable);
TrackingSettings trackingSettings = mapboxMap.getTrackingSettings();
trackingSettings.setDismissLocationTrackingOnGesture(false);
trackingSettings.setMyLocationTrackingMode(
enable ? MyLocationTracking.TRACKING_FOLLOW : MyLocationTracking.TRACKING_NONE);
} catch (SecurityException securityException) {
// permission not granted is handled in FeatureOverviewActivity
finish();
}
}
private void moveToBangalore() {
toggleGps(false);
LatLng bangalore = new LatLng(12.9810816, 77.6368034);
CameraPosition cameraPosition = new CameraPosition.Builder()
.zoom(16)
.target(bangalore)
.bearing(40)
.tilt(45)
.build();
mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mapboxMap.addMarker(new MarkerOptions().title("Center map").position(bangalore));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
private void toggleGps(boolean enable) {
try {
// Enable user location
mapboxMap.setMyLocationEnabled(enable);
TrackingSettings trackingSettings = mapboxMap.getTrackingSettings();
trackingSettings.setDismissTrackingOnGesture(false);
trackingSettings.setMyLocationTrackingMode(
enable ? MyLocationTracking.TRACKING_FOLLOW : MyLocationTracking.TRACKING_NONE);
} catch (SecurityException securityException) {
// permission not granted is handled in FeatureOverviewActivity
finish();
case R.id.action_user_tracking:
if (mapboxMap != null) {
toggleGps(true);
}
}
return true;
private void moveToBangalore() {
toggleGps(false);
LatLng bangalore = new LatLng(12.9810816, 77.6368034);
CameraPosition cameraPosition = new CameraPosition.Builder()
.zoom(16)
.target(bangalore)
.bearing(40)
.tilt(45)
.build();
mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mapboxMap.addMarker(new MarkerOptions().title("Center map").position(bangalore));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.action_user_tracking:
if (mapboxMap != null) {
toggleGps(true);
}
return true;
case R.id.action_bangalore:
if (mapboxMap != null) {
moveToBangalore();
}
return true;
default:
return super.onOptionsItemSelected(item);
case R.id.action_bangalore:
if (mapboxMap != null) {
moveToBangalore();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -32,221 +32,221 @@ import com.mapbox.mapboxsdk.testapp.R;
public class NavigationDrawerActivity extends AppCompatActivity {
private boolean firstStyle = true;
private MapboxMap mapboxMap;
private boolean firstStyle = true;
private MapboxMap mapboxMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
NavigationDrawerFragment navigationDrawerFragment;
getFragmentManager()
.beginTransaction()
.add(R.id.navigation_drawer, navigationDrawerFragment = new NavigationDrawerFragment())
.commit();
navigationDrawerFragment.setUp(this,
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout),
getSupportActionBar());
}
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
switch (position) {
case 0:
// options
MapboxMapOptions options = new MapboxMapOptions();
options.styleUrl(firstStyle ? Style.LIGHT : Style.SATELLITE);
options.camera(new CameraPosition.Builder()
.target(new LatLng(39.913271, 116.413891))
.zoom(12)
.build());
// fragment
MapFragment mapFragment = MapFragment.newInstance(options);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, mapFragment)
.commit();
// get callback when map is ready
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
}
});
firstStyle = !firstStyle;
break;
case 1:
Snackbar.make(
findViewById(android.R.id.content),
"Hello from snackbar",
Snackbar.LENGTH_LONG)
.show();
break;
}
}
public static class NavigationDrawerFragment extends Fragment {
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private ActionBarDrawerToggle drawerToggle;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private View fragmentContainerView;
private int currentSelectedPosition = 0;
private boolean fromSavedInstanceState;
private boolean userLearnedDrawer;
public NavigationDrawerFragment() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
userLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
NavigationDrawerFragment navigationDrawerFragment;
getFragmentManager()
.beginTransaction()
.add(R.id.navigation_drawer, navigationDrawerFragment = new NavigationDrawerFragment())
.commit();
navigationDrawerFragment.setUp(this,
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout),
getSupportActionBar());
if (savedInstanceState != null) {
currentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
fromSavedInstanceState = true;
}
selectItem(currentSelectedPosition);
}
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
switch (position) {
case 0:
// options
MapboxMapOptions options = new MapboxMapOptions();
options.styleUrl(firstStyle ? Style.LIGHT : Style.SATELLITE);
options.camera(new CameraPosition.Builder()
.target(new LatLng(39.913271, 116.413891))
.zoom(12)
.build());
// fragment
MapFragment mapFragment = MapFragment.newInstance(options);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, mapFragment)
.commit();
// get callback when map is ready
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
}
});
firstStyle = !firstStyle;
break;
case 1:
Snackbar.make(
findViewById(android.R.id.content),
"Hello from snackbar",
Snackbar.LENGTH_LONG)
.show();
break;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
public static class NavigationDrawerFragment extends Fragment {
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private ActionBarDrawerToggle drawerToggle;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private View fragmentContainerView;
private int currentSelectedPosition = 0;
private boolean fromSavedInstanceState;
private boolean userLearnedDrawer;
public NavigationDrawerFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
drawerListView = (ListView) inflater.inflate(
R.layout.drawer_navigation_drawer, container, false);
drawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
userLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
currentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
fromSavedInstanceState = true;
}
selectItem(currentSelectedPosition);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
drawerListView = (ListView) inflater.inflate(
R.layout.drawer_navigation_drawer, container, false);
drawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
drawerListView.setAdapter(new ArrayAdapter<>(
inflater.getContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2)
}));
drawerListView.setItemChecked(currentSelectedPosition, true);
return drawerListView;
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* @param fragmentId The android:id of this fragment in its activity's layout.
* @param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(Activity activity, int fragmentId, DrawerLayout drawerLayout, ActionBar actionBar) {
fragmentContainerView = activity.findViewById(fragmentId);
this.drawerLayout = drawerLayout;
// drawerLayout.setScrimColor(Color.TRANSPARENT);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
drawerToggle = new ActionBarDrawerToggle(
activity,
NavigationDrawerFragment.this.drawerLayout,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().invalidateOptionsMenu();
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!userLearnedDrawer) {
userLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu();
}
};
if (!userLearnedDrawer && !fromSavedInstanceState) {
this.drawerLayout.openDrawer(fragmentContainerView);
}
this.drawerLayout.post(new Runnable() {
@Override
public void run() {
drawerToggle.syncState();
}
});
this.drawerLayout.setDrawerListener(drawerToggle);
}
private void selectItem(int position) {
currentSelectedPosition = position;
if (drawerListView != null) {
drawerListView.setItemChecked(position, true);
}
if (drawerLayout != null) {
drawerLayout.closeDrawer(fragmentContainerView);
}
Activity activity = getActivity();
if (activity != null && activity instanceof NavigationDrawerActivity) {
NavigationDrawerActivity navActivity = (NavigationDrawerActivity) activity;
navActivity.onNavigationDrawerItemSelected(position);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, currentSelectedPosition);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
drawerListView.setAdapter(new ArrayAdapter<>(
inflater.getContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[] {
getString(R.string.title_section1),
getString(R.string.title_section2)
}));
drawerListView.setItemChecked(currentSelectedPosition, true);
return drawerListView;
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* @param fragmentId The android:id of this fragment in its activity's layout.
* @param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(Activity activity, int fragmentId, DrawerLayout drawerLayout, ActionBar actionBar) {
fragmentContainerView = activity.findViewById(fragmentId);
this.drawerLayout = drawerLayout;
// drawerLayout.setScrimColor(Color.TRANSPARENT);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
drawerToggle = new ActionBarDrawerToggle(
activity,
NavigationDrawerFragment.this.drawerLayout,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().invalidateOptionsMenu();
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!userLearnedDrawer) {
userLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu();
}
};
if (!userLearnedDrawer && !fromSavedInstanceState) {
this.drawerLayout.openDrawer(fragmentContainerView);
}
this.drawerLayout.post(new Runnable() {
@Override
public void run() {
drawerToggle.syncState();
}
});
this.drawerLayout.setDrawerListener(drawerToggle);
}
private void selectItem(int position) {
currentSelectedPosition = position;
if (drawerListView != null) {
drawerListView.setItemChecked(position, true);
}
if (drawerLayout != null) {
drawerLayout.closeDrawer(fragmentContainerView);
}
Activity activity = getActivity();
if (activity != null && activity instanceof NavigationDrawerActivity) {
NavigationDrawerActivity navActivity = (NavigationDrawerActivity) activity;
navActivity.onNavigationDrawerItemSelected(position);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, currentSelectedPosition);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -1,92 +1,86 @@
package com.mapbox.mapboxsdk.testapp.activity.maplayout;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import com.mapbox.mapboxsdk.constants.Style;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.testapp.R;
public class SimpleMapActivity extends AppCompatActivity {
private MapView mapView;
private MapView mapView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_simple);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_simple);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -32,170 +32,170 @@ import com.mapbox.mapboxsdk.testapp.R;
public class CarDrivingActivity extends AppCompatActivity implements MapboxMap.OnMyLocationChangeListener {
private static final int PERMISSIONS_LOCATION = 0;
private static final int PERMISSIONS_LOCATION = 0;
private MapView mapView;
private MapboxMap mapboxMap;
private Location location;
private MapView mapView;
private MapboxMap mapboxMap;
private Location location;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_car_driving);
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_car_driving);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
CarDrivingActivity.this.mapboxMap = mapboxMap;
// view settings
MyLocationViewSettings settings = mapboxMap.getMyLocationViewSettings();
settings.setPadding(0, getWindow().getDecorView().getMeasuredHeight() / 3, 0, 0);
// get car
Drawable car = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_taxi_top_small, getTheme());
settings.setForegroundTintColor(Color.TRANSPARENT);
settings.setForegroundDrawable(car, car);
// remove accuracy circle
settings.setAccuracyAlpha(0);
// disable dismissal when a gesture occurs
TrackingSettings trackingSettings = mapboxMap.getTrackingSettings();
trackingSettings.setDismissLocationTrackingOnGesture(false);
trackingSettings.setDismissBearingTrackingOnGesture(false);
mapboxMap.setOnMyLocationChangeListener(CarDrivingActivity.this);
if (savedInstanceState == null) {
toggleGps(true);
}
}
});
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
@UiThread
public void toggleGps(boolean enableGps) {
if (enableGps) {
if ((ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
|| (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_LOCATION);
} else {
enableLocation(true);
}
} else {
enableLocation(false);
}
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
CarDrivingActivity.this.mapboxMap = mapboxMap;
private void enableLocation(boolean enabled) {
if (enabled) {
mapboxMap.setMyLocationEnabled(true);
Location location = mapboxMap.getMyLocation();
if (location != null) {
setInitialPosition(new LatLng(location));
}
} else {
mapboxMap.setMyLocationEnabled(false);
}
}
// view settings
MyLocationViewSettings settings = mapboxMap.getMyLocationViewSettings();
settings.setPadding(0, getWindow().getDecorView().getMeasuredHeight() / 3, 0, 0);
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSIONS_LOCATION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
enableLocation(true);
}
}
}
// get car
Drawable car = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_taxi_top_small, getTheme());
settings.setForegroundTintColor(Color.TRANSPARENT);
settings.setForegroundDrawable(car, car);
private void setInitialPosition(LatLng latLng) {
mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder().target(latLng).zoom(15).tilt(20f).build()));
mapboxMap.setMyLocationEnabled(true);
// remove accuracy circle
settings.setAccuracyAlpha(0);
// disable dismissal when a gesture occurs
TrackingSettings trackingSettings = mapboxMap.getTrackingSettings();
trackingSettings.setMyLocationTrackingMode(MyLocationTracking.TRACKING_FOLLOW);
trackingSettings.setMyBearingTrackingMode(MyBearingTracking.GPS);
}
trackingSettings.setDismissLocationTrackingOnGesture(false);
trackingSettings.setDismissBearingTrackingOnGesture(false);
@Override
public void onMyLocationChange(@Nullable Location location) {
if (location != null) {
if (this.location == null) {
// initial location to reposition map
setInitialPosition(new LatLng(location));
}
this.location = location;
mapboxMap.setOnMyLocationChangeListener(CarDrivingActivity.this);
if (savedInstanceState == null) {
toggleGps(true);
}
}
}
});
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
@UiThread
public void toggleGps(boolean enableGps) {
if (enableGps) {
if ((ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
|| (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_LOCATION);
} else {
enableLocation(true);
}
} else {
enableLocation(false);
}
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
private void enableLocation(boolean enabled) {
if (enabled) {
mapboxMap.setMyLocationEnabled(true);
Location location = mapboxMap.getMyLocation();
if (location != null) {
setInitialPosition(new LatLng(location));
}
} else {
mapboxMap.setMyLocationEnabled(false);
}
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSIONS_LOCATION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
enableLocation(true);
}
}
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
private void setInitialPosition(LatLng latLng) {
mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder().target(latLng).zoom(15).tilt(20f).build()));
mapboxMap.setMyLocationEnabled(true);
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
TrackingSettings trackingSettings = mapboxMap.getTrackingSettings();
trackingSettings.setMyLocationTrackingMode(MyLocationTracking.TRACKING_FOLLOW);
trackingSettings.setMyBearingTrackingMode(MyBearingTracking.GPS);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
@Override
public void onMyLocationChange(@Nullable Location location) {
if (location != null) {
if (this.location == null) {
// initial location to reposition map
setInitialPosition(new LatLng(location));
}
this.location = location;
}
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -14,7 +14,9 @@ import android.support.v4.app.ActivityCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
@@ -59,417 +61,417 @@ import retrofit2.Response;
* Sample Activity to show a typical location picker use case
*/
public class LocationPickerActivity extends AppCompatActivity {
private static final int REQUEST_PERMISSIONS = 101;
private static final int REQUEST_PERMISSIONS = 101;
private MapView mapView;
private MapboxMap mapboxMap;
private MapView mapView;
private MapboxMap mapboxMap;
private ImageView dropPinView;
private Marker addressPin;
private ImageButton clearDisplayViewButton;
private MarkerView userMarker;
private ImageView dropPinView;
private Marker addressPin;
private ImageButton clearDisplayViewButton;
private MarkerView userMarker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_picker);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_picker);
setupActionBar();
setupActionBar();
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
//Create ui elements
createDropPin();
createSelectLocationButton();
createClearSelectionButton();
//Create ui elements
createDropPin();
createSelectLocationButton();
createClearSelectionButton();
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap map) {
//Store for later
mapboxMap = map;
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap map) {
//Store for later
mapboxMap = map;
//Add user marker
mapboxMap.getMarkerViewManager().addMarkerViewAdapter(
new PulseMarkerViewAdapter(LocationPickerActivity.this));
userMarker = createCustomUserMarker(new LatLng(0, 0));
//Add user marker
mapboxMap.getMarkerViewManager().addMarkerViewAdapter(
new PulseMarkerViewAdapter(LocationPickerActivity.this));
userMarker = createCustomUserMarker(new LatLng(0, 0));
//Fix the focal point to the center of the map
PointF focalPoint = new PointF(
(mapView.getX() + mapView.getWidth() / 2), (mapView.getY() + mapView.getHeight() / 2));
mapboxMap.getUiSettings().setFocalPoint(focalPoint);
//Fix the focal point to the center of the map
PointF focalPoint = new PointF(
(mapView.getX() + mapView.getWidth() / 2), (mapView.getY() + mapView.getHeight() / 2));
mapboxMap.getUiSettings().setFocalPoint(focalPoint);
//Track camera updates to animate the user location views
trackUserLocationView(userMarker);
}
});
//Track camera updates to animate the user location views
trackUserLocationView(userMarker);
}
});
}
private void zoomInOn(Location location) {
//Move the camera to the user
if (location != null) {
mapboxMap.setCameraPosition(new CameraPosition.Builder()
.target(new LatLng(location))
.zoom(16)
.bearing(0)
.tilt(0)
.build());
}
}
private void zoomInOn(Location location) {
//Move the camera to the user
if (location != null) {
mapboxMap.setCameraPosition(new CameraPosition.Builder()
.target(new LatLng(location))
.zoom(16)
.bearing(0)
.tilt(0)
.build());
/**
* Tracks the camera to animate the marker when overlapping with the picker.
* Makes sure the marker actually points to the user's position by tracking it.
*/
private void trackUserLocationView(final MarkerView markerView) {
final float circleDiameterSize = getResources().getDimension(R.dimen.circle_size);
//Track camera changes to check for overlap
mapboxMap.setOnCameraChangeListener(new MapboxMap.OnCameraChangeListener() {
private Animation pulseAnimation;
@Override
public void onCameraChange(CameraPosition position) {
if (markerView == null) {
return;
}
}
//Make drop pin visible, if it wasn't already
showDropPin();
/**
* Tracks the camera to animate the marker when overlapping with the picker.
* Makes sure the marker actually points to the user's position by tracking it.
*/
private void trackUserLocationView(final MarkerView markerView) {
final float circleDiameterSize = getResources().getDimension(R.dimen.circle_size);
//Get the distance from the tip of the location picker to the MarkerView
double distance = getLocationPickerLocation().distanceTo(markerView.getPosition());
//Track camera changes to check for overlap
mapboxMap.setOnCameraChangeListener(new MapboxMap.OnCameraChangeListener() {
private Animation pulseAnimation;
@Override
public void onCameraChange(CameraPosition position) {
if (markerView == null) {
return;
}
//Make drop pin visible, if it wasn't already
showDropPin();
//Get the distance from the tip of the location picker to the MarkerView
double distance = getLocationPickerLocation().distanceTo(markerView.getPosition());
//If closeby, animate, otherwise, stop animation
View view = mapboxMap.getMarkerViewManager().getView(markerView);
if (view != null) {
View backgroundView = view.findViewById(R.id.background_imageview);
if (pulseAnimation == null && distance < 0.5f * circleDiameterSize) {
pulseAnimation = AnimationUtils.loadAnimation(LocationPickerActivity.this, R.anim.pulse);
pulseAnimation.setRepeatCount(Animation.INFINITE);
pulseAnimation.setRepeatMode(Animation.RESTART);
backgroundView.startAnimation(pulseAnimation);
} else if (pulseAnimation != null && distance >= 0.5f * circleDiameterSize) {
backgroundView.clearAnimation();
pulseAnimation = null;
}
}
}
});
//Track location updates to move the user marker
LocationServices.getLocationServices(getApplicationContext()).addLocationListener(new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (location != null && markerView != null) {
markerView.setPosition(new LatLng(location));
}
}
});
}
private MarkerView createCustomUserMarker(LatLng markerPosition) {
return mapboxMap.addMarker(new PulseMarkerViewOptions()
.icon(IconFactory.getInstance(getApplicationContext()).fromResource(R.drawable.ic_my_location_24dp))
.position(markerPosition)
);
}
private void createClearSelectionButton() {
clearDisplayViewButton = (ImageButton) findViewById(R.id.clearDisplayViewButton);
clearDisplayViewButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
removeAddressPin();
hide(clearDisplayViewButton);
showDropPin();
}
});
}
private void createSelectLocationButton() {
Button selectLocationButton = (Button) findViewById(R.id.selectLocationButton);
//noinspection ConstantConditions
selectLocationButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
Timber.i("Location Selected!");
if (mapboxMap != null) {
//Control button's state
clearDisplayViewButton.setVisibility(View.VISIBLE);
dropPinView.setVisibility(View.INVISIBLE);
//Get position for the drop pin
LatLng position = getLocationPickerLocation();
//Show the address pin (result)
showAddressPin(position);
//Get the address for that location and update the marker
geocode(position, new GeocodeCallbacks() {
@Override
public void onResult(String result) {
updateAddressPin(result);
}
@Override
public void onFailure(Throwable failure) {
showFeedbackMessage("Could not retrieve address: " + failure.getMessage());
}
});
}
}
}
);
}
private void createDropPin() {
float density = getResources().getDisplayMetrics().density;
dropPinView = new ImageView(this);
dropPinView.setImageResource(R.drawable.ic_droppin_24dp);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
params.bottomMargin = (int) (12 * density);
dropPinView.setLayoutParams(params);
mapView.addView(dropPinView);
}
private void showDropPin() {
if (dropPinView != null && dropPinView.getVisibility() != View.VISIBLE) {
dropPinView.setVisibility(View.VISIBLE);
}
}
private void hide(View view) {
//If closeby, animate, otherwise, stop animation
View view = mapboxMap.getMarkerViewManager().getView(markerView);
if (view != null) {
view.setVisibility(View.INVISIBLE);
View backgroundView = view.findViewById(R.id.background_imageview);
if (pulseAnimation == null && distance < 0.5f * circleDiameterSize) {
pulseAnimation = AnimationUtils.loadAnimation(LocationPickerActivity.this, R.anim.pulse);
pulseAnimation.setRepeatCount(Animation.INFINITE);
pulseAnimation.setRepeatMode(Animation.RESTART);
backgroundView.startAnimation(pulseAnimation);
} else if (pulseAnimation != null && distance >= 0.5f * circleDiameterSize) {
backgroundView.clearAnimation();
pulseAnimation = null;
}
}
}
}
});
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
//Track location updates to move the user marker
LocationServices.getLocationServices(getApplicationContext()).addLocationListener(new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (location != null && markerView != null) {
markerView.setPosition(new LatLng(location));
}
}
}
});
}
/**
* Get address for the given location
*/
private void geocode(LatLng point, final GeocodeCallbacks callbacks) {
try {
//Create Geocoding client
MapboxGeocoding client = new MapboxGeocoding.Builder()
.setAccessToken(getString(R.string.mapbox_access_token))
.setCoordinates(Position.fromCoordinates(point.getLongitude(), point.getLatitude()))
.setGeocodingType(GeocodingCriteria.TYPE_ADDRESS)
.build();
private MarkerView createCustomUserMarker(LatLng markerPosition) {
return mapboxMap.addMarker(new PulseMarkerViewOptions()
.icon(IconFactory.getInstance(getApplicationContext()).fromResource(R.drawable.ic_my_location_24dp))
.position(markerPosition)
);
}
//Place the request
client.enqueueCall(new Callback<GeocodingResponse>() {
@Override
public void onResponse(Call<GeocodingResponse> call, Response<GeocodingResponse> response) {
private void createClearSelectionButton() {
clearDisplayViewButton = (ImageButton) findViewById(R.id.clearDisplayViewButton);
clearDisplayViewButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
removeAddressPin();
hide(clearDisplayViewButton);
showDropPin();
}
});
}
List<CarmenFeature> results = response.body().getFeatures();
String address = null;
if (results.size() > 0) {
CarmenFeature feature = results.get(0);
address = feature.getAddress() + " " + feature.getText();
Timber.i("address " + address);
} else {
showFeedbackMessage("No results for search.");
}
callbacks.onResult(address);
}
@Override
public void onFailure(Call<GeocodingResponse> call, Throwable throwable) {
Timber.e("Geocoding Failure: " + throwable.getMessage());
callbacks.onFailure(throwable);
}
});
} catch (ServicesException servicesException) {
Timber.e("Error geocoding: " + servicesException.toString());
callbacks.onFailure(servicesException);
}
}
private LatLng getLocationPickerLocation() {
return mapboxMap.getProjection().fromScreenLocation(
new PointF(dropPinView.getLeft() + (dropPinView.getWidth() / 2), dropPinView.getBottom())
);
}
private Marker showAddressPin(LatLng position) {
if (addressPin != null) {
//Remove previous pin
removeAddressPin();
}
//Create new one
addressPin = mapboxMap.addMarker(new MarkerViewOptions().title("Loading address...").position(position));
mapboxMap.selectMarker(addressPin);
return addressPin;
}
private void removeAddressPin() {
if (mapboxMap != null && addressPin != null) {
mapboxMap.removeMarker(addressPin);
}
}
private void updateAddressPin(@Nullable String address) {
if (addressPin != null) {
addressPin.setTitle(address == null ? "No address found" : address);
}
}
private void showFeedbackMessage(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private boolean arePermissionsGranted() {
if (Build.VERSION.SDK_INT >= 23
&& checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Timber.i("Requesting permissions");
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSIONS);
return false;
}
Timber.i("Permissions already granted");
return true;
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
//Check permissions
if (arePermissionsGranted()) {
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(final MapboxMap mapboxMap) {
//Get the user's location
final LocationServices locationServices = LocationServices.getLocationServices(getApplicationContext());
Location location = locationServices.getLastLocation();
if (location != null) {
zoomInOn(location);
userMarker.setPosition(new LatLng(location));
} else {
final ProgressDialog loadingDialog = ProgressDialog.show(
LocationPickerActivity.this, "Loading", "Getting user location", false);
locationServices.addLocationListener(new LocationListener() {
@Override
public void onLocationChanged(@Nullable Location location) {
//Move the camera to the user
if (location != null) {
zoomInOn(location);
userMarker.setPosition(new LatLng(location));
locationServices.removeLocationListener(this);
loadingDialog.hide();
}
}
});
}
locationServices.toggleGPS(true);
}
});
}
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Custom MarkerViewAdapter for the pulsing marker
*/
private static class PulseMarkerViewAdapter extends MapboxMap.MarkerViewAdapter<PulseMarkerView> {
private LayoutInflater inflater;
public PulseMarkerViewAdapter(@NonNull Context context) {
super(context);
this.inflater = LayoutInflater.from(context);
}
@Nullable
private void createSelectLocationButton() {
Button selectLocationButton = (Button) findViewById(R.id.selectLocationButton);
//noinspection ConstantConditions
selectLocationButton.setOnClickListener(
new View.OnClickListener() {
@Override
public View getView(@NonNull PulseMarkerView marker, @Nullable View convertView, @NonNull ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.view_pulse_marker, parent, false);
viewHolder.foregroundImageView = (ImageView) convertView.findViewById(R.id.foreground_imageView);
viewHolder.backgroundImageView = (ImageView) convertView.findViewById(R.id.background_imageview);
convertView.setTag(viewHolder);
}
return convertView;
public void onClick(View view) {
Timber.i("Location Selected!");
if (mapboxMap != null) {
//Control button's state
clearDisplayViewButton.setVisibility(View.VISIBLE);
dropPinView.setVisibility(View.INVISIBLE);
//Get position for the drop pin
LatLng position = getLocationPickerLocation();
//Show the address pin (result)
showAddressPin(position);
//Get the address for that location and update the marker
geocode(position, new GeocodeCallbacks() {
@Override
public void onResult(String result) {
updateAddressPin(result);
}
@Override
public void onFailure(Throwable failure) {
showFeedbackMessage("Could not retrieve address: " + failure.getMessage());
}
});
}
}
}
);
}
private void createDropPin() {
float density = getResources().getDisplayMetrics().density;
dropPinView = new ImageView(this);
dropPinView.setImageResource(R.drawable.ic_droppin_24dp);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
params.bottomMargin = (int) (12 * density);
dropPinView.setLayoutParams(params);
mapView.addView(dropPinView);
}
private void showDropPin() {
if (dropPinView != null && dropPinView.getVisibility() != View.VISIBLE) {
dropPinView.setVisibility(View.VISIBLE);
}
}
private void hide(View view) {
if (view != null) {
view.setVisibility(View.INVISIBLE);
}
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
}
/**
* Get address for the given location
*/
private void geocode(LatLng point, final GeocodeCallbacks callbacks) {
try {
//Create Geocoding client
MapboxGeocoding client = new MapboxGeocoding.Builder()
.setAccessToken(getString(R.string.mapbox_access_token))
.setCoordinates(Position.fromCoordinates(point.getLongitude(), point.getLatitude()))
.setGeocodingType(GeocodingCriteria.TYPE_ADDRESS)
.build();
//Place the request
client.enqueueCall(new Callback<GeocodingResponse>() {
@Override
public void onResponse(Call<GeocodingResponse> call, Response<GeocodingResponse> response) {
List<CarmenFeature> results = response.body().getFeatures();
String address = null;
if (results.size() > 0) {
CarmenFeature feature = results.get(0);
address = feature.getAddress() + " " + feature.getText();
Timber.i("address " + address);
} else {
showFeedbackMessage("No results for search.");
}
callbacks.onResult(address);
}
private static class ViewHolder {
ImageView foregroundImageView;
ImageView backgroundImageView;
@Override
public void onFailure(Call<GeocodingResponse> call, Throwable throwable) {
Timber.e("Geocoding Failure: " + throwable.getMessage());
callbacks.onFailure(throwable);
}
});
} catch (ServicesException servicesException) {
Timber.e("Error geocoding: " + servicesException.toString());
callbacks.onFailure(servicesException);
}
}
private LatLng getLocationPickerLocation() {
return mapboxMap.getProjection().fromScreenLocation(
new PointF(dropPinView.getLeft() + (dropPinView.getWidth() / 2), dropPinView.getBottom())
);
}
private Marker showAddressPin(LatLng position) {
if (addressPin != null) {
//Remove previous pin
removeAddressPin();
}
private interface GeocodeCallbacks {
void onResult(String result);
//Create new one
addressPin = mapboxMap.addMarker(new MarkerViewOptions().title("Loading address...").position(position));
mapboxMap.selectMarker(addressPin);
return addressPin;
}
void onFailure(Throwable failure);
private void removeAddressPin() {
if (mapboxMap != null && addressPin != null) {
mapboxMap.removeMarker(addressPin);
}
}
private void updateAddressPin(@Nullable String address) {
if (addressPin != null) {
addressPin.setTitle(address == null ? "No address found" : address);
}
}
private void showFeedbackMessage(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private boolean arePermissionsGranted() {
if (Build.VERSION.SDK_INT >= 23
&& checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Timber.i("Requesting permissions");
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSIONS);
return false;
}
Timber.i("Permissions already granted");
return true;
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
//Check permissions
if (arePermissionsGranted()) {
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(final MapboxMap mapboxMap) {
//Get the user's location
final LocationServices locationServices = LocationServices.getLocationServices(getApplicationContext());
Location location = locationServices.getLastLocation();
if (location != null) {
zoomInOn(location);
userMarker.setPosition(new LatLng(location));
} else {
final ProgressDialog loadingDialog = ProgressDialog.show(
LocationPickerActivity.this, "Loading", "Getting user location", false);
locationServices.addLocationListener(new LocationListener() {
@Override
public void onLocationChanged(@Nullable Location location) {
//Move the camera to the user
if (location != null) {
zoomInOn(location);
userMarker.setPosition(new LatLng(location));
locationServices.removeLocationListener(this);
loadingDialog.hide();
}
}
});
}
locationServices.toggleGPS(true);
}
});
}
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Custom MarkerViewAdapter for the pulsing marker
*/
private static class PulseMarkerViewAdapter extends MapboxMap.MarkerViewAdapter<PulseMarkerView> {
private LayoutInflater inflater;
public PulseMarkerViewAdapter(@NonNull Context context) {
super(context);
this.inflater = LayoutInflater.from(context);
}
@Nullable
@Override
public View getView(@NonNull PulseMarkerView marker, @Nullable View convertView, @NonNull ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.view_pulse_marker, parent, false);
viewHolder.foregroundImageView = (ImageView) convertView.findViewById(R.id.foreground_imageView);
viewHolder.backgroundImageView = (ImageView) convertView.findViewById(R.id.background_imageview);
convertView.setTag(viewHolder);
}
return convertView;
}
private static class ViewHolder {
ImageView foregroundImageView;
ImageView backgroundImageView;
}
}
private interface GeocodeCallbacks {
void onResult(String result);
void onFailure(Throwable failure);
}
}

View File

@@ -6,7 +6,9 @@ import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import timber.log.Timber;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
@@ -36,320 +38,320 @@ import com.mapbox.mapboxsdk.testapp.utils.OfflineUtils;
import java.util.ArrayList;
public class OfflineActivity extends AppCompatActivity
implements OfflineDownloadRegionDialog.DownloadRegionDialogListener {
implements OfflineDownloadRegionDialog.DownloadRegionDialogListener {
// JSON encoding/decoding
public static final String JSON_CHARSET = "UTF-8";
public static final String JSON_FIELD_REGION_NAME = "FIELD_REGION_NAME";
// JSON encoding/decoding
public static final String JSON_CHARSET = "UTF-8";
public static final String JSON_FIELD_REGION_NAME = "FIELD_REGION_NAME";
// Style URL
public static final String STYLE_URL = Style.MAPBOX_STREETS;
// Style URL
public static final String STYLE_URL = Style.MAPBOX_STREETS;
/*
* UI elements
*/
private MapView mapView;
private MapboxMap mapboxMap;
private ProgressBar progressBar;
private Button downloadRegion;
private Button listRegions;
/*
* UI elements
*/
private MapView mapView;
private MapboxMap mapboxMap;
private ProgressBar progressBar;
private Button downloadRegion;
private Button listRegions;
private boolean isEndNotified;
private boolean isEndNotified;
/*
* Offline objects
*/
private OfflineManager offlineManager;
private OfflineRegion offlineRegion;
/*
* Offline objects
*/
private OfflineManager offlineManager;
private OfflineRegion offlineRegion;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_offline);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_offline);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
// You can use MapboxAccountManager.setConnected(Boolean) to manually set the connectivity
// state of your app. This will override any checks performed via the ConnectivityManager.
//MapboxAccountManager.getInstance().setConnected(false);
Boolean connected = MapboxAccountManager.getInstance().isConnected();
Timber.d(String.format(MapboxConstants.MAPBOX_LOCALE,
"MapboxAccountManager is connected: %b", connected));
// Set up map
mapView = (MapView) findViewById(R.id.mapView);
mapView.setStyleUrl(STYLE_URL);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
Timber.d("Map is ready");
OfflineActivity.this.mapboxMap = mapboxMap;
// Set initial position to UNHQ in NYC
mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(new LatLng(40.749851, -73.967966))
.zoom(14)
.bearing(0)
.tilt(0)
.build()));
}
});
// The progress bar
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
// Set up button listeners
downloadRegion = (Button) findViewById(R.id.button_download_region);
downloadRegion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
handleDownloadRegion();
}
});
listRegions = (Button) findViewById(R.id.button_list_regions);
listRegions.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
handleListRegions();
}
});
// Set up the OfflineManager
offlineManager = OfflineManager.getInstance(this);
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/*
* Buttons logic
*/
private void handleDownloadRegion() {
Timber.d("handleDownloadRegion");
// Show dialog
OfflineDownloadRegionDialog offlineDownloadRegionDialog = new OfflineDownloadRegionDialog();
offlineDownloadRegionDialog.show(getSupportFragmentManager(), "download");
}
private void handleListRegions() {
Timber.d("handleListRegions");
// Query the DB asynchronously
offlineManager.listOfflineRegions(new OfflineManager.ListOfflineRegionsCallback() {
@Override
public void onList(OfflineRegion[] offlineRegions) {
// Check result
if (offlineRegions == null || offlineRegions.length == 0) {
Toast.makeText(OfflineActivity.this, "You have no regions yet.", Toast.LENGTH_SHORT).show();
return;
}
// You can use MapboxAccountManager.setConnected(Boolean) to manually set the connectivity
// state of your app. This will override any checks performed via the ConnectivityManager.
//MapboxAccountManager.getInstance().setConnected(false);
Boolean connected = MapboxAccountManager.getInstance().isConnected();
Timber.d(String.format(MapboxConstants.MAPBOX_LOCALE,
"MapboxAccountManager is connected: %b", connected));
// Set up map
mapView = (MapView) findViewById(R.id.mapView);
mapView.setStyleUrl(STYLE_URL);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
Timber.d("Map is ready");
OfflineActivity.this.mapboxMap = mapboxMap;
// Set initial position to UNHQ in NYC
mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(new LatLng(40.749851, -73.967966))
.zoom(14)
.bearing(0)
.tilt(0)
.build()));
}
});
// The progress bar
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
// Set up button listeners
downloadRegion = (Button) findViewById(R.id.button_download_region);
downloadRegion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
handleDownloadRegion();
}
});
listRegions = (Button) findViewById(R.id.button_list_regions);
listRegions.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
handleListRegions();
}
});
// Set up the OfflineManager
offlineManager = OfflineManager.getInstance(this);
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
// Get regions info
ArrayList<String> offlineRegionsNames = new ArrayList<>();
for (OfflineRegion offlineRegion : offlineRegions) {
offlineRegionsNames.add(OfflineUtils.convertRegionName(offlineRegion.getMetadata()));
}
}
/*
* Buttons logic
*/
private void handleDownloadRegion() {
Timber.d("handleDownloadRegion");
// Create args
Bundle args = new Bundle();
args.putStringArrayList(OfflineListRegionsDialog.ITEMS, offlineRegionsNames);
// Show dialog
OfflineDownloadRegionDialog offlineDownloadRegionDialog = new OfflineDownloadRegionDialog();
offlineDownloadRegionDialog.show(getSupportFragmentManager(), "download");
OfflineListRegionsDialog offlineListRegionsDialog = new OfflineListRegionsDialog();
offlineListRegionsDialog.setArguments(args);
offlineListRegionsDialog.show(getSupportFragmentManager(), "list");
}
@Override
public void onError(String error) {
Timber.e("Error: " + error);
}
});
}
/*
* Dialogs
*/
@Override
public void onDownloadRegionDialogPositiveClick(final String regionName) {
if (TextUtils.isEmpty(regionName)) {
Toast.makeText(OfflineActivity.this, "Region name cannot be empty.", Toast.LENGTH_SHORT).show();
return;
}
private void handleListRegions() {
Timber.d("handleListRegions");
// Start progress bar
Timber.d("Download started: " + regionName);
startProgress();
// Query the DB asynchronously
offlineManager.listOfflineRegions(new OfflineManager.ListOfflineRegionsCallback() {
@Override
public void onList(OfflineRegion[] offlineRegions) {
// Check result
if (offlineRegions == null || offlineRegions.length == 0) {
Toast.makeText(OfflineActivity.this, "You have no regions yet.", Toast.LENGTH_SHORT).show();
return;
}
// Definition
LatLngBounds bounds = mapboxMap.getProjection().getVisibleRegion().latLngBounds;
double minZoom = mapboxMap.getCameraPosition().zoom;
double maxZoom = mapboxMap.getMaxZoomLevel();
float pixelRatio = this.getResources().getDisplayMetrics().density;
OfflineTilePyramidRegionDefinition definition = new OfflineTilePyramidRegionDefinition(
STYLE_URL, bounds, minZoom, maxZoom, pixelRatio);
// Get regions info
ArrayList<String> offlineRegionsNames = new ArrayList<>();
for (OfflineRegion offlineRegion : offlineRegions) {
offlineRegionsNames.add(OfflineUtils.convertRegionName(offlineRegion.getMetadata()));
}
// Sample way of encoding metadata from a JSONObject
byte[] metadata = OfflineUtils.convertRegionName(regionName);
// Create args
Bundle args = new Bundle();
args.putStringArrayList(OfflineListRegionsDialog.ITEMS, offlineRegionsNames);
// Create region
offlineManager.createOfflineRegion(definition, metadata, new OfflineManager.CreateOfflineRegionCallback() {
@Override
public void onCreate(OfflineRegion offlineRegion) {
Timber.d("Offline region created: " + regionName);
OfflineActivity.this.offlineRegion = offlineRegion;
launchDownload();
}
// Show dialog
OfflineListRegionsDialog offlineListRegionsDialog = new OfflineListRegionsDialog();
offlineListRegionsDialog.setArguments(args);
offlineListRegionsDialog.show(getSupportFragmentManager(), "list");
}
@Override
public void onError(String error) {
Timber.e("Error: " + error);
}
});
}
@Override
public void onError(String error) {
Timber.e("Error: " + error);
}
});
}
private void launchDownload() {
// Set an observer
offlineRegion.setObserver(new OfflineRegion.OfflineRegionObserver() {
@Override
public void onStatusChanged(OfflineRegionStatus status) {
// Compute a percentage
double percentage = status.getRequiredResourceCount() >= 0
? (100.0 * status.getCompletedResourceCount() / status.getRequiredResourceCount()) :
0.0;
/*
* Dialogs
*/
@Override
public void onDownloadRegionDialogPositiveClick(final String regionName) {
if (TextUtils.isEmpty(regionName)) {
Toast.makeText(OfflineActivity.this, "Region name cannot be empty.", Toast.LENGTH_SHORT).show();
return;
if (status.isComplete()) {
// Download complete
endProgress("Region downloaded successfully.");
return;
} else if (status.isRequiredResourceCountPrecise()) {
// Switch to determinate state
setPercentage((int) Math.round(percentage));
}
// Start progress bar
Timber.d("Download started: " + regionName);
startProgress();
// Debug
Timber.d(String.format("%s/%s resources; %s bytes downloaded.",
String.valueOf(status.getCompletedResourceCount()),
String.valueOf(status.getRequiredResourceCount()),
String.valueOf(status.getCompletedResourceSize())));
}
// Definition
LatLngBounds bounds = mapboxMap.getProjection().getVisibleRegion().latLngBounds;
double minZoom = mapboxMap.getCameraPosition().zoom;
double maxZoom = mapboxMap.getMaxZoomLevel();
float pixelRatio = this.getResources().getDisplayMetrics().density;
OfflineTilePyramidRegionDefinition definition = new OfflineTilePyramidRegionDefinition(
STYLE_URL, bounds, minZoom, maxZoom, pixelRatio);
@Override
public void onError(OfflineRegionError error) {
Timber.e("onError reason: " + error.getReason());
Timber.e("onError message: " + error.getMessage());
}
// Sample way of encoding metadata from a JSONObject
byte[] metadata = OfflineUtils.convertRegionName(regionName);
@Override
public void mapboxTileCountLimitExceeded(long limit) {
Timber.e("Mapbox tile count limit exceeded: " + limit);
}
});
// Create region
offlineManager.createOfflineRegion(definition, metadata, new OfflineManager.CreateOfflineRegionCallback() {
@Override
public void onCreate(OfflineRegion offlineRegion) {
Timber.d("Offline region created: " + regionName);
OfflineActivity.this.offlineRegion = offlineRegion;
launchDownload();
}
// Change the region state
offlineRegion.setDownloadState(OfflineRegion.STATE_ACTIVE);
}
@Override
public void onError(String error) {
Timber.e("Error: " + error);
}
});
/*
* Progress bar
*/
private void startProgress() {
// Disable buttons
downloadRegion.setEnabled(false);
listRegions.setEnabled(false);
// Start and show the progress bar
isEndNotified = false;
progressBar.setIndeterminate(true);
progressBar.setVisibility(View.VISIBLE);
}
private void setPercentage(final int percentage) {
progressBar.setIndeterminate(false);
progressBar.setProgress(percentage);
}
private void endProgress(final String message) {
// Don't notify more than once
if (isEndNotified) {
return;
}
private void launchDownload() {
// Set an observer
offlineRegion.setObserver(new OfflineRegion.OfflineRegionObserver() {
@Override
public void onStatusChanged(OfflineRegionStatus status) {
// Compute a percentage
double percentage = status.getRequiredResourceCount() >= 0
? (100.0 * status.getCompletedResourceCount() / status.getRequiredResourceCount()) :
0.0;
// Enable buttons
downloadRegion.setEnabled(true);
listRegions.setEnabled(true);
if (status.isComplete()) {
// Download complete
endProgress("Region downloaded successfully.");
return;
} else if (status.isRequiredResourceCountPrecise()) {
// Switch to determinate state
setPercentage((int) Math.round(percentage));
}
// Stop and hide the progress bar
isEndNotified = true;
progressBar.setIndeterminate(false);
progressBar.setVisibility(View.GONE);
// Debug
Timber.d(String.format("%s/%s resources; %s bytes downloaded.",
String.valueOf(status.getCompletedResourceCount()),
String.valueOf(status.getRequiredResourceCount()),
String.valueOf(status.getCompletedResourceSize())));
}
// Show a toast
Toast.makeText(OfflineActivity.this, message, Toast.LENGTH_LONG).show();
}
@Override
public void onError(OfflineRegionError error) {
Timber.e("onError reason: " + error.getReason());
Timber.e("onError message: " + error.getMessage());
}
@Override
public void mapboxTileCountLimitExceeded(long limit) {
Timber.e("Mapbox tile count limit exceeded: " + limit);
}
});
// Change the region state
offlineRegion.setDownloadState(OfflineRegion.STATE_ACTIVE);
}
/*
* Progress bar
*/
private void startProgress() {
// Disable buttons
downloadRegion.setEnabled(false);
listRegions.setEnabled(false);
// Start and show the progress bar
isEndNotified = false;
progressBar.setIndeterminate(true);
progressBar.setVisibility(View.VISIBLE);
}
private void setPercentage(final int percentage) {
progressBar.setIndeterminate(false);
progressBar.setProgress(percentage);
}
private void endProgress(final String message) {
// Don't notify more than once
if (isEndNotified) {
return;
}
// Enable buttons
downloadRegion.setEnabled(true);
listRegions.setEnabled(true);
// Stop and hide the progress bar
isEndNotified = true;
progressBar.setIndeterminate(false);
progressBar.setVisibility(View.GONE);
// Show a toast
Toast.makeText(OfflineActivity.this, message, Toast.LENGTH_LONG).show();
}
}
}

View File

@@ -33,154 +33,158 @@ import java.util.List;
*/
public class UpdateMetadataActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private OfflineRegionMetadataAdapter adapter;
private OfflineRegionMetadataAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_metadata_update);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_metadata_update);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter = new OfflineRegionMetadataAdapter(this));
listView.setEmptyView(findViewById(android.R.id.empty));
listView.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final OfflineRegion region = adapter.getItem(position);
String metadata = OfflineUtils.convertRegionName(region.getMetadata());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Rename metadata");
final EditText input = new EditText(this);
input.setText(metadata);
input.setInputType(InputType.TYPE_CLASS_TEXT);
input.setSelection(metadata.length());
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
updateMetadata(region, OfflineUtils.convertRegionName(input.getText().toString()));
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
private void updateMetadata(OfflineRegion region, byte[] metadata) {
region.updateMetadata(metadata, new OfflineRegion.OfflineRegionUpdateMetadataCallback() {
@Override
public void onUpdate(byte[] metadata) {
adapter.notifyDataSetChanged();
}
@Override
public void onError(String error) {
Toast.makeText(
UpdateMetadataActivity.this,
"Region metadata update failed with " + error,
Toast.LENGTH_LONG
).show();
}
});
}
@Override
protected void onStart() {
super.onStart();
loadOfflineRegions();
}
private void loadOfflineRegions() {
OfflineManager.getInstance(this).listOfflineRegions(new OfflineManager.ListOfflineRegionsCallback() {
@Override
public void onList(OfflineRegion[] offlineRegions) {
if (offlineRegions != null && offlineRegions.length > 0) {
adapter.setOfflineRegions(Arrays.asList(offlineRegions));
}
}
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter = new OfflineRegionMetadataAdapter(this));
listView.setEmptyView(findViewById(android.R.id.empty));
listView.setOnItemClickListener(this);
@Override
public void onError(String error) {
Toast.makeText(UpdateMetadataActivity.this, "Error loading regions " + error, Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private static class OfflineRegionMetadataAdapter extends BaseAdapter {
private Context context;
private List<OfflineRegion> offlineRegions;
OfflineRegionMetadataAdapter(Context ctx) {
context = ctx;
offlineRegions = new ArrayList<>();
}
void setOfflineRegions(List<OfflineRegion> offlineRegions) {
this.offlineRegions = offlineRegions;
notifyDataSetChanged();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final OfflineRegion region = adapter.getItem(position);
String metadata = OfflineUtils.convertRegionName(region.getMetadata());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Rename metadata");
final EditText input = new EditText(this);
input.setText(metadata);
input.setInputType(InputType.TYPE_CLASS_TEXT);
input.setSelection(metadata.length());
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
updateMetadata(region, OfflineUtils.convertRegionName(input.getText().toString()));
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
private void updateMetadata(OfflineRegion region, byte[] metadata) {
region.updateMetadata(metadata, new OfflineRegion.OfflineRegionUpdateMetadataCallback() {
@Override
public void onUpdate(byte[] metadata) {
adapter.notifyDataSetChanged();
}
@Override
public void onError(String error) {
Toast.makeText(UpdateMetadataActivity.this, "Region metadata update failed with " + error, Toast.LENGTH_LONG).show();
}
});
public int getCount() {
return offlineRegions.size();
}
@Override
protected void onStart() {
super.onStart();
loadOfflineRegions();
}
private void loadOfflineRegions() {
OfflineManager.getInstance(this).listOfflineRegions(new OfflineManager.ListOfflineRegionsCallback() {
@Override
public void onList(OfflineRegion[] offlineRegions) {
if (offlineRegions != null && offlineRegions.length > 0) {
adapter.setOfflineRegions(Arrays.asList(offlineRegions));
}
}
@Override
public void onError(String error) {
Toast.makeText(UpdateMetadataActivity.this, "Error loading regions " + error, Toast.LENGTH_LONG).show();
}
});
public OfflineRegion getItem(int position) {
return offlineRegions.get(position);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
public long getItemId(int position) {
return position;
}
private static class OfflineRegionMetadataAdapter extends BaseAdapter {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
private Context context;
private List<OfflineRegion> offlineRegions;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, parent, false);
holder.text = (TextView) convertView.findViewById(android.R.id.text1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
OfflineRegionMetadataAdapter(Context ctx) {
context = ctx;
offlineRegions = new ArrayList<>();
}
void setOfflineRegions(List<OfflineRegion> offlineRegions) {
this.offlineRegions = offlineRegions;
notifyDataSetChanged();
}
@Override
public int getCount() {
return offlineRegions.size();
}
@Override
public OfflineRegion getItem(int position) {
return offlineRegions.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, parent, false);
holder.text = (TextView) convertView.findViewById(android.R.id.text1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(OfflineUtils.convertRegionName(getItem(position).getMetadata()));
return convertView;
}
static class ViewHolder {
TextView text;
}
holder.text.setText(OfflineUtils.convertRegionName(getItem(position).getMetadata()));
return convertView;
}
static class ViewHolder {
TextView text;
}
}
}

View File

@@ -8,7 +8,9 @@ import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.MenuItem;
import android.view.View;
@@ -33,120 +35,120 @@ import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleRadius;
*/
public class CircleLayerActivity extends AppCompatActivity {
private MapboxMap mapboxMap;
private MapView mapView;
private Layer circleLayer;
private MapboxMap mapboxMap;
private MapView mapView;
private Layer circleLayer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_circlelayer);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_circlelayer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull final MapboxMap map) {
mapboxMap = map;
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setColorFilter(ContextCompat.getColor(CircleLayerActivity.this, R.color.primary));
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (circleLayer == null) {
// first time
try {
mapboxMap.addSource(new GeoJsonSource("point", new URL("https://gist.githubusercontent.com/anonymous/87eca90e80a72b1b42be9d0201ec3c8e/raw/acbb46384fd56044a504f122950d0637d98b4e7a/map.geojson")));
} catch (MalformedURLException malformedUrlException) {
Timber.e(
"That's not an url... " + malformedUrlException.getMessage()
);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull final MapboxMap map) {
mapboxMap = map;
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setColorFilter(ContextCompat.getColor(CircleLayerActivity.this, R.color.primary));
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (circleLayer == null) {
// first time
try {
mapboxMap.addSource(new GeoJsonSource("point", new URL("https://gist.githubusercontent.com/anonymous/87eca90e80a72b1b42be9d0201ec3c8e/raw/acbb46384fd56044a504f122950d0637d98b4e7a/map.geojson")));
} catch (MalformedURLException malformedUrlException) {
Timber.e(
"That's not an url... " + malformedUrlException.getMessage()
);
}
circleLayer = new CircleLayer("circleLayer", "point");
circleLayer.setProperties(
circleColor(ResourcesCompat.getColor(getResources(), R.color.primary_dark, getTheme())),
circleRadius(getResources().getDimension(R.dimen.circle_size))
);
circleLayer = new CircleLayer("circleLayer", "point");
circleLayer.setProperties(
circleColor(ResourcesCompat.getColor(getResources(), R.color.primary_dark, getTheme())),
circleRadius(getResources().getDimension(R.dimen.circle_size))
);
// lets add a circle below labels!
mapboxMap.addLayer(circleLayer, "waterway-label");
} else {
// change size and color
circleLayer.setProperties(
circleRadius(mapView.getTag() == null
? getResources().getDimension(R.dimen.activity_horizontal_margin)
: getResources().getDimension(R.dimen.circle_size)),
circleColor(mapView.getTag() == null ? ResourcesCompat.getColor(
getResources(), R.color.blue_accent, getTheme()) : ResourcesCompat.getColor(
getResources(), R.color.green_accent, getTheme())));
mapView.setTag(mapView.getTag() == null ? mapboxMap : null);
}
}
});
// lets add a circle below labels!
mapboxMap.addLayer(circleLayer, "waterway-label");
} else {
// change size and color
circleLayer.setProperties(
circleRadius(mapView.getTag() == null
? getResources().getDimension(R.dimen.activity_horizontal_margin)
: getResources().getDimension(R.dimen.circle_size)),
circleColor(mapView.getTag() == null ? ResourcesCompat.getColor(
getResources(), R.color.blue_accent, getTheme()) : ResourcesCompat.getColor(
getResources(), R.color.green_accent, getTheme())));
mapView.setTag(mapView.getTag() == null ? mapboxMap : null);
}
}
});
}
}
});
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -8,7 +8,9 @@ import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.MenuItem;
import android.view.View;
@@ -32,126 +34,133 @@ import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;
* Example to add a sprite image and use it in a Symbol Layer
*/
public class CustomSpriteActivity extends AppCompatActivity {
private static final String CUSTOM_ICON = "custom-icon";
private static final String CUSTOM_ICON = "custom-icon";
private MapboxMap mapboxMap;
private MapView mapView;
private Layer layer;
private GeoJsonSource source;
private MapboxMap mapboxMap;
private MapView mapView;
private Layer layer;
private GeoJsonSource source;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_sprite);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_sprite);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull final MapboxMap map) {
mapboxMap = map;
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setColorFilter(ContextCompat.getColor(CustomSpriteActivity.this, R.color.primary));
fab.setOnClickListener(new View.OnClickListener() {
private Point point;
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull final MapboxMap map) {
mapboxMap = map;
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setColorFilter(ContextCompat.getColor(CustomSpriteActivity.this, R.color.primary));
fab.setOnClickListener(new View.OnClickListener() {
private Point point;
@Override
public void onClick(View view) {
if (point == null) {
Timber.i("First click -> Car");
// Add an icon to reference later
mapboxMap.addImage(CUSTOM_ICON, BitmapFactory.decodeResource(getResources(), R.drawable.ic_car_top));
@Override
public void onClick(View view) {
if (point == null) {
Timber.i("First click -> Car");
// Add an icon to reference later
mapboxMap.addImage(CUSTOM_ICON, BitmapFactory.decodeResource(getResources(), R.drawable.ic_car_top));
//Add a source with a geojson point
point = Point.fromCoordinates(Position.fromCoordinates(13.400972d, 52.519003d));
source = new GeoJsonSource("point", FeatureCollection.fromFeatures(new Feature[]{Feature.fromGeometry(point)}));
mapboxMap.addSource(source);
//Add a source with a geojson point
point = Point.fromCoordinates(Position.fromCoordinates(13.400972d, 52.519003d));
source = new GeoJsonSource(
"point",
FeatureCollection.fromFeatures(new Feature[] {Feature.fromGeometry(point)})
);
mapboxMap.addSource(source);
//Add a symbol layer that references that point source
layer = new SymbolLayer("layer", "point");
layer.setProperties(
//Set the id of the sprite to use
iconImage(CUSTOM_ICON)
);
//Add a symbol layer that references that point source
layer = new SymbolLayer("layer", "point");
layer.setProperties(
//Set the id of the sprite to use
iconImage(CUSTOM_ICON)
);
// lets add a circle below labels!
mapboxMap.addLayer(layer, "waterway-label");
// lets add a circle below labels!
mapboxMap.addLayer(layer, "waterway-label");
fab.setImageResource(R.drawable.ic_directions_car_black_24dp);
} else {
//Update point
point = Point.fromCoordinates(Position.fromCoordinates(point.getCoordinates().getLongitude() + 0.001, point.getCoordinates().getLatitude() + 0.001));
source.setGeoJson(FeatureCollection.fromFeatures(new Feature[]{Feature.fromGeometry(point)}));
fab.setImageResource(R.drawable.ic_directions_car_black_24dp);
} else {
//Update point
point = Point.fromCoordinates(
Position.fromCoordinates(point.getCoordinates().getLongitude() + 0.001,
point.getCoordinates().getLatitude() + 0.001)
);
source.setGeoJson(FeatureCollection.fromFeatures(new Feature[] {Feature.fromGeometry(point)}));
//Move the camera as well
mapboxMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(point.getCoordinates().getLatitude(), point.getCoordinates().getLongitude())));
}
}
});
//Move the camera as well
mapboxMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(
point.getCoordinates().getLatitude(), point.getCoordinates().getLongitude())));
}
}
});
}
}
});
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -6,7 +6,9 @@ import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.MenuItem;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
@@ -38,150 +40,150 @@ import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textSize;
*/
public class GeoJsonClusteringActivity extends AppCompatActivity {
private MapView mapView;
private MapboxMap mapboxMap;
private MapView mapView;
private MapboxMap mapboxMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geojson_clustering);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geojson_clustering);
setupActionBar();
setupActionBar();
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
//noinspection ConstantConditions
mapView.onCreate(savedInstanceState);
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
//noinspection ConstantConditions
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
mapboxMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(37.7749, 122.4194), 0));
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
mapboxMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(37.7749, 122.4194), 0));
//Add a clustered source with some layers
addClusteredGeoJsonSource();
}
});
//Add a clustered source with some layers
addClusteredGeoJsonSource();
}
});
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void addClusteredGeoJsonSource() {
//Add a clustered source
try {
mapboxMap.addSource(
new GeoJsonSource("earthquakes",
new URL("https://www.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson"),
new GeoJsonOptions()
.withCluster(true)
.withClusterMaxZoom(14)
.withClusterRadius(50)
)
);
} catch (MalformedURLException malformedUrlException) {
Timber.e("That's not an url... " + malformedUrlException.getMessage());
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
//Add unclustered layer
int[][] layers = new int[][] {
new int[] {150, ResourcesCompat.getColor(getResources(), R.color.red_accent, getTheme())},
new int[] {20, ResourcesCompat.getColor(getResources(), R.color.green_accent, getTheme())},
new int[] {0, ResourcesCompat.getColor(getResources(), R.color.blue_accent, getTheme())}
};
SymbolLayer unclustered = new SymbolLayer("unclustered-points", "earthquakes");
unclustered.setProperties(iconImage("marker-15"));
mapboxMap.addLayer(unclustered);
for (int i = 0; i < layers.length; i++) {
//Add some nice circles
CircleLayer circles = new CircleLayer("cluster-" + i, "earthquakes");
circles.setProperties(
circleColor(layers[i][1]),
circleRadius(18f)
);
circles.setFilter(
i == 0
? gte("point_count", layers[i][0]) :
all(gte("point_count", layers[i][0]), lt("point_count", layers[i - 1][0]))
);
mapboxMap.addLayer(circles);
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void addClusteredGeoJsonSource() {
//Add a clustered source
try {
mapboxMap.addSource(
new GeoJsonSource("earthquakes",
new URL("https://www.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson"),
new GeoJsonOptions()
.withCluster(true)
.withClusterMaxZoom(14)
.withClusterRadius(50)
)
);
} catch (MalformedURLException malformedUrlException) {
Timber.e("That's not an url... " + malformedUrlException.getMessage());
}
//Add unclustered layer
int[][] layers = new int[][]{
new int[]{150, ResourcesCompat.getColor(getResources(), R.color.red_accent, getTheme())},
new int[]{20, ResourcesCompat.getColor(getResources(), R.color.green_accent, getTheme())},
new int[]{0, ResourcesCompat.getColor(getResources(), R.color.blue_accent, getTheme())}
};
SymbolLayer unclustered = new SymbolLayer("unclustered-points", "earthquakes");
unclustered.setProperties(iconImage("marker-15"));
mapboxMap.addLayer(unclustered);
for (int i = 0; i < layers.length; i++) {
//Add some nice circles
CircleLayer circles = new CircleLayer("cluster-" + i, "earthquakes");
circles.setProperties(
circleColor(layers[i][1]),
circleRadius(18f)
);
circles.setFilter(
i == 0
? gte("point_count", layers[i][0]) :
all(gte("point_count", layers[i][0]), lt("point_count", layers[i - 1][0]))
);
mapboxMap.addLayer(circles);
}
//Add the count labels
SymbolLayer count = new SymbolLayer("count", "earthquakes");
count.setProperties(
textField("{point_count}"),
textSize(12f),
textColor(Color.WHITE)
);
mapboxMap.addLayer(count);
//Zoom out to start
mapboxMap.animateCamera(CameraUpdateFactory.zoomTo(1));
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
//Add the count labels
SymbolLayer count = new SymbolLayer("count", "earthquakes");
count.setProperties(
textField("{point_count}"),
textSize(12f),
textColor(Color.WHITE)
);
mapboxMap.addLayer(count);
//Zoom out to start
mapboxMap.animateCamera(CameraUpdateFactory.zoomTo(1));
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
}
}

View File

@@ -6,7 +6,9 @@ import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.MenuItem;
import com.mapbox.mapboxsdk.maps.MapView;
@@ -29,119 +31,119 @@ import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;
*/
public class RealTimeGeoJsonActivity extends AppCompatActivity implements OnMapReadyCallback {
private final static String ID_GEOJSON_LAYER = "wanderdrone";
private final static String ID_GEOJSON_SOURCE = ID_GEOJSON_LAYER;
private final static String URL_GEOJSON_SOURCE = "https://wanderdrone.appspot.com/";
private static final String ID_GEOJSON_LAYER = "wanderdrone";
private static final String ID_GEOJSON_SOURCE = ID_GEOJSON_LAYER;
private static final String URL_GEOJSON_SOURCE = "https://wanderdrone.appspot.com/";
private MapView mapView;
private MapboxMap mapboxMap;
private Handler handler;
private Runnable runnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_default);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
@Override
public void onMapReady(@NonNull final MapboxMap map) {
mapboxMap = map;
// add source
try {
mapboxMap.addSource(new GeoJsonSource(ID_GEOJSON_SOURCE, new URL(URL_GEOJSON_SOURCE)));
} catch (MalformedURLException malformedUrlException) {
Timber.e("Invalid URL", malformedUrlException);
}
// add layer
SymbolLayer layer = new SymbolLayer(ID_GEOJSON_LAYER, ID_GEOJSON_SOURCE);
layer.setProperties(iconImage("rocket-15"));
mapboxMap.addLayer(layer);
// loop refresh geojson
handler = new Handler();
runnable = new RefreshGeoJsonRunnable(mapboxMap, handler);
handler.postDelayed(runnable, 2000);
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
handler.removeCallbacks(runnable);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private static class RefreshGeoJsonRunnable implements Runnable {
private MapView mapView;
private MapboxMap mapboxMap;
private Handler handler;
private Runnable runnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_default);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
RefreshGeoJsonRunnable(MapboxMap mapboxMap, Handler handler) {
this.mapboxMap = mapboxMap;
this.handler = handler;
}
@Override
public void onMapReady(@NonNull final MapboxMap map) {
mapboxMap = map;
// add source
try {
mapboxMap.addSource(new GeoJsonSource(ID_GEOJSON_SOURCE, new URL(URL_GEOJSON_SOURCE)));
}catch (MalformedURLException e){
Timber.e("Invalid URL", e);
}
// add layer
SymbolLayer layer = new SymbolLayer(ID_GEOJSON_LAYER, ID_GEOJSON_SOURCE);
layer.setProperties(iconImage("rocket-15"));
mapboxMap.addLayer(layer);
// loop refresh geojson
handler = new Handler();
runnable = new RefreshGeoJsonRunnable(mapboxMap, handler);
handler.postDelayed(runnable, 2000);
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
handler.removeCallbacks(runnable);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private static class RefreshGeoJsonRunnable implements Runnable {
private MapboxMap mapboxMap;
private Handler handler;
RefreshGeoJsonRunnable(MapboxMap mapboxMap, Handler handler) {
this.mapboxMap = mapboxMap;
this.handler = handler;
}
@Override
public void run() {
((GeoJsonSource) mapboxMap.getSource(ID_GEOJSON_SOURCE)).setUrl(URL_GEOJSON_SOURCE);
handler.postDelayed(this, 2000);
}
public void run() {
((GeoJsonSource) mapboxMap.getSource(ID_GEOJSON_SOURCE)).setUrl(URL_GEOJSON_SOURCE);
handler.postDelayed(this, 2000);
}
}
}

View File

@@ -7,7 +7,6 @@ import android.support.annotation.RawRes;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
@@ -44,7 +43,8 @@ import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import static android.os.Looper.getMainLooper;
import timber.log.Timber;
import static com.mapbox.mapboxsdk.style.layers.Filter.all;
import static com.mapbox.mapboxsdk.style.layers.Filter.eq;
import static com.mapbox.mapboxsdk.style.layers.Filter.gte;
@@ -75,508 +75,512 @@ import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.visibility;
*/
public class RuntimeStyleActivity extends AppCompatActivity {
private MapView mapView;
private MapboxMap mapboxMap;
private MapView mapView;
private MapboxMap mapboxMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_runtime_style);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_runtime_style);
setupActionBar();
setupActionBar();
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap map) {
//Store for later
mapboxMap = map;
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap map) {
//Store for later
mapboxMap = map;
//Center and Zoom (Amsterdam, zoomed to streets)
mapboxMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(52.379189, 4.899431), 14));
}
});
}
//Center and Zoom (Amsterdam, zoomed to streets)
mapboxMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(52.379189, 4.899431), 14));
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_runtime_style, menu);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_runtime_style, menu);
return true;
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.action_water_color:
setWaterColor();
return true;
case R.id.action_background_opacity:
setBackgroundOpacity();
return true;
case R.id.action_road_avoid_edges:
setRoadSymbolPlacement();
return true;
case R.id.action_layer_visibility:
setLayerInvisible();
return true;
case R.id.action_remove_layer:
removeBuildings();
return true;
case R.id.action_add_parks_layer:
addParksLayer();
return true;
case R.id.action_add_dynamic_parks_layer:
addDynamicParksLayer();
return true;
case R.id.action_add_terrain_layer:
addTerrainLayer();
return true;
case R.id.action_add_satellite_layer:
addSatelliteLayer();
return true;
case R.id.action_update_water_color_on_zoom:
updateWaterColorOnZoom();
return true;
case R.id.action_add_custom_tiles:
addCustomTileSource();
return true;
case R.id.action_fill_filter:
styleFillFilterLayer();
return true;
case R.id.action_line_filter:
styleLineFilterLayer();
return true;
case R.id.action_numeric_filter:
styleNumericFillLayer();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
private void setLayerInvisible() {
String[] roadLayers = new String[] {"water"};
for (String roadLayer : roadLayers) {
Layer layer = mapboxMap.getLayer(roadLayer);
if (layer != null) {
layer.setProperties(visibility(NONE));
}
}
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.action_water_color:
setWaterColor();
return true;
case R.id.action_background_opacity:
setBackgroundOpacity();
return true;
case R.id.action_road_avoid_edges:
setRoadSymbolPlacement();
return true;
case R.id.action_layer_visibility:
setLayerInvisible();
return true;
case R.id.action_remove_layer:
removeBuildings();
return true;
case R.id.action_add_parks_layer:
addParksLayer();
return true;
case R.id.action_add_dynamic_parks_layer:
addDynamicParksLayer();
return true;
case R.id.action_add_terrain_layer:
addTerrainLayer();
return true;
case R.id.action_add_satellite_layer:
addSatelliteLayer();
return true;
case R.id.action_update_water_color_on_zoom:
updateWaterColorOnZoom();
return true;
case R.id.action_add_custom_tiles:
addCustomTileSource();
return true;
case R.id.action_fill_filter:
styleFillFilterLayer();
return true;
case R.id.action_line_filter:
styleLineFilterLayer();
return true;
case R.id.action_numeric_filter:
styleNumericFillLayer();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setLayerInvisible() {
String[] roadLayers = new String[]{"water"};
private void setRoadSymbolPlacement() {
//Zoom so that the labels are visible first
mapboxMap.animateCamera(CameraUpdateFactory.zoomTo(14), new DefaultCallback() {
@Override
public void onFinish() {
String[] roadLayers = new String[] {"road-label-small", "road-label-medium", "road-label-large"};
for (String roadLayer : roadLayers) {
Layer layer = mapboxMap.getLayer(roadLayer);
if (layer != null) {
layer.setProperties(visibility(NONE));
}
Layer layer = mapboxMap.getLayer(roadLayer);
if (layer != null) {
layer.setProperties(symbolPlacement(SYMBOL_PLACEMENT_POINT));
}
}
}
});
}
private void setBackgroundOpacity() {
Layer background = mapboxMap.getLayer("background");
if (background != null) {
background.setProperties(backgroundOpacity(0.2f));
}
}
private void setWaterColor() {
Layer water = mapboxMap.getLayer("water");
if (water != null) {
water.setProperties(
visibility(VISIBLE),
fillColor(Color.RED)
);
} else {
Toast.makeText(RuntimeStyleActivity.this, "No water layer in this style", Toast.LENGTH_SHORT).show();
}
}
private void removeBuildings() {
//Zoom to see buildings first
try {
mapboxMap.removeLayer("building");
} catch (NoSuchLayerException noSuchLayerException) {
Toast.makeText(RuntimeStyleActivity.this, noSuchLayerException.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void addParksLayer() {
//Add a source
Source source;
try {
source = new GeoJsonSource("amsterdam-spots", readRawResource(R.raw.amsterdam));
} catch (IOException ioException) {
Toast.makeText(
RuntimeStyleActivity.this,
"Couldn't add source: " + ioException.getMessage(),
Toast.LENGTH_SHORT).show();
return;
}
private void setRoadSymbolPlacement() {
//Zoom so that the labels are visible first
mapboxMap.animateCamera(CameraUpdateFactory.zoomTo(14), new DefaultCallback() {
@Override
public void onFinish() {
String[] roadLayers = new String[]{"road-label-small", "road-label-medium", "road-label-large"};
for (String roadLayer : roadLayers) {
Layer layer = mapboxMap.getLayer(roadLayer);
if (layer != null) {
layer.setProperties(symbolPlacement(SYMBOL_PLACEMENT_POINT));
}
}
}
});
mapboxMap.addSource(source);
FillLayer layer = new FillLayer("parksLayer", "amsterdam-spots");
layer.setProperties(
fillColor(Color.RED),
fillOutlineColor(Color.BLUE),
fillOpacity(0.3f),
fillAntialias(true)
);
//Only show me parks (except westerpark with stroke-width == 3)
layer.setFilter(all(eq("type", "park"), eq("stroke-width", 2)));
mapboxMap.addLayer(layer, "building");
//layer.setPaintProperty(fillColor(Color.RED)); //XXX But not after the object is attached
//Or get the object later and set it. It's all good.
mapboxMap.getLayer("parksLayer").setProperties(fillColor(Color.RED));
//You can get a typed layer, if you're sure it's of that type. Use with care
layer = mapboxMap.getLayerAs("parksLayer");
//And get some properties
PropertyValue<Boolean> fillAntialias = layer.getFillAntialias();
Timber.d("Fill anti alias: " + fillAntialias.getValue());
layer.setProperties(fillTranslateAnchor(FILL_TRANSLATE_ANCHOR_MAP));
PropertyValue<String> fillTranslateAnchor = layer.getFillTranslateAnchor();
Timber.d("Fill translate anchor: " + fillTranslateAnchor.getValue());
PropertyValue<String> visibility = layer.getVisibility();
Timber.d("Visibility: " + visibility.getValue());
//Get a good look at it all
mapboxMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
private void addDynamicParksLayer() {
//Load some data
FeatureCollection parks;
try {
String json = readRawResource(R.raw.amsterdam);
parks = FeatureCollection.fromJson(json);
} catch (IOException ioException) {
Toast.makeText(
RuntimeStyleActivity.this,
"Couldn't add source: " + ioException.getMessage(),
Toast.LENGTH_SHORT
).show();
return;
}
private void setBackgroundOpacity() {
Layer background = mapboxMap.getLayer("background");
if (background != null) {
background.setProperties(backgroundOpacity(0.2f));
//Add an empty source
mapboxMap.addSource(new GeoJsonSource("dynamic-park-source"));
FillLayer layer = new FillLayer("dynamic-parks-layer", "dynamic-park-source");
layer.setProperties(
fillColor(Color.GREEN),
fillOutlineColor(Color.GREEN),
fillOpacity(0.8f),
fillAntialias(true)
);
//Only show me parks
layer.setFilter(all(eq("type", "park")));
mapboxMap.addLayer(layer);
//Get a good look at it all
mapboxMap.animateCamera(CameraUpdateFactory.zoomTo(12));
//Animate the parks source
animateParksSource(parks, 0);
}
private void animateParksSource(final FeatureCollection parks, final int counter) {
Handler handler = new Handler(getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (mapboxMap == null) {
return;
}
Timber.d("Updating parks source");
//change the source
int park = counter < parks.getFeatures().size() - 1 ? counter : 0;
GeoJsonSource source = mapboxMap.getSourceAs("dynamic-park-source");
if (source == null) {
Timber.e("Source not found");
Toast.makeText(RuntimeStyleActivity.this, "Source not found", Toast.LENGTH_SHORT).show();
return;
}
List<Feature> features = new ArrayList<>();
features.add(parks.getFeatures().get(park));
source.setGeoJson(FeatureCollection.fromFeatures(features));
//Re-post
animateParksSource(parks, park + 1);
}
}, counter == 0 ? 100 : 1000);
}
private void addTerrainLayer() {
//Add a source
Source source = new VectorSource("my-terrain-source", "mapbox://mapbox.mapbox-terrain-v2");
mapboxMap.addSource(source);
LineLayer layer = new LineLayer("terrainLayer", "my-terrain-source");
layer.setSourceLayer("contour");
layer.setProperties(
lineJoin(Property.LINE_JOIN_ROUND),
lineCap(Property.LINE_CAP_ROUND),
lineColor(Color.RED),
lineWidth(20f)
);
mapboxMap.addLayer(layer);
//Need to get a fresh handle
layer = mapboxMap.getLayerAs("terrainLayer");
//Make sure it's also applied after the fact
layer.setMinZoom(10);
layer.setMaxZoom(15);
layer = (LineLayer) mapboxMap.getLayer("terrainLayer");
Toast.makeText(this, String.format(
"Set min/max zoom to %s - %s", layer.getMinZoom(), layer.getMaxZoom()), Toast.LENGTH_SHORT).show();
}
private void addSatelliteLayer() {
//Add a source
Source source = new RasterSource("my-raster-source", "mapbox://mapbox.satellite", 512);
mapboxMap.addSource(source);
//Add a layer
mapboxMap.addLayer(new RasterLayer("satellite-layer", "my-raster-source"));
}
private void updateWaterColorOnZoom() {
FillLayer layer = mapboxMap.getLayerAs("water");
if (layer == null) {
return;
}
private void setWaterColor() {
Layer water = mapboxMap.getLayer("water");
if (water != null) {
water.setProperties(
visibility(VISIBLE),
fillColor(Color.RED)
);
//Set a zoom function to update the color of the water
layer.setProperties(fillColor(zoom(0.8f,
stop(1, fillColor(Color.GREEN)),
stop(4, fillColor(Color.BLUE)),
stop(12, fillColor(Color.RED)),
stop(20, fillColor(Color.BLACK))
)));
//do some animations to show it off properly
mapboxMap.animateCamera(CameraUpdateFactory.zoomTo(1), 1500);
PropertyValue<String> fillColor = layer.getFillColor();
Function<String> function = fillColor.getFunction();
if (function != null) {
Timber.d("Fill color base: " + function.getBase());
Timber.d("Fill color #stops: " + function.getStops().length);
if (function.getStops() != null) {
for (Stop stop : function.getStops()) {
Timber.d("Fill color #stops: " + stop);
}
}
}
}
private String readRawResource(@RawRes int rawResource) throws IOException {
InputStream is = getResources().openRawResource(rawResource);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int numRead;
while ((numRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, numRead);
}
} finally {
is.close();
}
return writer.toString();
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
}
private void addCustomTileSource() {
//Add a source
Source source = new VectorSource("custom-tile-source", new TileSet("2.1.0", "https://vector.mapzen.com/osm/all/{z}/{x}/{y}.mvt?api_key=vector-tiles-LM25tq4"));
mapboxMap.addSource(source);
//Add a layer
mapboxMap.addLayer(
new FillLayer("custom-tile-layers", "custom-tile-source")
.withSourceLayer("water")
);
}
private void styleFillFilterLayer() {
mapboxMap.setStyleUrl("asset://fill_filter_style.json");
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(31, -100), 3));
Handler handler = new Handler(getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (mapboxMap == null) {
return;
}
Timber.d("Styling filtered fill layer");
FillLayer states = (FillLayer) mapboxMap.getLayer("states");
if (states != null) {
states.setFilter(eq("name", "Texas"));
states.setProperties(
fillColor(Color.RED),
fillOpacity(0.25f)
);
} else {
Toast.makeText(RuntimeStyleActivity.this, "No water layer in this style", Toast.LENGTH_SHORT).show();
Toast.makeText(RuntimeStyleActivity.this, "No states layer in this style", Toast.LENGTH_SHORT).show();
}
}
}
}, 2000);
}
private void removeBuildings() {
//Zoom to see buildings first
try {
mapboxMap.removeLayer("building");
} catch (NoSuchLayerException noSuchLayerException) {
Toast.makeText(RuntimeStyleActivity.this, noSuchLayerException.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void styleLineFilterLayer() {
mapboxMap.setStyleUrl("asset://line_filter_style.json");
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(40, -97), 5));
private void addParksLayer() {
//Add a source
Source source;
try {
source = new GeoJsonSource("amsterdam-spots", readRawResource(R.raw.amsterdam));
} catch (IOException ioException) {
Toast.makeText(
RuntimeStyleActivity.this,
"Couldn't add source: " + ioException.getMessage(),
Toast.LENGTH_SHORT).show();
return;
Handler handler = new Handler(getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (mapboxMap == null) {
return;
}
mapboxMap.addSource(source);
Timber.d("Styling filtered line layer");
FillLayer layer = new FillLayer("parksLayer", "amsterdam-spots");
layer.setProperties(
fillColor(Color.RED),
fillOutlineColor(Color.BLUE),
fillOpacity(0.3f),
fillAntialias(true)
);
LineLayer counties = (LineLayer) mapboxMap.getLayer("counties");
//Only show me parks (except westerpark with stroke-width == 3)
layer.setFilter(all(eq("type", "park"), eq("stroke-width", 2)));
if (counties != null) {
counties.setFilter(eq("NAME10", "Washington"));
mapboxMap.addLayer(layer, "building");
//layer.setPaintProperty(fillColor(Color.RED)); //XXX But not after the object is attached
counties.setProperties(
lineColor(Color.RED),
lineOpacity(0.75f),
lineWidth(5f)
);
} else {
Toast.makeText(RuntimeStyleActivity.this, "No counties layer in this style", Toast.LENGTH_SHORT).show();
}
}
}, 2000);
}
//Or get the object later and set it. It's all good.
mapboxMap.getLayer("parksLayer").setProperties(fillColor(Color.RED));
private void styleNumericFillLayer() {
mapboxMap.setStyleUrl("asset://numeric_filter_style.json");
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(40, -97), 5));
//You can get a typed layer, if you're sure it's of that type. Use with care
layer = mapboxMap.getLayerAs("parksLayer");
//And get some properties
PropertyValue<Boolean> fillAntialias = layer.getFillAntialias();
Timber.d("Fill anti alias: " + fillAntialias.getValue());
layer.setProperties(fillTranslateAnchor(FILL_TRANSLATE_ANCHOR_MAP));
PropertyValue<String> fillTranslateAnchor = layer.getFillTranslateAnchor();
Timber.d("Fill translate anchor: " + fillTranslateAnchor.getValue());
PropertyValue<String> visibility = layer.getVisibility();
Timber.d("Visibility: " + visibility.getValue());
//Get a good look at it all
mapboxMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
private void addDynamicParksLayer() {
//Load some data
FeatureCollection parks;
try {
String json = readRawResource(R.raw.amsterdam);
parks = FeatureCollection.fromJson(json);
} catch (IOException e) {
Toast.makeText(RuntimeStyleActivity.this, "Couldn't add source: " + e.getMessage(), Toast.LENGTH_SHORT).show();
return;
Handler handler = new Handler(getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (mapboxMap == null) {
return;
}
//Add an empty source
mapboxMap.addSource(new GeoJsonSource("dynamic-park-source"));
Timber.d("Styling numeric fill layer");
FillLayer layer = new FillLayer("dynamic-parks-layer", "dynamic-park-source");
layer.setProperties(
fillColor(Color.GREEN),
fillOutlineColor(Color.GREEN),
fillOpacity(0.8f),
fillAntialias(true)
);
FillLayer regions = (FillLayer) mapboxMap.getLayer("regions");
//Only show me parks
layer.setFilter(all(eq("type", "park")));
if (regions != null) {
regions.setFilter(all(gte("HRRNUM", 200), lt("HRRNUM", 300)));
mapboxMap.addLayer(layer);
//Get a good look at it all
mapboxMap.animateCamera(CameraUpdateFactory.zoomTo(12));
//Animate the parks source
animateParksSource(parks, 0);
}
private void animateParksSource(final FeatureCollection parks, final int counter) {
Handler handler = new Handler(getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (mapboxMap == null) {
return;
}
Timber.d("Updating parks source");
//change the source
int park = counter < parks.getFeatures().size() - 1 ? counter : 0;
GeoJsonSource source = mapboxMap.getSourceAs("dynamic-park-source");
if (source == null) {
Timber.e("Source not found");
Toast.makeText(RuntimeStyleActivity.this, "Source not found", Toast.LENGTH_SHORT).show();
return;
}
List<Feature> features = new ArrayList<>();
features.add(parks.getFeatures().get(park));
source.setGeoJson(FeatureCollection.fromFeatures(features));
//Re-post
animateParksSource(parks, park + 1);
}
}, counter == 0 ? 100 : 1000);
}
private void addTerrainLayer() {
//Add a source
Source source = new VectorSource("my-terrain-source", "mapbox://mapbox.mapbox-terrain-v2");
mapboxMap.addSource(source);
LineLayer layer = new LineLayer("terrainLayer", "my-terrain-source");
layer.setSourceLayer("contour");
layer.setProperties(
lineJoin(Property.LINE_JOIN_ROUND),
lineCap(Property.LINE_CAP_ROUND),
lineColor(Color.RED),
lineWidth(20f)
);
mapboxMap.addLayer(layer);
//Need to get a fresh handle
layer = mapboxMap.getLayerAs("terrainLayer");
//Make sure it's also applied after the fact
layer.setMinZoom(10);
layer.setMaxZoom(15);
layer = (LineLayer) mapboxMap.getLayer("terrainLayer");
Toast.makeText(this, String.format(
"Set min/max zoom to %s - %s", layer.getMinZoom(), layer.getMaxZoom()), Toast.LENGTH_SHORT).show();
}
private void addSatelliteLayer() {
//Add a source
Source source = new RasterSource("my-raster-source", "mapbox://mapbox.satellite", 512);
mapboxMap.addSource(source);
//Add a layer
mapboxMap.addLayer(new RasterLayer("satellite-layer", "my-raster-source"));
}
private void updateWaterColorOnZoom() {
FillLayer layer = mapboxMap.getLayerAs("water");
if (layer == null) {
return;
regions.setProperties(
fillColor(Color.BLUE),
fillOpacity(0.5f)
);
} else {
Toast.makeText(RuntimeStyleActivity.this, "No regions layer in this style", Toast.LENGTH_SHORT).show();
}
}
}, 2000);
}
//Set a zoom function to update the color of the water
layer.setProperties(fillColor(zoom(0.8f,
stop(1, fillColor(Color.GREEN)),
stop(4, fillColor(Color.BLUE)),
stop(12, fillColor(Color.RED)),
stop(20, fillColor(Color.BLACK))
)));
private static class DefaultCallback implements MapboxMap.CancelableCallback {
//do some animations to show it off properly
mapboxMap.animateCamera(CameraUpdateFactory.zoomTo(1), 1500);
PropertyValue<String> fillColor = layer.getFillColor();
Function<String> function = fillColor.getFunction();
if (function != null) {
Timber.d("Fill color base: " + function.getBase());
Timber.d("Fill color #stops: " + function.getStops().length);
if (function.getStops() != null) {
for (Stop stop : function.getStops()) {
Timber.d("Fill color #stops: " + stop);
}
}
}
@Override
public void onCancel() {
//noop
}
private String readRawResource(@RawRes int rawResource) throws IOException {
InputStream is = getResources().openRawResource(rawResource);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
}
private void addCustomTileSource() {
//Add a source
Source source = new VectorSource("custom-tile-source", new TileSet("2.1.0", "https://vector.mapzen.com/osm/all/{z}/{x}/{y}.mvt?api_key=vector-tiles-LM25tq4"));
mapboxMap.addSource(source);
//Add a layer
mapboxMap.addLayer(
new FillLayer("custom-tile-layers", "custom-tile-source")
.withSourceLayer("water")
);
}
private void styleFillFilterLayer() {
mapboxMap.setStyleUrl("asset://fill_filter_style.json");
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(31, -100), 3));
Handler handler = new Handler(getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (mapboxMap == null) {
return;
}
Timber.d("Styling filtered fill layer");
FillLayer states = (FillLayer) mapboxMap.getLayer("states");
if (states != null) {
states.setFilter(eq("name", "Texas"));
states.setProperties(
fillColor(Color.RED),
fillOpacity(0.25f)
);
} else {
Toast.makeText(RuntimeStyleActivity.this, "No states layer in this style", Toast.LENGTH_SHORT).show();
}
}
}, 2000);
}
private void styleLineFilterLayer() {
mapboxMap.setStyleUrl("asset://line_filter_style.json");
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(40, -97), 5));
Handler handler = new Handler(getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (mapboxMap == null) {
return;
}
Timber.d("Styling filtered line layer");
LineLayer counties = (LineLayer) mapboxMap.getLayer("counties");
if (counties != null) {
counties.setFilter(eq("NAME10", "Washington"));
counties.setProperties(
lineColor(Color.RED),
lineOpacity(0.75f),
lineWidth(5f)
);
} else {
Toast.makeText(RuntimeStyleActivity.this, "No counties layer in this style", Toast.LENGTH_SHORT).show();
}
}
}, 2000);
}
private void styleNumericFillLayer() {
mapboxMap.setStyleUrl("asset://numeric_filter_style.json");
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(40, -97), 5));
Handler handler = new Handler(getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (mapboxMap == null) {
return;
}
Timber.d("Styling numeric fill layer");
FillLayer regions = (FillLayer) mapboxMap.getLayer("regions");
if (regions != null) {
regions.setFilter(all(gte("HRRNUM", 200), lt("HRRNUM", 300)));
regions.setProperties(
fillColor(Color.BLUE),
fillOpacity(0.5f)
);
} else {
Toast.makeText(RuntimeStyleActivity.this, "No regions layer in this style", Toast.LENGTH_SHORT).show();
}
}
}, 2000);
}
private static class DefaultCallback implements MapboxMap.CancelableCallback {
@Override
public void onCancel() {
//noop
}
@Override
public void onFinish() {
//noop
}
@Override
public void onFinish() {
//noop
}
}
}

View File

@@ -13,68 +13,68 @@ import com.mapbox.mapboxsdk.testapp.R;
*/
public class RuntimeStyleTestActivity extends AppCompatActivity {
public MapView mapView;
private MapboxMap mapboxMap;
public MapView mapView;
private MapboxMap mapboxMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_runtime_style);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_runtime_style);
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap mapboxMap) {
RuntimeStyleTestActivity.this.mapboxMap = mapboxMap;
}
});
}
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap mapboxMap) {
RuntimeStyleTestActivity.this.mapboxMap = mapboxMap;
}
});
}
public MapboxMap getMapboxMap() {
return mapboxMap;
}
public MapboxMap getMapboxMap() {
return mapboxMap;
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}

View File

@@ -21,80 +21,80 @@ import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.visibility;
*/
public class RuntimeStyleTimingTestActivity extends AppCompatActivity {
public MapView mapView;
private MapboxMap mapboxMap;
public MapView mapView;
private MapboxMap mapboxMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_runtime_style);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_runtime_style);
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap mapboxMap) {
RuntimeStyleTimingTestActivity.this.mapboxMap = mapboxMap;
VectorSource museums = new VectorSource("museums_source", "mapbox://mapbox.2opop9hr");
mapboxMap.addSource(museums);
//Initialize map as normal
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap mapboxMap) {
RuntimeStyleTimingTestActivity.this.mapboxMap = mapboxMap;
VectorSource museums = new VectorSource("museums_source", "mapbox://mapbox.2opop9hr");
mapboxMap.addSource(museums);
CircleLayer museumsLayer = new CircleLayer("museums", "museums_source");
museumsLayer.setSourceLayer("museum-cusco");
museumsLayer.setProperties(
visibility(VISIBLE),
circleRadius(8f),
circleColor(Color.argb(1, 55, 148, 179))
);
CircleLayer museumsLayer = new CircleLayer("museums", "museums_source");
museumsLayer.setSourceLayer("museum-cusco");
museumsLayer.setProperties(
visibility(VISIBLE),
circleRadius(8f),
circleColor(Color.argb(1, 55, 148, 179))
);
mapboxMap.addLayer(museumsLayer);
}
});
}
mapboxMap.addLayer(museumsLayer);
}
});
}
public MapboxMap getMapboxMap() {
return mapboxMap;
}
public MapboxMap getMapboxMap() {
return mapboxMap;
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}

View File

@@ -9,7 +9,6 @@ import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import timber.log.Timber;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
@@ -30,8 +29,7 @@ import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleRadius;
import timber.log.Timber;
/**
* Example on how to use a file:// resource for the style.json
@@ -88,10 +86,10 @@ public class StyleFileActivity extends AppCompatActivity {
cacheStyleFile.createNewFile();
Timber.i("Writing style file to: " + cacheStyleFile.getAbsolutePath());
writeToFile(cacheStyleFile, readRawResource(R.raw.local_style));
} catch (Exception e) {
} catch (Exception exception) {
Toast.makeText(StyleFileActivity.this, "Could not create style file in cache dir", Toast.LENGTH_SHORT).show();
}
return 1l;
return 1L;
}
protected void onPostExecute(Long result) {
@@ -105,9 +103,9 @@ public class StyleFileActivity extends AppCompatActivity {
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
int numRead;
while ((numRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, numRead);
}
} finally {
is.close();

View File

@@ -18,7 +18,6 @@ import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.style.layers.Layer;
import com.mapbox.mapboxsdk.style.layers.SymbolLayer;
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import com.mapbox.mapboxsdk.testapp.R;
@@ -29,8 +28,6 @@ import com.mapbox.services.commons.geojson.Point;
import java.util.Arrays;
import java.util.List;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleRadius;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconAllowOverlap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconSize;
@@ -44,171 +41,175 @@ import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textSize;
*/
public class SymbolLayerActivity extends AppCompatActivity implements MapboxMap.OnMapClickListener {
public static final String MARKER_SOURCE = "marker-source";
public static final String MARKER_LAYER = "marker-layer";
private MapboxMap mapboxMap;
private MapView mapView;
public static final String MARKER_SOURCE = "marker-source";
public static final String MARKER_LAYER = "marker-layer";
private MapboxMap mapboxMap;
private MapView mapView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_symbollayer);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_symbollayer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull final MapboxMap map) {
mapboxMap = map;
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull final MapboxMap map) {
mapboxMap = map;
//Add a image for the makers
mapboxMap.addImage("my-marker-image", BitmapFactory.decodeResource(SymbolLayerActivity.this.getResources(), R.drawable.mapbox_marker_icon_default));
//Add a image for the makers
mapboxMap.addImage(
"my-marker-image",
BitmapFactory.decodeResource(SymbolLayerActivity.this.getResources(),
R.drawable.mapbox_marker_icon_default)
);
//Add a source
FeatureCollection markers = FeatureCollection.fromFeatures(new Feature[]{
Feature.fromGeometry(Point.fromCoordinates(new double[]{4.91638, 52.35673}), featureProperties("Marker 1")),
Feature.fromGeometry(Point.fromCoordinates(new double[]{4.91638, 52.34673}), featureProperties("Marker 2"))
});
mapboxMap.addSource(new GeoJsonSource(MARKER_SOURCE, markers));
//Add the symbol-layer
mapboxMap.addLayer(
new SymbolLayer(MARKER_LAYER, MARKER_SOURCE)
.withProperties(
iconImage("my-marker-image"),
iconAllowOverlap(true),
textField("{title}"),
textColor(Color.RED),
textSize(10f)
)
);
//Show
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(52.35273, 4.91638), 14));
//Set a click-listener so we can manipulate the map
mapboxMap.setOnMapClickListener(SymbolLayerActivity.this);
}
//Add a source
FeatureCollection markers = FeatureCollection.fromFeatures(new Feature[] {
Feature.fromGeometry(Point.fromCoordinates(new double[] {4.91638, 52.35673}), featureProperties("Marker 1")),
Feature.fromGeometry(Point.fromCoordinates(new double[] {4.91638, 52.34673}), featureProperties("Marker 2"))
});
mapboxMap.addSource(new GeoJsonSource(MARKER_SOURCE, markers));
//Add the symbol-layer
mapboxMap.addLayer(
new SymbolLayer(MARKER_LAYER, MARKER_SOURCE)
.withProperties(
iconImage("my-marker-image"),
iconAllowOverlap(true),
textField("{title}"),
textColor(Color.RED),
textSize(10f)
)
);
//Show
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(52.35273, 4.91638), 14));
//Set a click-listener so we can manipulate the map
mapboxMap.setOnMapClickListener(SymbolLayerActivity.this);
}
});
}
@Override
public void onMapClick(@NonNull LatLng point) {
//Query which features are clicked
PointF screenLoc = mapboxMap.getProjection().toScreenLocation(point);
List<Feature> features = mapboxMap.queryRenderedFeatures(screenLoc, MARKER_LAYER);
SymbolLayer layer = mapboxMap.getLayerAs(MARKER_LAYER);
if (features.size() == 0) {
//Reset
layer.setProperties(iconSize(1f));
} else {
layer.setProperties(iconSize(3f));
}
}
@Override
public void onMapClick(@NonNull LatLng point) {
//Query which features are clicked
PointF screenLoc = mapboxMap.getProjection().toScreenLocation(point);
List<Feature> features = mapboxMap.queryRenderedFeatures(screenLoc, MARKER_LAYER);
private void toggleTextSize() {
SymbolLayer layer = mapboxMap.getLayerAs(MARKER_LAYER);
layer.setProperties(layer.getTextSize().getValue() > 10 ? textSize(10f) : textSize(20f));
}
SymbolLayer layer = mapboxMap.getLayerAs(MARKER_LAYER);
if (features.size() == 0) {
//Reset
layer.setProperties(iconSize(1f));
} else {
layer.setProperties(iconSize(3f));
}
private void toggleTextField() {
SymbolLayer layer = mapboxMap.getLayerAs(MARKER_LAYER);
layer.setProperties("{title}".equals(layer.getTextField().getValue()) ? textField("āA") : textField("{title}"));
}
private void toggleTextFont() {
SymbolLayer layer = mapboxMap.getLayerAs(MARKER_LAYER);
String[] fonts = layer.getTextFont().getValue();
if (fonts == null || fonts.length == 0 || Arrays.asList(fonts).contains("Arial Unicode MS Regular")) {
layer.setProperties(textFont(new String[] {"DIN Offc Pro Bold", "Arial Unicode MS Bold"}));
} else {
layer.setProperties(textFont(new String[] {"DIN Offc Pro Medium", "Arial Unicode MS Regular"}));
}
}
private void toggleTextSize() {
SymbolLayer layer = mapboxMap.getLayerAs(MARKER_LAYER);
layer.setProperties(layer.getTextSize().getValue() > 10 ? textSize(10f) : textSize(20f));
}
private JsonObject featureProperties(String title) {
JsonObject object = new JsonObject();
object.add("title", new JsonPrimitive(title));
return object;
}
private void toggleTextField() {
SymbolLayer layer = mapboxMap.getLayerAs(MARKER_LAYER);
layer.setProperties("{title}".equals(layer.getTextField().getValue()) ? textField("āA") : textField("{title}"));
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
private void toggleTextFont() {
SymbolLayer layer = mapboxMap.getLayerAs(MARKER_LAYER);
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
String[] fonts = layer.getTextFont().getValue();
if (fonts == null || fonts.length == 0 || Arrays.asList(fonts).contains("Arial Unicode MS Regular")) {
layer.setProperties(textFont(new String[]{"DIN Offc Pro Bold", "Arial Unicode MS Bold"}));
} else {
layer.setProperties(textFont(new String[]{"DIN Offc Pro Medium", "Arial Unicode MS Regular"}));
}
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
private JsonObject featureProperties(String title) {
JsonObject object = new JsonObject();
object.add("title", new JsonPrimitive(title));
return object;
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_symbol_layer, menu);
return true;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_symbol_layer, menu);
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.action_toggle_text_size:
toggleTextSize();
return true;
case R.id.action_toggle_text_field:
toggleTextField();
return true;
case R.id.action_toggle_text_font:
toggleTextFont();
return true;
default:
return super.onOptionsItemSelected(item);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.action_toggle_text_size:
toggleTextSize();
return true;
case R.id.action_toggle_text_field:
toggleTextField();
return true;
case R.id.action_toggle_text_font:
toggleTextFont();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
}

View File

@@ -29,154 +29,154 @@ import com.mapbox.mapboxsdk.testapp.R;
public class MyLocationDrawableActivity extends AppCompatActivity implements LocationListener {
private static final int PERMISSIONS_LOCATION = 0;
private static final int PERMISSIONS_LOCATION = 0;
private MapView mapView;
private MapboxMap mapboxMap;
private MapView mapView;
private MapboxMap mapboxMap;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_location_customization);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_location_customization);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
findViewById(R.id.progress).setVisibility(View.GONE);
MapboxMapOptions mapboxMapOptions = new MapboxMapOptions();
mapboxMapOptions.styleUrl(Style.MAPBOX_STREETS);
// configure MyLocationView drawables
mapboxMapOptions.myLocationForegroundDrawable(ContextCompat.getDrawable(this, R.drawable.ic_chelsea));
mapboxMapOptions.myLocationBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.ic_arsenal));
mapboxMapOptions.myLocationForegroundTintColor(Color.GREEN);
mapboxMapOptions.myLocationBackgroundTintColor(Color.YELLOW);
mapboxMapOptions.myLocationBackgroundPadding(new int[]{0, 0,
(int) getResources().getDimension(R.dimen.locationview_background_drawable_padding),
(int) getResources().getDimension(R.dimen.locationview_background_drawable_padding)});
mapboxMapOptions.myLocationAccuracyTint(Color.RED);
mapboxMapOptions.myLocationAccuracyAlpha(155);
mapView = new MapView(this, mapboxMapOptions);
mapView.setId(R.id.mapView);
ViewGroup parent = (ViewGroup) findViewById(R.id.container);
parent.addView(mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
toggleGps(true);
}
});
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
public void toggleGps(boolean enableGps) {
if (enableGps) {
if ((ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
|| (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_LOCATION);
} else {
enableLocation(true);
}
} else {
enableLocation(false);
}
}
findViewById(R.id.progress).setVisibility(View.GONE);
private void enableLocation(boolean enabled) {
if (enabled) {
mapboxMap.setMyLocationEnabled(true);
Location location = mapboxMap.getMyLocation();
if (location != null) {
onLocationChanged(location);
} else {
LocationServices.getLocationServices(this).addLocationListener(this);
}
} else {
mapboxMap.setMyLocationEnabled(false);
}
}
MapboxMapOptions mapboxMapOptions = new MapboxMapOptions();
mapboxMapOptions.styleUrl(Style.MAPBOX_STREETS);
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSIONS_LOCATION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
enableLocation(true);
}
}
}
// configure MyLocationView drawables
mapboxMapOptions.myLocationForegroundDrawable(ContextCompat.getDrawable(this, R.drawable.ic_chelsea));
mapboxMapOptions.myLocationBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.ic_arsenal));
mapboxMapOptions.myLocationForegroundTintColor(Color.GREEN);
mapboxMapOptions.myLocationBackgroundTintColor(Color.YELLOW);
mapboxMapOptions.myLocationBackgroundPadding(new int[] {0, 0,
(int) getResources().getDimension(R.dimen.locationview_background_drawable_padding),
(int) getResources().getDimension(R.dimen.locationview_background_drawable_padding)});
@Override
public void onLocationChanged(Location location) {
if (mapboxMap != null) {
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location), 14));
}
}
mapboxMapOptions.myLocationAccuracyTint(Color.RED);
mapboxMapOptions.myLocationAccuracyAlpha(155);
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
mapView = new MapView(this, mapboxMapOptions);
mapView.setId(R.id.mapView);
ViewGroup parent = (ViewGroup) findViewById(R.id.container);
parent.addView(mapView);
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
toggleGps(true);
}
});
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
public void toggleGps(boolean enableGps) {
if (enableGps) {
if ((ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
|| (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_LOCATION);
} else {
enableLocation(true);
}
} else {
enableLocation(false);
}
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
private void enableLocation(boolean enabled) {
if (enabled) {
mapboxMap.setMyLocationEnabled(true);
Location location = mapboxMap.getMyLocation();
if (location != null) {
onLocationChanged(location);
} else {
LocationServices.getLocationServices(this).addLocationListener(this);
}
} else {
mapboxMap.setMyLocationEnabled(false);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSIONS_LOCATION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
enableLocation(true);
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
@Override
public void onLocationChanged(Location location) {
if (mapboxMap != null) {
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location), 14));
}
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

View File

@@ -32,217 +32,217 @@ import com.mapbox.mapboxsdk.testapp.R;
public class MyLocationTintActivity extends AppCompatActivity implements LocationListener {
private MapView mapView;
private MapboxMap mapboxMap;
private boolean firstRun;
private MapView mapView;
private MapboxMap mapboxMap;
private boolean firstRun;
private static final int PERMISSIONS_LOCATION = 0;
private static final int PERMISSIONS_LOCATION = 0;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_location_dot_color);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_location_dot_color);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
// enable location updates
toggleGps(!mapboxMap.isMyLocationEnabled());
// add some padding
final MyLocationViewSettings myLocationViewSettings = mapboxMap.getMyLocationViewSettings();
myLocationViewSettings.setPadding(0, 500, 0, 0);
// enable tracking
TrackingSettings settings = mapboxMap.getTrackingSettings();
settings.setDismissLocationTrackingOnGesture(false);
settings.setMyLocationTrackingMode(MyLocationTracking.TRACKING_FOLLOW);
// handle default button clicks
ViewUtils.attachClickListener(
MyLocationTintActivity.this,
R.id.default_user_dot_coloring_button,
new View.OnClickListener() {
@Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
// enable location updates
toggleGps(!mapboxMap.isMyLocationEnabled());
// add some padding
final MyLocationViewSettings myLocationViewSettings = mapboxMap.getMyLocationViewSettings();
myLocationViewSettings.setPadding(0, 500, 0, 0);
// enable tracking
TrackingSettings settings = mapboxMap.getTrackingSettings();
settings.setDismissLocationTrackingOnGesture(false);
settings.setMyLocationTrackingMode(MyLocationTracking.TRACKING_FOLLOW);
// handle default button clicks
ViewUtils.attachClickListener(
MyLocationTintActivity.this,
R.id.default_user_dot_coloring_button,
new View.OnClickListener() {
@Override
public void onClick(View view) {
myLocationViewSettings.setAccuracyTintColor(ContextCompat.getColor(
MyLocationTintActivity.this, R.color.mapbox_my_location_ring));
myLocationViewSettings.setForegroundTintColor(ContextCompat.getColor(
MyLocationTintActivity.this, R.color.mapbox_blue));
myLocationViewSettings.setBackgroundTintColor(Color.WHITE);
}
});
// handle tint user dot button clicks
ViewUtils.attachClickListener(
MyLocationTintActivity.this,
R.id.tint_user_dot_button,
new View.OnClickListener() {
@Override
public void onClick(View view) {
myLocationViewSettings.setAccuracyTintColor(
ContextCompat.getColor(MyLocationTintActivity.this, R.color.mapbox_green));
myLocationViewSettings.setForegroundTintColor(
ContextCompat.getColor(MyLocationTintActivity.this, R.color.mapbox_green));
myLocationViewSettings.setBackgroundTintColor(Color.WHITE);
}
});
// handle tint accuracy ring button clicks
ViewUtils.attachClickListener(
MyLocationTintActivity.this,
R.id.user_accuracy_ring_tint_button,
new View.OnClickListener() {
@Override
public void onClick(View view) {
myLocationViewSettings.setAccuracyTintColor(
ContextCompat.getColor(MyLocationTintActivity.this, R.color.accent));
myLocationViewSettings.setForegroundTintColor(
ContextCompat.getColor(MyLocationTintActivity.this, R.color.mapbox_blue));
myLocationViewSettings.setBackgroundTintColor(Color.WHITE);
}
});
ViewUtils.attachClickListener(
MyLocationTintActivity.this,
R.id.user_dot_transparent_button,
new View.OnClickListener() {
@Override
public void onClick(View view) {
myLocationViewSettings.setForegroundTintColor(Color.TRANSPARENT);
myLocationViewSettings.setBackgroundTintColor(Color.TRANSPARENT);
}
}
);
public void onClick(View view) {
myLocationViewSettings.setAccuracyTintColor(ContextCompat.getColor(
MyLocationTintActivity.this, R.color.mapbox_blue));
myLocationViewSettings.setForegroundTintColor(ContextCompat.getColor(
MyLocationTintActivity.this, R.color.mapbox_blue));
myLocationViewSettings.setBackgroundTintColor(Color.WHITE);
}
});
});
}
@Override
public void onLocationChanged(Location location) {
if (mapboxMap != null && firstRun) {
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location), 15));
firstRun = false;
}
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
LocationServices.getLocationServices(this).addLocationListener(this);
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
LocationServices.getLocationServices(this).removeLocationListener(this);
mapView.onStop();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@UiThread
public void toggleGps(boolean enableGps) {
if (enableGps) {
if ((ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
|| (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_LOCATION);
} else {
enableLocation(true);
// handle tint user dot button clicks
ViewUtils.attachClickListener(
MyLocationTintActivity.this,
R.id.tint_user_dot_button,
new View.OnClickListener() {
@Override
public void onClick(View view) {
myLocationViewSettings.setAccuracyTintColor(
ContextCompat.getColor(MyLocationTintActivity.this, R.color.mapbox_green));
myLocationViewSettings.setForegroundTintColor(
ContextCompat.getColor(MyLocationTintActivity.this, R.color.mapbox_green));
myLocationViewSettings.setBackgroundTintColor(Color.WHITE);
}
} else {
enableLocation(false);
}
}
});
private void enableLocation(boolean enabled) {
if (enabled) {
mapboxMap.setMyLocationEnabled(true);
if (mapboxMap.getMyLocation() != null) {
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mapboxMap.getMyLocation().getLatitude(),
mapboxMap.getMyLocation().getLongitude()), 15));
// handle tint accuracy ring button clicks
ViewUtils.attachClickListener(
MyLocationTintActivity.this,
R.id.user_accuracy_ring_tint_button,
new View.OnClickListener() {
@Override
public void onClick(View view) {
myLocationViewSettings.setAccuracyTintColor(
ContextCompat.getColor(MyLocationTintActivity.this, R.color.accent));
myLocationViewSettings.setForegroundTintColor(
ContextCompat.getColor(MyLocationTintActivity.this, R.color.mapbox_blue));
myLocationViewSettings.setBackgroundTintColor(Color.WHITE);
}
} else {
mapboxMap.setMyLocationEnabled(false);
}
}
});
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSIONS_LOCATION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
enableLocation(true);
ViewUtils.attachClickListener(
MyLocationTintActivity.this,
R.id.user_dot_transparent_button,
new View.OnClickListener() {
@Override
public void onClick(View view) {
myLocationViewSettings.setForegroundTintColor(Color.TRANSPARENT);
myLocationViewSettings.setBackgroundTintColor(Color.TRANSPARENT);
}
}
}
}
);
}
});
private static class ViewUtils {
}
public static void attachClickListener(
@NonNull Activity activity, @IdRes int buttonId, @Nullable View.OnClickListener clickListener) {
View view = activity.findViewById(buttonId);
if (view != null) {
view.setOnClickListener(clickListener);
}
}
@Override
public void onLocationChanged(Location location) {
if (mapboxMap != null && firstRun) {
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location), 15));
firstRun = false;
}
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
LocationServices.getLocationServices(this).addLocationListener(this);
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
LocationServices.getLocationServices(this).removeLocationListener(this);
mapView.onStop();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@UiThread
public void toggleGps(boolean enableGps) {
if (enableGps) {
if ((ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
|| (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_LOCATION);
} else {
enableLocation(true);
}
} else {
enableLocation(false);
}
}
private void enableLocation(boolean enabled) {
if (enabled) {
mapboxMap.setMyLocationEnabled(true);
if (mapboxMap.getMyLocation() != null) {
mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mapboxMap.getMyLocation().getLatitude(),
mapboxMap.getMyLocation().getLongitude()), 15));
}
} else {
mapboxMap.setMyLocationEnabled(false);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSIONS_LOCATION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
enableLocation(true);
}
}
}
private static class ViewUtils {
public static void attachClickListener(
@NonNull Activity activity, @IdRes int buttonId, @Nullable View.OnClickListener clickListener) {
View view = activity.findViewById(buttonId);
if (view != null) {
view.setOnClickListener(clickListener);
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More