Gestures

As you may have seen from the Get Started example, a map view by default supports all common map gestures, for example, pinch and double tap to zoom in. The following table is a summary of the available gestures and their corresponding default behavior on the map.

Tap the screen with one finger. This gesture does not have a predefined map action.
To zoom the map in a fixed amount, tap the screen twice with one finger.
Press and hold one finger to the screen. This gesture does not have a predefined map action.
To move the map, press and hold one finger to the screen, and move it in any direction. The map will keep moving with a little momentum after the finger was lifted.
To tilt the map, press and hold two fingers to the screen, and move them in a vertical direction. No behavior is predefined for other directions.
To zoom out a fixed amount, tap the screen with two fingers.
To zoom in or out continuously, press and hold two fingers to the screen, and increase or decrease the distance between them.

The HERE SDK for Android provides support for the following gestures:

  • Tap: TapListener
  • Double Tap: DoubleTapListener
  • Long Press: LongPressListener
  • Pan: PanListener
  • Two Finger Pan: TwoFingerPanListener
  • Two Finger Tap: TwoFingerTapListener
  • Pinch Rotate: PinchRotateListener

Each listener provides a dedicated callback that informs you whenever the user performs an action that could be detected, for example, the beginning or the end of that specific gesture. Usually, you will want to add a specific behavior to your application after a gesture was detected, like placing a map marker after a long press.

Note that only one listener can be set at a time for the same gesture.

Control map actions

Setting a listener does not affect the default map behavior of the gestures. That can be controlled independently. By default, all default behaviors, such as zooming in when double tapping the map, are enabled.

For example, you can disable the default map gesture behavior for double tap (zooms in) and two finger tap (zooms out) as follows:

mapView.getGestures().disableDefaultAction(GestureType.DOUBLE_TAP);
mapView.getGestures().disableDefaultAction(GestureType.TWO_FINGER_TAP);

When disabling a default map action, you can still listen for the gesture event. This can be useful when you want to turn off the default action of a gesture to implement your own zooming behavior, for example. All gestures - except for tap and long press - provide a default map action. More details can be found in the overview above.

To bring back the default map gesture behavior, you can call:

mapView.getGestures().enableDefaultAction(GestureType.DOUBLE_TAP);
mapView.getGestures().enableDefaultAction(GestureType.TWO_FINGER_TAP);

Attach a gesture listener

Let's see an example of how a gesture listener can be attached to the map view. The map view provides specific setters for each gesture. As soon as you set a listener, it will receive all related events for that gesture via the dedicated callback, which is onTap() in case of a TapListener:

private void setTapGestureHandler(MapViewLite mapView) {
    mapView.getGestures().setTapListener(new TapListener() {
        @Override
        public void onTap(@NonNull Point2D touchPoint) {
            GeoCoordinates geoCoordinates = mapView.getCamera().viewToGeoCoordinates(touchPoint);
            Log.d(TAG, "Tap at: " + geoCoordinates);
        }
    });
}

As soon as you set a listener, you will begin to receive notifications that gestures have been detected.

The touchPoint specifies the point from the device's screen where the gesture happened. By calling mapView.getCamera().viewToGeoCoordinates(touchPoint), you can convert the pixels into geographic coordinates (as shown above).

Likewise, to stop listening, we can simply call:

mapView.getGestures().setTapListener(null);

For continuous gestures (like long press, pinch, pan, two finger pan), the BEGIN gesture state will indicate that the gesture was detected. While the finger(s) still touch the display, you may receive UPDATE states, until the END state indicates that a finger has been lifted:

private void setLongPressGestureHandler(MapViewLite mapView) {
    mapView.getGestures().setLongPressListener(new LongPressListener() {
        @Override
        public void onLongPress(@NonNull GestureState gestureState, @NonNull Point2D touchPoint) {
            GeoCoordinates geoCoordinates = mapView.getCamera().viewToGeoCoordinates(touchPoint);

            if (gestureState == GestureState.BEGIN) {
                Log.d(TAG, "LongPress detected at: " + geoCoordinates);
            }

            if (gestureState == GestureState.UPDATE) {
                Log.d(TAG, "LongPress update at: " + geoCoordinates);
            }

            if (gestureState == GestureState.END) {
                Log.d(TAG, "LongPress finger lifted at: " + geoCoordinates);
            }
        }
    });
}

For example, a user may still keep his finger on the screen after a long press event was detected - or even move it around. However, only the BEGIN event will mark the point in time, when the long press gesture was detected.

A long press gesture can be useful to place a map marker on the map. An example of this can be seen in the Search example app.

Note that for the non-continuous gestures (like tap, double tap, two finger tap), no GestureState is needed to handle the gesture event.

Tutorial: Customize map actions

As we have already seen, by default, a double tap gesture zooms in the map in discrete steps - for example, from city level closer to street level. You can disable such default map gesture actions to implement your own behaviors - or you can add your desired actions to existing behaviors.

If needed, it is also possible to combine platform gesture handling with the HERE SDK gesture detection. The HERE SDK does not provide all kind of low level gesture events as it is primarily focusing on the common map gestures - for your convenience. If you need more granular control, you can always combine the gesture handling available from the HERE SDK with the native Android gesture detection.

For this tutorial, we want to show how to enable custom zoom animations: The map should zoom gradually in or out after the user has performed a double tap or a two finger tap gesture. The zoom animation should slow down after a short time.

Add custom zoom behavior

Let's start with the animation. For this we can use Android's animation framework and a ValueAnimator that allows us to interpolate between certain start and end value.

For convenience, we create a new class called GestureMapAnimator, that should handle all gesture related animations. It requires a reference to the map's Camera instance, as the map needs to be zoomed via the camera.

By default, the map zooms in/out in one discrete step at the location where the finger touches the map - without intermediate steps. For this tutorial, we simplify the behavior to zoom the map at the default target location - but, of course, we will add intermediate steps to introduce the desired animation. Later on we will also show how to zoom in at the finger's touch point.

Let's hook up the needed gesture events:

mapView.getGestures().disableDefaultAction(GestureType.DOUBLE_TAP);
mapView.getGestures().disableDefaultAction(GestureType.TWO_FINGER_TAP);

mapView.getGestures().setDoubleTapListener(new DoubleTapListener() {
    @Override
    public void onDoubleTap(@NonNull Point2D touchPoint) {
        // Start our custom zoom in animation.
        gestureMapAnimator.zoomIn();
    }
});

mapView.getGestures().setTwoFingerTapListener(new TwoFingerTapListener() {
    @Override
    public void onTwoFingerTap(@NonNull Point2D origin) {
        // Start our custom zoom out animation.
        gestureMapAnimator.zoomOut();
    }
});

No magic here: We simply listen for the two gesture events. We just have to make sure to disable the default zoom behavior beforehand. The zoomIn() and zoomOut() methods from above lead to a new method in our GestureMapAnimator you can see below.

// Starts the zoom in animation.
public void zoomIn() {
    startZoomAnimation(true);
}

// Starts the zoom out animation.
public void zoomOut() {
    startZoomAnimation(false);
}

The implementation inside the new GestureMapAnimator class uses a ValueAnimator:

private void startZoomAnimation(boolean zoomIn) {
    stopAnimations();

    // A new Animator that zooms the map.
    zoomValueAnimator = createZoomValueAnimator(zoomIn);

    // Start the animation.
    zoomValueAnimator.start();
}

private ValueAnimator createZoomValueAnimator(boolean zoomIn) {
    ValueAnimator zoomValueAnimator = ValueAnimator.ofFloat(0.1F, 0);
    zoomValueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
    zoomValueAnimator.addUpdateListener(animation -> {
        // Called periodically until zoomVelocity is zero.
        float zoomVelocity = (float) animation.getAnimatedValue();
        double zoom = camera.getZoomLevel();
        zoom = zoomIn ? zoom + zoomVelocity : zoom - zoomVelocity;
        camera.setZoomLevel(zoom);
    });

    long halfSecond = 500;
    zoomValueAnimator.setDuration(halfSecond);

    return zoomValueAnimator;
}

We use a ValueAnimator to interpolate the values from 0.1 to 0. These values should determine the zoom velocity. The AccelerateDecelerateInterpolator provides intermediate values with a slowing down effect at the end. The listener we set to the ValueAnimator is executed periodically until zoomVelocity reaches 0. zoomVelocity is the animated value that we can use to zoom the map. We use it as an argument to change the current zoom value from the previous frame. As zoomVelocity slowly reaches 0, the resulting zoom step will get smaller and smaller.

Note that we provide a boolean value to indicate if the map should be zoomed in or out. This enables us to use the code for both zoom cases: The only difference is that the animated value zoomVelocity is added or subtracted from the current zoom level.

The stopAnimations() method from above simply cancels any ongoing animation of the corresponding ValueAnimator instance:

public void stopAnimations() {
    if (zoomValueAnimator != null) {
        zoomValueAnimator.cancel();
    }
}

Zoom in at the touch point

Above we have simplified our custom zoom in behavior as we have ignored the touch origin. Ideally, the map should zoom in at the point where the finger has touched the screen. How to make this possible? By default, all programmatical map manipulations are based on the target anchor point which is centered on the map view. Therefore, the map zooms at the map's center location. You can read more about the target anchor point concept here.

All we have to do is to change that point to the point where the finger has touched the screen. As a result, a call to zoom the map will use this new anchor point as target. The double tap gesture already provides a Point2D instance that indicates the touch origin. Changing the target anchor point is easy - we only need to add one more line of code to our zoom in method:

public void zoomIn(MapViewLite mapView, Point2D touchPoint) {
    // Change the anchor point to zoom in at the touched point.
    camera.setTargetAnchorPoint(getAnchorPoint(mapView, touchPoint));

    startZoomAnimation(true);
}

The anchor point can be specified with normalized coordinates where (0, 0) marks the top-left corner and (1, 1) the bottom-right corner of the map view. In opposition, the touch point delivered from the double tap gesture is providing the pixel position on the map view. This requires us to calculate the new anchor using the following method:

private Anchor2D getAnchorPoint(MapViewLite mapView, Point2D mapViewPoint) {
    float normalizedX = (float) ((1F / mapView.getWidth()) * mapViewPoint.x);
    float normalizedY = (float) ((1F / mapView.getHeight()) * mapViewPoint.y);

    Anchor2D transformationCenter = new Anchor2D(normalizedX, normalizedY);
    return transformationCenter;
}

First, we need to get the pixel size of our map view. Then we can calculate the normalized touch point on that view which will make up our new Anchor2D instance. Once this new target anchor point is set, the map will smoothly zoom in at the touched location.

Since zooming out is performed using two fingers, it may be desired to perform that gesture using the map's center as target. Therefore, when stopping your animations, you may wish to optionally reset the anchor point to it's default position:

// Reset anchor point to its default location.
camera.setTargetAnchorPoint(new Anchor2D(0.5F, 0.5F));

If your application requires different anchor points, you may instead store the previous anchor point before starting the zoom animation - and reset to it after the animation has stopped. Keep in mind that the target anchor point also determines where a new map location is shown in relation to the map view - usually, this should be at the center of the view.

Now, that's it for our little excursion. Feel free to adapt the above code snippets to your own needs. For example, start by playing around with different interpolators, different animated values - or a different duration for an animation.

results matching ""

    No results matching ""