Reputation: 69
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 ?
Upvotes: 2
Views: 2984
Reputation: 4153
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.
Upvotes: 2
Reputation: 81
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.
Upvotes: 8
Reputation: 31
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}}/>
Upvotes: 3