Search code examples
javascriptphplaravelgoogle-maps-api-3infowindow

How to show more column from database in google maps infowindow?


Previously I was able to display the infowindow on maps, but it only displayed one value from the database. How do you display more than one database value on the google maps infowindow? Thanks

This is my GoogleController

 public function index()
    {
        $data = Pelabuhan::all();
        $locations = [];
        foreach ($data as $item) {
        $locations[] = [
            $item->nama_pelabuhan,
            $item->latitude,
            $item->longitude,
            $item->title
        ];
        }
        
        return view('sinkopel', [
            'data' => $data,
            'locations' => $locations,
            'title' => 'Home'
        ]);
    }

This is my views

<div id="map"></div>
    <script type="text/javascript">
        function initMap() {
            const myLatLng = { lat: -8.636176573413225, lng: 117.53647409339307 }; 
            const map = new google.maps.Map(document.getElementById("map"), {
                zoom: 9.1,
                center: myLatLng,
            });
  
            var locations = {{ Illuminate\Support\Js::from($locations) }};
  
            var infowindow = new google.maps.InfoWindow();
  
            var marker, i;
              
            for (i = 0; i < locations.length; i++) {  
                  marker = new google.maps.Marker({
                    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                    map: map
                  });
                    
                  google.maps.event.addListener(marker, 'click', (function(marker, i) {
                    return function() {
                      infowindow.setContent(locations[i][0]);
                      infowindow.open(map, marker);
                    }

                  })(marker, i));
  
            }
        }
  
        window.initMap = initMap;
    </script>
  
    <script type="text/javascript"
        src="https://maps.google.com/maps/api/js?key={{ env('GOOGLE_MAP_KEY') }}&callback=initMap" ></script>

This is the results : here


Solution

  • The Google Maps API Reference for InfoWindow can be found here: https://developers.google.com/maps/documentation/javascript/reference/info-window#InfoWindow.setContent

    setContent([content])

    Parameters:

    content: string|Element|Text optional The content to be displayed by this InfoWindow.

    Return Value: None

    The info window will display whatever you pass to it.

    infowindow.setContent(locations[i][0]);
    

    This line means it will display the contents of locations[i][0].

    If you want to display more information, the best way to do that is to format the information with some HTML and pass that to setContent.

    infowindow.setContent("\
        <h1>My Title</h1>\
        <p>Some text about something</p>\
    ");