Leaflet dynamic popup
Creating a popup on the fly
HTML
<!DOCTYPE html>
<html>
<head>
<title>Quick Start - Leaflet</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin="" />
<script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js" integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA==" crossorigin=""></script>
</head>
<body>
<div id="mapid" style="width: 100vw; height: 100vh;"></div>
</body>
</html>
JavaScript
var map = L.map('mapid').setView([18.12875, 83.0137], 8);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
id: 'mapbox.streets'
}).addTo(map);
var data = {
"datapoint": [{
"img": "https://i0.wp.com/www.appsforpctech.com/wp-content/uploads/2018/03/820ad301d8829120f63d825d67ab9650.jpg?fit=256%2C256&ssl=1",
"latitud": "18.52",
"longitud": "82.4767"
},
{
"img": "https://d2drx6n2xb0i5r.cloudfront.net/site/wp-content/uploads/2013/05/tt.png",
"latitud": "17.7375",
"longitud": "82.8347"
}
]
}
function markerOnClick(e) {
L.popup()
.setLatLng(e.latlng)
.setContent('<img src="' + e.target.img + '">')
.openOn(map);
}
for (i in data.datapoint) {
var marker = L.marker([data.datapoint[i].latitud, data.datapoint[i].longitud]);
marker.img = data.datapoint[i].img;
marker.on('click', markerOnClick);
map.addLayer(marker);
}