Implement custom zooming in React-Mapbox-GL

Viewed 933

I am trying to achieve custom zoom behavior in React-Mapbox-GL. If user scrolls, the map doesn't zoom, only the web page is scrolling. Only if user "pinch-to-zoom", the map can zoom.

I use scrollZoom: false, which disables zooming for both actions (scrolling and "pinch-to-zoom"). Then, I added react-quick-pinch-zoom library and its onUpdate event, which helps me to add listener for "pinch-to-zoom" event.

Zooming experience is not good and I don't know how to achieve a similar zoom experience to React-Mapbox-GL.

codesandbox

import React, { useState, useCallback } from "react";
import QuickPinchZoom from "react-quick-pinch-zoom";
import ReactDOM from "react-dom";
import ReactMapboxGL from "react-mapbox-gl";

const Map = ReactMapboxGL({
  accessToken:
    "pk.eyJ1IjoiZG9ubm5lLWdyaSIsImEiOiJjanF5eHB1aDMwOG83NDVxcTd4aG0xbTcxIn0.sZBpmFCnFBApzXGsIFXh4A",
  maxZoom: 18,
  scrollZoom: false
});

const MapContainer = () => {
  const [mapZoom, setMapZoom] = useState(8);

  const onUpdate = useCallback(
    ({ scale }) => {
      if (scale === 1) {
        return;
      }
      const scaleDiff = (scale - 1) / 12;
      setMapZoom(scaleDiff + mapZoom);
    },
    [mapZoom]
  );

  return (
    <QuickPinchZoom onUpdate={onUpdate}>
      <Map
        style="mapbox://styles/mapbox/streets-v9"
        zoom={[mapZoom]}
        center={[-0.109970527, 51.52916347]}
        containerStyle={{
          position: "absolute",
          top: 0,
          left: 0,
          height: "100%",
          width: "100%"
        }}
      ></Map>
    </QuickPinchZoom>
  );
};

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <MapContainer />
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
0 Answers
Related