Customizing react-leaflet marker icons by using font awesome
Asked Answered
H

3

15

It is more theoretical question, rather than a problem.

How to use font awesome icons as react-leaflet map marker icons?

I would like to have such an icon selector control to assign(customize) each marker icon I have got on my map. By the way I am using JSX components of Map and Marker.

Is it possible to achieve this?

Anybody have a sample pen about this? I have really googled it strongly but couldn't find any plugin but a fontawesome plugin that is working only with Leaflet 1.0.

So any idea appreciated.

Thanks in advance.

Holster answered 29/8, 2018 at 16:51 Comment(0)
D
21

For some reasons code is not getting formatted. See code on code sandbox

Here is how you can use font-awesome icons as markers.

  1. Add font-awesome CDN to your index.html

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">

  1. Use divIcon along with renderToStaticMarkup from react-dom/server to generate icon for marker. And pass this divIcon to Marker as a icon prop.

    import React, { Component } from 'react';
    import ReactDOM from 'react-dom';
    import { renderToStaticMarkup } from 'react-dom/server';
    import { divIcon } from 'leaflet';
    import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
    
    import './styles.css';
    
    class App extends Component {
      state = {
        lat: 51.505,
        lng: -0.091,
        zoom: 13,
      };
    
    render() {
        const position = [this.state.lat, this.state.lng];
        const iconMarkup = renderToStaticMarkup(<i className=" fa fa-map-marker-alt fa-3x" />);
        const customMarkerIcon = divIcon({
          html: iconMarkup,
        });
    
        return (
          <Map center={position} zoom={this.state.zoom}>
            <TileLayer
              attribution="&amp;copy <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
              url="https://{s}.tile.osm.org/{z}/{x}/{y}.png"
            />
            <Marker position={position} icon={customMarkerIcon}>
              <Popup>
                A pretty CSS3 popup. <br /> Easily customizable.
              </Popup>
            </Marker>
          </Map>
        );
      }
    }
    
    const rootElement = document.getElementById('root');
    ReactDOM.render(<App />, rootElement);
    
  2. Override divIcon default style by adding the following class to your css file

    .leaflet-div-icon {
        background: transparent;
        border: none;
    }  
    
Demand answered 1/9, 2018 at 18:52 Comment(7)
Thank you Murli . You saved me hours! Excellent answer :)Holster
One more little question: Why is the Map disappearing when it is surrounding by div tags? Do you have any idea or workaround?Holster
@H.SerhanEkinci you need to provide height and width to the div.Demand
any other solution or advice?Holster
@H.SerhanEkinci you must add .leaflet-container class to your css with height and width. Refer code sandbox style.css file.Demand
Worked like a charm:) I appreciate it.Holster
thank you man, you saved me hours of timeCinerary
C
6

For those who already use the React components of Fontawesome (FontAwesomeIcon), there is a solution that does not require importing via CDN again. It uses the same principles of Murli's answers, but instead of adding <i className=" fa fa-map-marker-alt fa-3x" />, you can convert the FontAwesomeIcon component to html and pass that into the html attribute of the divIcon. It would look like this (adapted the example of the accepted answer):

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import ReactDOMServer from 'react-dom/server';
import Leaflet from 'leaflet'
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

import './styles.css';

// FontAwesome requirements
import { faUserAstronaut } from '@fortawesome/free-solid-svg-icons'
library.add(faUserAstronaut)

class App extends Component {
  state = {
    lat: 51.505,
    lng: -0.091,
    zoom: 13,
  };

  render() {
    const position = [this.state.lat, this.state.lng];
    const iconHTML = ReactDOMServer.renderToString(<FontAwesomeIcon icon='user-astronaut' />)
    const customMarkerIcon = new Leaflet.DivIcon({
      html: iconHTML,
    });

    return (
      <Map center={position} zoom={this.state.zoom}>
        <TileLayer
          attribution="&amp;copy <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
          url="https://{s}.tile.osm.org/{z}/{x}/{y}.png"
        />
        <Marker position={position} icon={customMarkerIcon}>
          <Popup>
            A pretty CSS3 popup. <br /> Easily customizable.
          </Popup>
        </Marker>
      </Map>
    );
  }
}

const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);
Callao answered 16/12, 2020 at 10:23 Comment(1)
This is working for me, thanks! Note that by default, you will get a white square with black border behind the icon, which may not be what you want. Here is how to remove it.Albarran
S
-1

Create divIcon and insert it into icon property:

// marker-icons.js
import L from 'leaflet';

const factory = new L.divIcon({
  className: '',
  iconAnchor: [12, 25],
  labelAnchor: [-6, 0],
  popupAnchor: [0, -15],
  iconSize: [25, 41],
  html: `<span class="fa fa-industry"></span>`
});

export default { factory };

Use icon in component file:

// component.js
import { factory } from './marker-icons';

<MapContainer center={[12.23432, 87.234]} zoom={6} scrollWheelZoom={false}>
    <TileLayer attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"/>
    <Marker position={45.4534, 23.43]} icon={factory}>
        <Popup>Help text</Popup>
    </Marker>
</MapContainer>
Sinter answered 29/6, 2021 at 9:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.