Raruto / leaflet-rotate

Leaflet plugin that allows to add rotation functionality to map tiles
GNU General Public License v3.0
77 stars 21 forks source link

How can I use this lib with react-leaflet? #16

Closed siimaoo closed 1 year ago

siimaoo commented 1 year ago

I tried to use this lib with react-leaflet but no success. I also read this and that but I can't make any working example.

Any example using react-leaflet or idea to make this works? Thanks!

Raruto commented 1 year ago

Hi @siimaoo

take a look at this codesanbox (that I forked from the other one submitted by @laurencefass in https://github.com/Raruto/leaflet-rotate/issues/9)

/**
 * DEMO URL: https://codesandbox.io/s/react-leaflet-forked-crkvt9
 * 
 * Forked from: https://codesandbox.io/s/react-leaflet-forked-me1he5
 */

import React, { Component, useEffect, useRef } from "react";
import ReactDOM from "react-dom";
import {
  MapContainer,
  TileLayer,
  Marker,
  Popup,
  useMapEvents,
  useMap
} from "react-leaflet";
import "leaflet-rotate"; // 😄 <-- you should include it as ES module if you really want something to happen...

import "../node_modules/leaflet/dist/leaflet.css";
import "./styles.css";

function MapSubscriber() {
  let map = useMap();
  useEffect(() => {
    console.log("map", map);
  }, [map]);

  return null;
}

function App() {
  let mapRef = useRef();

  let state = {
    center: [51.505, -0.091],
    zoom: 13
  };

  useEffect(() => {
    console.log("mapRef.current", mapRef);
  }, [mapRef]);
  return (
    <div>
      <MapContainer
        whenCreated={(mapInstance) => {
          mapRef.current = mapInstance;
        }}
        center={state.center}
        zoom={state.zoom}
        rotate={true}
        touchRotate={true}
        rotateControl={{
          closeOnZeroBearing: false
        }}
        bearing={30}
      >
        <MapSubscriber />
        <TileLayer
          attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.osm.org/{z}/{x}/{y}.png"
        />
        <Marker position={state.center}>
          <Popup>
            A pretty CSS3 popup. <br /> Easily customizable.
          </Popup>
        </Marker>
      </MapContainer>
    </div>
  );
}

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

Have a nice day, Raruto

laurencefass commented 1 year ago

Thats a great demo. thanks Raruto.

siimaoo commented 1 year ago

@Raruto Thanks a lot! You can't imagine how much you helped me with this simple example.