Adding Interactive Maps to Laravel Applications with Leaflet js - Step 3 - Adding Markers to the Map based on Json

The next step uses the getJson() jquery function which makes an Asynchronous Javascript And XML call to the courts.map.json route to retrieve json data relating to the courts in the database. This function is an asychronous call meaning that the app and code will continue to execute while it is retrieving the json data. If the json data is retrieved successfully the .done promise will be executed. If there is a problem retrieving the user will be alerted with an error message.

The json data, once retrieved is passed to an array of objects called courts. A for loop loops through each one of these court objects, it uses the lat and lng attributes of the court to instantiate marker objects and add them to the map. The bindPopup method is use to add a popup to each marker containing whatever is in the name attribute for the court object. In our case, this will include the court surface, whether its floodlit and whether it's indoor or outdoor. Add the following method inside the script tags in the \resources\courts\showmap.blade.php view

fitBounds( )

The fitBounds( ) method one of the clever aspects of map APIs (a similar function is part of Google Maps API) - It automatically pans the map over the cluster of markers that passed in an array to the function. The level of zoom on the map will be automatically adjusted so all the markers can be seen at the same time. If the markers are spread over a wide area the map will be zoomed out and if the markers are in a tight cluster the map will be zoomed in.

To make all this work add the following method inside the script tags in the \resources\courts\showmap.blade.php view

$.getJSON({
    url: '{{route('courts.map.json')}}'
    }).done(function (courts) {
        var bounds = [];
        for ( var i=0; i < courts.length; ++i ) {
           thisMarker = L.marker( [courts[i].lat, courts[i].lng] ,{icon : icon}).addTo( mymap ).bindPopup(courts[i].name);
           bounds.push([courts[i].lat,courts[i].lng]);
        }
        mymap.fitBounds(bounds,{padding: [20,20]});
    }).fail(function (xhr, status, error) {
        alert("There is a problem with your route to your json data: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
});

Now when you visit http://localhost:8000/courts/show/map you should see markers with the locations of the various courts as in the screenshot below. If you click on the marker you will see information about the court

Leave a Reply