[Solved] How do you show multiple markers in Google Maps using PHP from the database when searching?

The following is wholly untested! The Object Orientated style of using mySQLi is considerably less verbose than the procedural style and alas your code is vulnerable to SQL injection due to the use of POST data directly used within the SQL statement. You should consider using Prepared Statements to mitigate this threat.

It appears that you could simplify the PHP code to produce some JSON data which you can consume within the Javascript code once the page has loaded. The data is returned following a POST request so presumably the form is on another page not detailed here. You could easily have the form on the same page and remove the need to use a redirection in Javascript – or even AJAX for a much cleaner effect with no page reloads/views ( which will increase the map loads recorded by Google )

The recordset is converted to JSON and this is written to the page as a Javascript variable. Once the map is loaded you iterate through this JSON data and add a new marker for each record in the results.

    if( isset( $_POST['search'] ) ){
        $query='SELECT * from hospitals WHERE hname LIKE ?';
        $stmt=$db->prepare( $query );
        $data=$res->fetch_all( MYSQLI_ASSOC );
        $json=json_encode( $data );


<!DOCTYPE html>
<html lang='en'>
        <meta charset="utf-8">

        <link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/sidebars/">
        <link rel="stylesheet" type="text/css" href="map/map.css" />
        <link rel="stylesheet" href="styles/sidebars.css" />
        <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
                #Convert the PHP variable into Javascript variable
                printf('const json=%s;',$json ?: '[]');
            function initMap() {
                var options = {
                    center: { lat: 14.586225342331847, lng: 120.99824317301842 }
                var map = new google.maps.Map( document.getElementById('map'), options );
                function addMarker( coords, args ){
                    // using `Object.assign` allows you to easily 
                    // add more properties when you call this function
                    let opts=Object.assign({
                    return new google.maps.Marker(opts);
                if( json && Object.keys( json ).length > 0 ){
                    Object.keys( json ).forEach( key=>{
                        let obj=json[key];
                        let latlng=new google.maps.LatLng( obj.lat, obj.lng );
                        let args={
        <div id='map'></div>
        <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBQbnrTvBW0ML5bVlgsgMhYCqdRR04d7k0&callback=initMap"></script>


solved How do you show multiple markers in Google Maps using PHP from the database when searching?