Adeyemi Oyinlola
Adeyemi Oyinlola

Reputation: 11

Adding leafletjs map and marker to a laravel project

The markers show up, but the map itself is blank when markers show, but on pages with no featured listing and no markers, the map displays

<script src="https://unpkg.com/[email protected]/dist/leaflet.js"
     integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo="
     crossorigin=""></script>

<script>
document.addEventListener("DOMContentLoaded", function () {
    // Initialize the map with Brampton coordinates and a zoom level
    var map = L.map('map').setView([43.7315, -79.7624], 13);

    // Add a tile layer using OpenStreetMap
    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 19,
    attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}).addTo(map);

    // Get housing locations from the backend as JSON
    var housingLocations = @json($housingLocations);

    // Create a feature group for markers
    var markers = L.featureGroup();

    // Loop through each housing location and add a marker if valid coordinates exist
    housingLocations.forEach(function(location) {
        console.log("Location:", location);
        if (location.lat && location.lon) {
            console.log("Adding marker at:", location.lat, location.lon);
            var marker = L.marker([location.lat, location.lon]);
            var popupContent = '<strong>' + location.name + '</strong><br>' +
                               location.address + '<br>' +
                               location.city + ', ' + location.province + ' ' + location.postal_code;
            marker.bindPopup(popupContent);
            markers.addLayer(marker);
        } else {
            console.log("Invalid coordinates:", location.lat, location.lon);
        }
    });

    // Add all markers to the map
    map.addLayer(markers);
    if (housingLocations.length > 0 && markers.getLayers().length > 0) {
        map.fitBounds(markers.getBounds());
    }

    // Invalidate map size after a short delay to ensure proper rendering
    setTimeout(function() {
        map.invalidateSize();
    }, 500);
});
</script>
/ Fetch housing locations for the map (same query as HousingMapController)
        $housingLocations = DB::table('housing_metas')
        ->join('housings', 'housing_metas.HousingID', '=', 'housings.ID')
        ->select(
            'housings.Name as name',
            'housings.Type as type',
            'housings.Status as status',
            'housing_metas.Address as address',
            'housing_metas.City as city',
            'housing_metas.Province as province',
            'housing_metas.PostalCode as postal_code',
            'housing_metas.Lon as lon',
            'housing_metas.Lat as lat'
        )
        ->whereIn('housings.ID', $housingIDs)
        ->where('housing_metas.City', '=', 'Brampton')
        ->whereIn('housings.Type', ['p', 'b'])
        ->whereNotNull('housing_metas.Lon')
        ->where('housing_metas.Lon', '!=', 0)
        ->get();

        return view('frontend.residence_type', [
            'page_title' => 'Types of Residence',
            'housings' => $housings,
            'category' => $category, // Pass category to view
            'housingLocations' => $housingLocations
        ]);
    }
}

Below is a short summary of what my code has accomplished so far:

• Leaflet Assets: – The Leaflet CSS and JS libraries are included via CDN to enable map rendering and functionality.

• Map Container & Styling: – A div with the id "map" is defined with a fixed height and full width to display the map.

• Map Initialization: – On DOMContentLoaded, a Leaflet map is initialized with a central coordinate (Brampton) and a specified zoom level.

• Tile Layer Setup: – The map uses OpenStreetMap tiles, loaded via HTTPS, with proper attribution.

• Markers Data: – Housing location data is passed from the backend (via the $housingLocations JSON object) to JavaScript.

• Markers Creation: – A feature group is created, and for each housing location that has valid latitude and longitude, a marker is added with a popup containing the name, address, city, province, and postal code.

• Map View Adjustment: – Once the markers are added, the map’s view is adjusted to fit all markers (using fitBounds) and the map size is validated with invalidateSize after a short delay.

This setup allows to dynamically display housing markers on a Leaflet map within your Laravel application.

Upvotes: 0

Views: 30

Answers (0)

Related Questions