搜索时如何使用数据库中的 PHP 在 Google 地图中显示多个标记?

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

我尝试制作一个简单的搜索功能来查找医院名称,然后它会显示在地图上,我在搜索时使用了 $_POST superglobal,它会在数据库中查找结果。该代码稍微起作用,并且通过稍微起作用它只在地图上显示一个标记,即使它应该根据您在文本框中输入的文本显示多个结果。

<?php
if(isset($_POST['search'])){
  
  $term = $_POST['term'];
  
  $query = "SELECT * from hospitals WHERE hname LIKE '%$term%' ";
  $search_query = mysqli_query($connection, $query);
  
  if(!$search_query){
  
    die("QUERY FAILED" . mysqli_error($connection));
  
  }
  
  $count = mysqli_num_rows($search_query);
  
  if($count == 0){
  
    echo "<script>
            alert('No Result!.');
            window.location.href='Index.php';
            </script>"; 
  } else if (empty($term)){
  
    echo "<script>
            alert('Please fill up.');
            window.location.href='Index.php';
            </script>";   
  
  } else {
  $select_all_hospitals_query = mysqli_query($connection, $query);
  while($row = mysqli_fetch_assoc($select_all_hospitals_query)){
  $post_hname = $row['hname'];
  $post_address = $row['Address'];
  $post_lat = $row['lat'];
  $post_longi = $row['lng'];
  $coordinates = 'new google.maps.LatLng( '. $row['lat']. ','. $row['lng']. '),';

  }
  
  }
  
}

?>
<html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>LabSeek</title>

    <link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/sidebars/">
    <link rel="stylesheet" type="text/css" href="map/map.css" />
    <link href="styles/sidebars.css" rel="stylesheet">
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <!-- <script src="map/map.js"></script> -->
  </head>

<body>
<div id="map">

 <!-- Async script executes immediately and must be after any DOM elements used in callback. -->
 <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBQbnrTvBW0ML5bVlgsgMhYCqdRR04d7k0&callback=initMap&libraries=&v=weekly"
      async
      
    ></script>
<script>
  
function initMap() {
var options = {
  zoom:14,
  center: { lat: 14.586225342331847, lng: 120.99824317301842 }
}

//new map
var map = new
google.maps.Map(document.getElementById('map'),options);


//add marker from search
  function addMarker(coords){
    var marker = new google.maps.Marker({
  position: coords,map:map, });
  }
 addMarker({<?php echo 'lat:'. $post_lat .', lng:'. $post_longi; ?>});

}
</script>
</div>
</html>

以下内容完全未经测试!使用 mySQLiObject Orientated 风格比 procedural 风格要简洁得多,唉,由于使用 POST 数据,您的代码容易受到 SQL 注入的攻击直接在 SQL 语句中使用。您应该考虑使用 Prepared Statements 来减轻这种威胁。

您似乎可以简化 PHP 代码以生成一些 JSON 数据,您可以在页面加载后在 Javascript 代码中使用这些数据。数据是在 POST 请求之后返回的,因此可能该表单位于此处未详细说明的另一页上。您可以轻松地将表单放在同一页面上,并且无需在 Javascript 中使用重定向 - 甚至 AJAX 以获得没有页面 reloads/views 的更清晰的效果(这将增加Google )

记录的地图负载

记录集被转换为 JSON 并作为 Javascript 变量写入页面。加载地图后,您将遍历此 JSON 数据并为结果中的每条记录添加一个新标记。

<?php
    
    $json=false;
    
    if( isset( $_POST['search'] ) ){
    
        $term='%'.$_POST['term'].'%';
        $query='SELECT * from hospitals WHERE hname LIKE ?';
        
        $stmt=$db->prepare( $query );
        $stmt->bind_param('s',$term);
        $stmt->execute();
        
        $res=$stmt->get_result();
        $data=$res->fetch_all( MYSQLI_ASSOC );
        $json=json_encode( $data );
    }

?>

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8'>
        <title>LabSeek</title>

        <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>
        <script>
            <?php
            
                #Convert the PHP variable into Javascript variable
                printf('const json=%s;',$json ?: '[]');
                
            ?>
            function initMap() {
                var options = {
                    zoom:14,
                    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({
                        position:coords,
                        map:map             
                    },args);
                
                    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={
                            'Address':obj.Address,
                            'Name':obj.hname
                        };
                        
                        addMarker(latlng,args)
                    })
                }
            }
        </script>
    </head>
    <body>
        <div id='map'></div>
        <script async defer src='//maps.googleapis.com/maps/api/js?key=AIzaSyBQbnrTvBW0ML5bVlgsgMhYCqdRR04d7k0&callback=initMap'></script>
    </body>
</html>