resq/templates/leaflet/index.html.twig
2024-10-28 17:53:06 +08:00

89 lines
3.2 KiB
Twig

{% extends 'base.html.twig' %}
{% block title %}Leaflet Map with Layers{% endblock %}
{% block stylesheets %}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css" />
<style>
#map {
height: 500px; /* You can adjust the height here */
width: 100%;
}
</style>
{% endblock %}
{% block body %}
<h2>Leaflet Map</h2>
<div id="map" class="w-full h-96 mb-4"></div>
<div id="coordinates" class="text-gray-600 text-sm mt-4"></div>
<script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"></script>
<script>
// Base layers: Streets and Satellite
var streets = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
});
var satellite = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
maxZoom: 17,
});
// Initialize the map
var map = L.map('map', {
center: [14.5995, 120.9842], // Latitude, Longitude of Manila
zoom: 13,
layers: [streets] // Set default layer
});
// Base layers for diff map sets
var baseMaps = {
"Streets": streets,
"Satellite": satellite
};
// Switch between base layers
L.control.layers(baseMaps).addTo(map);
// Add markers for cities
var manilaMarker = L.marker([14.5995, 120.9842]).addTo(map)
.bindPopup("<b>Manila</b><br>Capital of the Philippines").openPopup();
var sanJuanMarker = L.marker([14.6042, 121.0293]).addTo(map)
.bindPopup("<b>San Juan City</b><br>Known for historical sites.");
var quezonMarker = L.marker([14.6760, 121.0437]).addTo(map)
.bindPopup("<b>Quezon City</b><br>Largest city in Metro Manila.");
// Add click event listener for adding new markers
map.on('click', function(e) {
var lat = e.latlng.lat; // Get latitude
var lng = e.latlng.lng; // Get longitude
// Create a new marker
var newMarker = L.marker([lat, lng]).addTo(map);
// Create a delete button inside the popup
var deleteButton = `<button onclick="deleteMarker(${lat}, ${lng})"
style='background-color: red; color: white; padding: 5px;'>Delete Marker</button>`;
// Add a popup to the marker with the "Save Marker" and "Delete" button
newMarker.bindPopup("<b>Save Marker</b><br>" + deleteButton).openPopup();
// Update the coordinates in the div
document.getElementById('coordinates').innerHTML =
'Coordinates: Latitude ' + lat + ', Longitude ' + lng;
});
// Function to delete marker based on lat/lng
function deleteMarker(lat, lng) {
map.eachLayer(function (layer) {
if (layer instanceof L.Marker) {
if (layer.getLatLng().lat === lat && layer.getLatLng().lng === lng) {
map.removeLayer(layer); // Remove the marker
}
}
});
}
</script>
{% endblock %}