2

I am using react with the library leaflet but I would like to add on my map a scale in kilometers.

How can I do to do that ?

Here is my code :

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
import './styles.css';

class App extends Component {
  state = {
    center: [51.505, -0.091],
    zoom: 13,
  };

  render() {
    return (
      <div>
        <Map center={this.state.center} zoom={this.state.zoom}>
          <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={this.state.center}>
            <Popup>
              A pretty CSS3 popup. <br /> Easily customizable.
            </Popup>
          </Marker>
        </Map>
      </div>
    );
  }
}

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

And this is the link :

Map

I saw that :

Documentation

But I didn't find any examples on how to implement that in my code...

Could you help me please ?

3 Answers 3

8

If you are using the React Leaflet library, another alternative would be to import ScaleControl like so

import { ScaleControl } from 'react-leaflet' 

and then you can just add the scale by adding <ScaleControl /> inside <MapContainer></MapContainer> and add different attributes such as position. For example,

  <MapContainer>
    <ScaleControl position="topleft" />
  </MapContainer>

Finally, you can always use CSS to edit the appearance of the scale.

3

create a simple react-leaflet object

import { useEffect } from "react";
import L from "leaflet";
import { useLeafletMap } from "use-leaflet";

const MapScale = ({ options }) => {
  const map = useLeafletMap();

  useEffect(() => {
    L.control.scale(options).addTo(map);
  }, [map]);

  return null;
};

export default MapScale;

then in your main page, simply add <MapScale options={{imperial:false}}/>

2

Nothing simpler, just use it:

import { ScaleControl } from 'react-leaflet';


<ScaleControl imperial={false} />

By default, the location is in the lower left corner of the map.

Not the answer you're looking for? Browse other questions tagged or ask your own question.