Using Font Awesome icons instead of markers in Leaflet

Within this code snippet, I initially utilized data[key].category to represent the corresponding icon as a marker. However, my intention is to switch to Font Awesome icons for a more lightweight runtime experience in instances where multiple icons may need to be loaded as markers.

var Cofee= Leaflet.icon({
      iconUrl: '/img/Coffee.png',
      shadowUrl: '/img/pale-shadow.png',
      iconSize: [34, 49], 
      shadowSize: [49, 49],
      iconAnchor: [5, 62],
      shadowAnchor: [4, 62],
      popupAnchor: [12, -30]
});
var Store= Leaflet.icon({
      iconUrl: '/img/Store.png',
      shadowUrl: '/img/pale-shadow.png',
      iconSize: [34, 49], 
      shadowSize: [49, 49],
      iconAnchor: [5, 62],
      shadowAnchor: [4, 62],
      popupAnchor: [12, -30]
});
..
..
..

this.Getlatlng(currentlatlng, 9000).then(data => {
    for (var key in data) {
        Leaflet.marker(data[key].location, { icon: data[key].category })      
         .addTo(this.map).bindPopup('<h4>'+data[key].caption+'</h4>');
          markers.push([data[key].location.lat,data[key].location.lng]);
}

Answer №1

Instead of using the default marker icons, you have the option to utilize font-awesome icons in Leaflet like so:

const fontAwesomeIcon = L.divIcon({
    html: '<i class="fa fa-map-marker fa-4x"></i>',
    iconSize: [20, 20],
    className: 'myDivIcon'
});

L.marker([51.5, -0.09], { icon: fontAwesomeIcon }).addTo(map)
    .bindPopup('A stylish CSS3 popup.<br> Fully customizable.')

const map = L.map('mapid').setView([51.505, -0.09], 8);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

const fontAwesomeIcon = L.divIcon({
  html: '<i class="fa fa-map-marker fa-4x"></i>',
  iconSize: [20, 20],
  className: 'myDivIcon'
});

L.marker([51.5, -0.09], {
    icon: fontAwesomeIcon
  }).addTo(map)
  .bindPopup('A stylish CSS3 popup.<br> Fully customizable.')
#mapid {
  height: 100vh;
}

body {
  margin: 0px;
}

.leaflet-popup-close-button {
  display: none;
}

.myDivIcon {
  text-align: center;
  /* Center the text (icon) horizontally */
  line-height: 20px;
  /* Center the text (icon) vertically */
}
<link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec80898d8a808998acddc2d8c2dc">[email protected]</a>/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin="" />

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />

<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8fe3eaeee9e3eafbcfbea1bba1bf">[email protected]</a>/dist/leaflet.js" integrity="sha512-QVftwZFqvtRNi0ZyCtsznlKSWOStnDORoefr1enyq5mVL4tmKB3S/EnC3rRJcxCPavG10IcrVGSmPh6Qw5lwrg==" crossorigin=""></script>

<div id="mapid"></div>

Answer №2

kboul's answer was a lifesaver for me with its simple and effective solution. In addition, I successfully implemented the code with geojson point data to create an overlay map.

var medicalFacilities = L.geoJson(facilityData, {
  pointToLayer: function (feature, latlng) {
    return L.marker(latlng, { icon: customMarkerIcon });
  },
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a method for viewing or manipulating an object within a JSON file?

Could someone please assist me in accessing the total sum displayed in the chart using console.log? I have tried setting it using "var item": "[[value.sum]]", but it did not work. Any help is appreciated. var chartData1 = []; generateChartData(); func ...

Guide on how to add multiple options to a select element in HTML using prototype.js

What is the best way to add multiple options to a select tag in HTML using prototype js? Appreciate your help. ...

Font may seem more slender in Firefox and Safari compared to Chrome where the appearance is impeccable

I am currently working on achieving consistent font appearance across Mac Chrome, Safari, and Firefox (IE compatibility to be addressed later). My experiments have included: -webkit-font-smoothing: subpixel-antialiased; The font appears almost identica ...

Ensuring the validation of JSON schemas with dynamically generated keys using Typescript

I have a directory called 'schemas' that holds various JSON files containing different schemas. For instance, /schemas/banana-schema.json { "$schema": "http://json-schema.org/draft-06/schema", "type": "object", "properties": { "banan ...

Issue with displaying multiple checkboxes using Materialize CSS in combination with Leaflet for web-mapping overlays

I'm currently using Materialize 0.97.7 along with Leaflet 1.0.1 (the latest version). <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.1/leaflet-src.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com ...

Using Linux variables in the .env file of your Vue.js project can provide a convenient way to

Using .env in a *.js file allowed me to set the BANK variable as either A_BANK or B_BANK like so: BANK=A_BANK or BANK=B_BANK However, when passing the argument as A_BANK or B_BANK like: --bank A_BANK in a shell script loop for var in $@ do if [ ${var} ...

Modifying Background Images Dynamically with jQuery as You Scroll

Struggling to make my background image change while scrolling has been a challenge for me. I've tried different solutions suggested for similar questions, but so far no success - it only displays the initial background image. The setup involves havin ...

Numerous criteria for selecting a checkbox

I am working with a student database table called student_db, which looks like this: Name Gender Grade City John Male 2 North Dave Male 4 North Garry Male 3 North Chirsty Female 5 East Monica Female 4 East Andrew Male ...

Optimal Placement of jQuery Event Handlers in React/Redux Components with Asynchronous Data Loading

After reviewing the ReactJS documentation, it's clear that the most suitable lifecycle method for handling redux action calls is componentDidMount. However, I'm facing a challenge when it comes to incorporating jQuery operations within this parti ...

Substitute this.bindMethod for function component

I have a class component that is structured like this: interface MyProps { addingCoord: any resetCoords: any } interface MyState { x: any y: any } class DrawerOld extends React.Component<MyProps, MyState> { width: number height: number ...

What is the correct way to utilize href in CSS content property?

Below is the content of a box I have: https://i.sstatic.net/QmG5i.png When the above box is hovered over, it flips to this: https://i.sstatic.net/QsS9t.png This block's HTML code is as follows: <div class='tiles'> <div class= ...

The 'mergeMap' property is not found on the 'Observable<any>' type

Currently, I'm working on an HttpInterceptor within my Ionic 4 application. My goal is to retrieve the Bearer Authorization token stored in local storage. Although I attempted to utilize mergeMap for this task, I kept encountering the following error ...

Tips for resizing a 100% div without displaying vertical scrollbars in the browser

I am facing an issue with a table that has three rows. I have a main #container div with a height of 100%, and inside it is a table with 3 rows. The first and last row contain fixed size content. However, in the second row, there is a #content div with a h ...

mention a Vue.js component computed property that points to a specific DOM element

Is there a way to access the DOM element that initiated a method inside a Vue component computed property? For example: <template> <img :src="getUrl" class="image1"/> <img :src="getUrl" class="image2"/> </template> <scri ...

Exploring the deep nested structure of an object array JSON file through mapping

I am currently working on mapping a nested JSON file, but I am encountering some difficulties. When I log the data in the console, it returns as an 'object' and I am unable to go further than that. (Please note that I am still learning JavaScript ...

The AJAX email submission form is not functioning properly

Recently, I have upgraded my email sign-up form on the website to include validation. However, after adding the validation, the form no longer sends and an error message is not displayed. Upon inspecting, I found the following error: TypeError: null is ...

Encountering an unexpected error with the InvalidCharacterError in IE11 when using VEE Validate in conjunction with Vue.js and babel-p

Encountering an issue in IE11 where I receive an InvalidCharacterError when attempting to validate a form using vee validate in vue.js. It seems like it might be related to a polyfill error, but I'm uncertain. I have tried debugging by removing certai ...

Bidimensional Selenium matrix

Could someone please help me understand how to extract values from a bi-dimensional array using Selenium? I have a resources.js file with the array created, and need to access it in Selenium. Here is the structure of the array: The array consists of 4 col ...

A CSS rule to display a nested list on the left-hand side

I created a menu that you can view here. When hovering over "tanfa demo example," the sublist appears on the right side. The issue I'm facing is that my menu is positioned all the way to the right, which means the sublist also appears on the extreme ...

What steps can I take to resolve the TypeError in next js where I am unable to set properties of undefined for 'className'?

I've been working on a Next.js project and I've copied some code from CodePen that is used for designing product layouts on an e-commerce website. However, I'm encountering a problem with the following error message: TypeError: Cannot set pr ...