Search code examples
javascriptmapshere-api

How to achieve Google Maps-like scrolling behavior on Here Maps API for JavaScript?


I am using Here's Maps API for JavaScript and trying to achieve a scrolling behavior on mobile similar to what Google Map's API's has.

When I want to scroll by touching the map, scrolling the page should not be always prevented, only if the Map's DRAGGING behavior is disabled.

I have tried calling window.scroll() with the corresponding Y parameters extracted from pointer events, but it is not as smooth as the browser's default scrolling.

How should I use drag or some other event targeting the Map to scroll the page?


Solution

  • This code should work for you:

    let mapevents = new mapsjs.mapevents.MapEvents(map),
        behavior = new mapsjs.mapevents.Behavior(mapevents);
    
    let startY, endY = 0;
    map.addEventListener('dragstart', function(evt) {
      if (evt.currentPointer.type == 'touch' && evt.pointers.length < 2) {
        startY = evt.currentPointer.viewportY;
        behavior.disable(H.mapevents.Behavior.DRAGGING);
      }
    });
    
    map.addEventListener('drag', function(evt) {
      if (evt.currentPointer.type == 'touch' && evt.pointers.length < 2) {
        endY = evt.currentPointer.viewportY;
        window.scrollBy(0, (startY - endY));
      }
    });
    
    map.addEventListener('dragend', function(evt) {
      behavior.enable(H.mapevents.Behavior.DRAGGING);
    });
    

    In dragstart and drag callbacks the scrolling is disabled only when pointer's type is touch and number of pointers is 1. That makes it possible to zoom & pan the map with two fingers on touch device and also with mouse on desktops / laptops.

    Note, that method behavior.isEnabled(feature) doesn't disable the feature. For that you need to use behavior.disable(opt_features) See https://developer.here.com/documentation/maps/topics_api/h-mapevents-behavior.html