Leaflet Tambah dan Hapus Marker on Click

Posting sekarang adalah lanjutan mengenai leaflet. Bahasannya adalah bagaimana menambah dan menghapus tanda marker dalam peta.


// We’ll add a OSM tile layer to our map
var osmUrl = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
osmAttrib = '© OpenStreetMap contributors',
osm = L.tileLayer(osmUrl, {
maxZoom: 18,
attribution: osmAttrib

// initialize the map on the "map" div with a given center and zoom
var map = L.map('map').setView([25.92, 79.84], 5).addLayer(osm);

// attaching function on map click
map.on('click', onMapClick);

// Script for adding marker on map click
function onMapClick(e) {
var geojsonFeature = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [e.latlng.lat, e.latlng.lng]

var marker;

L.geoJson(geojsonFeature, {
pointToLayer: function(feature, latlng){
marker = L.marker(e.latlng, {
title: "Resource Location",
alt: "Resource Location",
riseOnHover: true,
draggable: true,
}).bindPopup("<[remove this]input class="marker-delete-button" type="button" value="Delete this marker" />");
marker.on("popupopen", onPopupOpen);
return marker;

// Function to handle delete as well as other events on marker popup open
function onPopupOpen() {

var tempMarker = this;

//var tempMarkerGeoJSON = this.toGeoJSON();
//var lID = tempMarker._leaflet_id; // Getting Leaflet ID of this marker

// To remove marker on click of delete
$(".marker-delete-button:visible").click(function () {

// Getting all the markers
function getAllMarkers() {

var allMarkersObjArray = [];//new Array();
var allMarkersGeoJsonArray = [];//new Array();

$.each(map._layers, function (ml) {
if (map._layers[ml].feature) {


alert("total Markers : " + allMarkersGeoJsonArray.length + "\n\n" + allMarkersGeoJsonArray + "\n\n Also see your console for object view of this array" );

$(".get-markers").on("click", getAllMarkers);


output yang dihasilkan menjadi seperti berikut.


Semoga bermanfaat, wassalam.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s