Our Blog

LeafletJS. Why is it awesome? And how to add markers from outer div, change their color and stylize their popup – simple tutorial

Mariana Georgieva
by Mariana Georgieva on Mon 17 February 2014 2 comments

Although Leaflet is a new JavaScript library for maps, it has gained popularity very quickly.

Why? First, it works well for both desktop and mobile devices. Second, it is an open source, which is great. And this is probably the thing I should have started with. It is simple and by simple I mean it is very easy to start using it even if you don’t have any experience with maps. The API documentation is wonderful, the code is clean, readable and OOP-based and there are also tones of tutorials on the net.

With Leaflet I love that you are able to edit the CSS of all the map elements and customize it according to your needs. It is also very small and fast. Despite being about 34 kb, it has all the features most developers have ever needed for online maps. And it is easy to add features or customize existing ones to your needs.

There is so much that can be said but I think I should stop and go to the example.

start

This is how the map looks like. There is a small menu on the left where the markers can be added from. How? There is a MouseOver event attached to the plus icon which shows a new icon – a little flag.

mouseover

The flag must be dragged over the map. When the mouseup event occurs a new marker will be shown on the map at the current position of the cursor.

mouseup

Once the marker is positioned on the map, its color can be changed by selecting preferred one from a menu in the marker’s popup.  We will also see how the popup can be stylized.

popup marker-changed

The markers can be added by dragging them from the outside div. The color menu will be shown in the popups, so we’ll see how to stylize them for our needs. Now let’s start coding. Before writing anything, we have to include Leaflet CSS and JavaScript files, jQuery and jQuery UI in the head tag. We will use jQuery UI for making marker’s icon draggable. Here is the whole html code that will be needed. One div for the map menu with two icons, one for adding marker, and another hidden, which is going to be dragged to the map. The second div is the container of the map. And the third one is the color menu, which will appear in the markers’ popup.


<div class="map-menu">
    <img src="Images/add-marker.png" class="marker-selector-icon">
    <img src="Images/flag.png" id="draggable">
</div>
<div id="map"></div>
<div class="markers-color-palette">
    <img src="Images/red-marker.png" class="marker-colors redIcon" />
    <img src="Images/green-marker.png" class="marker-colors greenIcon" />
</div>

Now let’s start with JavaScript. First, the map must be initialized. We need some images, made by ourselves or just downloaded from somewhere to make custom icons. Marker icons in Leaflet are defined by L.Icon objects, which are passed as an option when creating markers.  We need to create two icons that have a lot in common, so we’ll define icon class.

    var map,
        markers = [],
        markersCount = 1,
        posTop,
        posLeft,
        drag;

	var CustomIcon = L.Icon.extend({
	        options: {
	            iconSize: [38, 55]
	        }
	});

	var redIcon = new CustomIcon({ iconUrl: 'Images/red-marker.png' }),
	greenIcon = new CustomIcon({ iconUrl: 'Images/green-marker.png' });

	L.icon = function (options) {
	    return new L.Icon(options);
	};

	var initMap = function () {
	    map = new L.Map('map', { zoomControl: false }).setView([42.7, 23.33], 15);

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

Let’s take a look at the function that adds markers on the map. What we have here? Like I said before, to make the icon draggable we use jQuery UI library. The problem is how the marker can be positioned on the map. In order to do this we need coordinates in latitude, longitude format, but all we have is position on the screen in pixels. So we use containerPointToLatLng function , which returns the geographical coordinates of a given map container point.
Once we have the coordinates, placing a marker on the map is like a child’s play. The important thing here is to change the popup’s html with the html of our color menu, after marker is created. This can be done by putting the html as a parameter of the bindPopup function, which attaches the popup to the marker.

var addMarkers = function () {
        $(".marker-selector-icon").on("mouseenter", function () {
            $("#draggable").show();
        })

        map.on("click", function () {
            $("#draggable").hide();
        })

        $("#draggable").draggable({
            start: function (event, ui) {
                posTop = $("#draggable").css("top");
                posLeft = $("#draggable").css("left")
            },
            stop: function (e, ui) {
                $("#draggable").css("top", posTop);
                $("#draggable").css("left", posLeft);
                $("#draggable").hide();
            },
            drag: function (e, ui) {
            }
        });

        $("#draggable").on("mouseup", function (event) {

                var coordsX = event.clientX - 50;
                var coordsY = event.clientY;
                var point = L.point(coordsX, coordsY);
                var markerCoords = map.containerPointToLatLng(point);

                markers[markersCount] = L.marker([markerCoords.lat, markerCoords.lng], {
                    icon: greenIcon,
                    draggable: true,
                    id: markersCount
                }).addTo(map).bindPopup($(".markers-color-palette").html());

                markersCount++;
                editMarkerColor();
        })
    }

Now let’s see how to change the color of the markers. It’s easy. We use setIcon function to change the icon with the chosen one from the menu in the popup.


var editMarkerColor = function (marker) {
        for (i in markers) {
            markers[i].on('popupopen', function () {
                var marker = this;
                $(".marker-colors").on("click", function () {
                    marker.setIcon(eval($(this).attr("id")));
                })
            })
        }
	}

And in the end we need to call our functions.

 $(".markers-color-palette").hide();
 $("#draggable").hide();

 initMap();
 editMarkerColor();
 addMarkers();

Now let’s see how to make popups looking good. It’s simple, we just need to select them (.leaflet-popup-content-wrapper, .leaflet-popup-tip) and change their css properties. Isn’t it great?

#map {
	position: absolute;
	display: inline-block;
	height: 400px;
	width: 400px;
	margin-left: 50px;
}

.map-menu {
	position: absolute;
	display: inline-block;
	height: 400px;
	width: 50px;
	background-color: rgb(250, 245, 221);
	margin-left: 5px;
}

.marker-selector-icon {
	width: 30px;
	left: 0;
	right: 0;
	margin: auto;
	top: 10;
	position: absolute;
	cursor: pointer;
}

#draggable {
	position: absolute;
	width: 30px;
	top: 50px;
	left: 0;
	right: 0;
	margin: auto;
	cursor: pointer;
	z-index: 2;
}

.marker-colors {
	width: 30px;
	margin: 5px;
}

.leaflet-popup-content-wrapper {
	background-color: rgb(247, 245, 197) !important;
	border: 2px solid rgb(39, 175, 93) !important;
	border-radius: 60px !important;
}

.leaflet-popup-tip {
	display: none !important;
}

So, that is all for now. You saw how easy it is to manipulate with the map and its items, you just need to use your imagination and make some great looking things.

Mariana GeorgievaLeafletJS. Why is it awesome? And how to add markers from outer div, change their color and stylize their popup – simple tutorial

Related Posts

Take a look at these posts

2 comments

Join the conversation
  • steflp - Tue 17 June 2014 reply

    Hello, I want to use bindpopup and popup but maxWidth is 300px ! so it s not very nice on my map …
    I don’t find anywhere how to make somme js to change this …
    I find on leafletjs.com here : http://leafletjs.com/reference.html#popup-maxwidth
    But i Dont know how …
    Can you help me ?

    Thanks a lot ….
    Stef

  • David - Mon 23 June 2014 reply

    Hi.

    What I want to do is change the size of the marker, instead of 41×21 use minor size. Any idea?

    thanks

Join the conversation