搜索时如何使用数据库中的php在googleMap中显示多个标记?

e5njpo68  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(252)

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

<?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>
4szc88ey

4szc88ey1#

以下内容完全未经测试!这个 Object Orientated 使用风格 mySQLi 要比 procedural 由于在sql语句中直接使用post数据,因此您的代码容易受到sql注入的攻击。您应该考虑使用准备好的语句来减轻这种威胁。
似乎可以简化php代码以生成一些json数据,一旦页面加载完毕,就可以在javascript代码中使用这些数据。数据是在post请求后返回的,因此该表单可能位于此处未详细说明的另一页上。您可以轻松地将表单放在同一页面上,并且无需使用javascript重定向,甚至无需使用ajax重定向即可获得更清晰的效果,无需重新加载/查看页面(这将增加google记录的Map加载)
记录集转换为json,并作为javascript变量写入页面。加载Map后,您将遍历此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>

相关问题