Tips for updating the default pin icon in a leaflet directive

Is it possible to change the default blue icon with a custom icon when initializing the app? I have read about how to change it, but I want a unique icon for the entire application.

HTML

<div ng-controller="CustomizedMarkersController">
   <button type="button" class="btn btn-primary padright" ng-click="markers.m1.icon=icon" ng-repeat="(key, icon) in icons">{{ key }}</button>
   <leaflet markers="markers" center="lisbon"></leaflet>
</div>

JS

app.controller("CustomizedMarkersController", [ '$scope', function($scope) {
    var local_icons = {
       default_icon: {},
       leaf_icon: {
          iconUrl: 'examples/img/leaf-green.png',
          shadowUrl: 'examples/img/leaf-shadow.png',
          iconSize:     [38, 95],
          shadowSize:   [50, 64],
          iconAnchor:   [22, 94],
          shadowAnchor: [4, 62],
          popupAnchor:  [-3, -76]
       },
       div_icon: {
           type: 'div',
           iconSize: [230, 0],
           html: 'Using <strong>Bold text as an icon</strong>: Lisbon',
           popupAnchor:  [0, 0]
       },
       orange_leaf_icon: {
          iconUrl: 'examples/img/leaf-orange.png',
          shadowUrl: 'examples/img/leaf-shadow.png',
          iconSize:     [38, 95],
          shadowSize:   [50, 64],
          iconAnchor:   [22, 94],
          shadowAnchor: [4, 62]
       }
 };

angular.extend($scope, {
    icons: local_icons
});

angular.extend($scope, {
    lisbon: {
        lat: 38.716,
        lng: -9.13,
        zoom: 8
    },
    markers: {
        m1: {
            lat: 38.716,
            lng: -9.13,
            message: "I'm a static marker",
            icon: local_icons.default_icon,
        },
    },
    defaults: {
        scrollWheelZoom: false
    }
});
}]);

Based on this example.

Answer №1

According to the documentation on Leaflet, check out Icon.Default

To modify the default icon, adjust the properties of L.Icon.Default.prototype.options (which represents a collection of Icon options).

For example, add this line in your code:

L.Icon.Default.prototype.options.iconUrl = 'myNewDefaultImage.png';

You may also need to update the shadows and 2x icons for retina displays by modifying the options shadowUrl and iconRetinaUrl.

Answer №2

After encountering issues with the previous solution in my implementation of Leaflet-1.7, I found success by following this alternative approach:

L.Marker.prototype.options.icon = L.icon({
    iconUrl: "/custom/path/markericon.png",
    shadowUrl: "/custom/path/markershadow.png"
});

Answer №3

To easily achieve this goal, it is recommended to utilize the mergeOptions method in Leaflet. It is not advisable to directly manipulate the prototype, as mentioned in various responses here, as doing so may interfere with the internal workings of the library and lead to potential issues in the future.

L.Icon.Default.mergeOptions(icons)

The contents of icons should include:

icons = { // feel free to customize with your specific image paths
  iconUrl: 'media/images/marker-icon.png', 
  iconRetinaUrl: 'media/images/marker-icon-2x.png',
  shadowUrl: 'media/images/marker-shadow.png',
}

For a complete list of available options for Icon.default set within icons, refer to the Icon documentation.

Answer №4

For customizing draw plugins, you can use the following code:

var drawPluginOptions = {
  position: 'topright',
  draw: {
    polyline: false,
    polygon: false,
    circle: false, // Disable this drawing tool
    rectangle: false,
    circlemarker: false,
    marker: {
      title: "markerTest",
      icon: new MyCustomMarker()
    }
  },
  edit: {
    featureGroup: editableLayers, //REQUIRED!!
    remove: false
  }
};

Once you have customized the draw plugins, add them to the map using the code below:

map.on('draw:created', function(e) {
  var type = e.layerType,
    layer = e.layer;
    
    /*if(layer.title == "Place hospital marker"){
        do this...
    }*/

  editableLayers.addLayer(layer);
});

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

How can I capture and save a webpage print on the server?

Currently, I am developing a custom card editor where users can make changes to text directly on the card, upload images, and perform basic editing functions such as resizing, framing, and converting to black and white using javascript. After the user fini ...

node.js: The Yahoo weather jQuery plugin fails to display any data

After successfully implementing node.js with jQuery and the plugin from , I now aim to utilize the weather data for a different purpose rather than directly inserting it into the HTML. However, I am encountering difficulties in accessing or displaying the ...

Sum result from jQuery calculation is not desirable

Within my table, the <th> tag is initially set to 0: <th id="total_price" style="text-align:center">0</th> When a new item is sold, its price should be added to the value within this <th>. For example, if the new item costs 20,000 ...

Using Angular to create unique filter elements

<select ng-model="model" id="filter"> <option value="" id="dropdownDefault">Title</option> <option ng-repeat="select in selects" value="{{select.title}}" id="dropdown">{{select.title}}</option> </select> <sel ...

504 error when attempting to access HTTPS with Node.js

I have encountered an issue with making an https request in my backend node.js web app. The code I am using is as follows: const express = require('express'); const https = require('https'); const app = express(); app.get("/", functio ...

The table's content extends beyond the confines of the page

I have an HTML page where I am embedding an SSRS report. The report extends beyond the page as shown in the image below: This is the table that is generated: <table cellpadding="0" cellspacing="0" id="ctl00_MainContent_FiveYearReportViewer_fixedTable" ...

Anticipate the arrival of a gadget and deliver a response to a website

My current project involves utilizing the nfc module from npm to read smartCard data and send the results to a web interface. Everything works smoothly when the card reader is connected. However, when the card reader is not plugged in, the web server (nod ...

ngTagsInput retrieves and processes information from the database

Before sending data to the database using ngTagsInput, I perform the following action: angular.toJson($scope.tags); Upon retrieving the data, my scope displays something similar to this: [{"text":"abc"},{"text":"cba"},{"text":"tag"}] How can I display ...

Each time guildMemberAdd is triggered in Discord.js, it may not run consistently

At times, I am left baffled by the inconsistency in behavior of this code. Sometimes it works like a charm, while other times it refuses to add people for hours on end, only to randomly start working again. Any suggestions on how I can resolve this issue? ...

Tips for assigning a cookie as the id of a div?

I've been tasked with making the selected menu stand out when the page is refreshed. I'm thinking of using a cookie to achieve this. Here's the HTML code: <div class="menuBar"> <div class="menuHeader ui-corner-top"> ...

What is the best way to loop through a dataset and extract only the properties listed in an array?

Currently, I am working on a project in Angular and came across this particular query. However, it doesn't fully meet my requirements. After making an API call, I receive a JSON object with over twenty properties. For instance, a user could have prop ...

Successive, Interrelated Delayed Invocations

There are two functions in my code, getStudentById(studentId) and getBookTitleById(bookId), which retrieve data through ajax calls. My ultimate goal is to use Deferreds in the following sequence: Retrieve the Student object, Then fetch the Book Title bas ...

Can you tell me if the "dom model" concept belongs to the realm of HTML or JavaScript?

Is the ability to use "document.X" in JavaScript to visit an HTML page and all its tags defined by the HTML protocol or the ECMAScript protocol? Or is it simply a choice made in the implementation of JavaScript, resulting in slight differences in every bro ...

Vue 2 failing to retain component data upon page refresh

I've encountered a peculiar issue with Vue (v2.6.14) where I'm trying to create a new array based on one received as a prop. Here's the code snippet that's causing the trouble: props: { employees: Array }, data() { return { sorted ...

What could cause the variable "this" in a function within an AngularJS service to be undefined?

Why is the inside function undefined in the AngularJS service? .service('SliceService', function () { var self = this; var Slice = function(intervals, intervalSpan) { self.activeSlice = []; self.hasNext = true; s ...

Utilizing ngDisabled within ng-class

After reviewing the ui-bootstrap pagination template, I am confused about the use of ngDisabled within ng-class. I would appreciate some clarification on this matter. I examined the 'PaginationController', and it seems that ngDisabled is not a s ...

Handling Access-Control-Allow-Origin issue in AngularJS and Flask-Socketio

I am facing a challenge while attempting to establish a connection between Flask-Socketio from AngularJS on the client side to a Flask server. Establishing the connection with the Flask server is successful, however, encountering an error when trying to c ...

Image not displayed when JavaScript adds <IMG SRC=

While I am dynamically adding rows to a table, each new table item's innerHTML is set as follows: picCell.innerHTML = '<label for="checkbox-a" data-form="ui-btn-up-a" class="'+uncheckedClassString+'" ...

If the ID (i.e. document.getElementById) is not found, then keep JavaScript running

I'm currently working on a JavaScript project where I need the script to gracefully handle missing div-ids and continue executing. I've looked into various solutions, but many involve either replacing the missing ID or placing information into an ...

creating dynamic column headers with JavaScript

I am looking for a way to make the column names dynamic so that I don't have to manually update them every time. Here is my code snippet: jqGrid11.prototype = { display : function() { $('body').append(this.html.join("")); $("#jqGrid").j ...