'How can I add a scale on react leaflet?
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='&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 :
I saw that :
But I didn't find any examples on how to implement that in my code...
Could you help me please ?
Solution 1:[1]
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.
Solution 2:[2]
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}}/>
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | EdgarHR |
| Solution 2 | akem |
| Solution 3 | Grzegorz T. |
