React: Leaflet Markers

This entry is part 9 of 9 in the series React: Leaflet

In this tutorial I will demonstrate how to add a marker to the map. Refer to the documentation for more information.

Before We Begin:

Text:

LayerGroup onAdd Method

//Define the marker. Since this is text based their is no icon but instead a divIcon
this.textMarker = L.marker([20.5, -0.09],{
	icon: L.divIcon({
		iconSize: [100,16],
		iconAnchor: [22, 30],
		className: "",
	}), 
	zIndexOffset: 75,
});

//Sets the text
this.textMarker.options.icon.options.html = "This is my text";

//Adds the text marker to the layer
this.addLayer(this.textMarker);

LayerGroup onRemove Method

//Remove the text marker you just added
this.removeLayer(this.textMarker);

Results: Now you will see as you turn the layer on and off from the context menu the text will show or hide.

Icon:

Import Image:

import myImagefrom "../images/myImage.png";

Create Icon/Marker onAdd Method

//Define the icon you will be using
var myIcon = L.icon({
	iconUrl: myImage,
	iconSize:     [75, 75], // size of the icon
	iconAnchor:   [22, 94], // point of the icon which will correspond to marker's location
});

//Define the icon based marker
this.marker = L.marker([20.5, -40.09],{
	icon: myIcon,
	opacity: 0.7,
	zIndexOffset: 30
 });

//Adds the icon marker to the layer
this.addLayer(this.marker);

onRemove Method

//Remove the marker you just added
this.removeLayer(this.marker);

Results: Now you will see as you turn the layer on and off from the context menu the icon will show or hide.

Set Latitude/Longitude:

You can set the latitude and longitude in one of two ways.

//Set the latitude and longitude

//Method 1:
L.marker([20.5, -0.09])

//Method 2:
this.textMarker.setLatLng([20.5, -0.09]);

Event(s):

onClick

marker.on("click", function(e) {
	var marker = e.target;
	//Do my work here
}.bind(this));

MouseOver

marker.on("mouseover", function(e) {
	var marker = e.target;
	//Do my work here
}.bind(this));

MouseOut

marker.on("mouseout", function(e) {
	var marker = e.target;
	//Do my work here
}.bind(this));

Popup:

BindPopup

marker.bindPopup(L.popup(),{
	offset: L.point(0,-10) //You can add an offset if you want to
});

OpenPopup

Let’s say you want to open the popup during a mouseover event.

marker.on("mouseover", function(e) {
	var marker = e.target;

	//Set the content to display in the popup
	marker.setPopupContent("My Text");
	//Now open the popup
	marker.openPopup();
}.bind(this));

ClosePopup

Let’s say you want to open the popup during a mouseout event.

marker.on("mouseout", function(e) {
	var marker = e.target;
	//Close the popup now
	marker.closePopup();
}.bind(this));