-1

When I try to show multiple markers from the database information, the map only shows the last of the markers returned with its infoWindow.

I read other post that talks about a clousure, but I can't resolve my problem.

This is the original code:

  <body>
    <?php
      include("conexion.php");
      $tipo = $_POST['type'];
    ?>
    <div class="container">
      <div class="row">
        <div class="col-md-12">
          <h1>Map</h1>
          <div id="map" style="width:100%;height:360px;"></div><br><br>
          <?php
            $con = mysqli_connect($host, $user, $pass, $db_name) or die("Error");
            $query = "select * from table where type_name='".$type."'";
            $result = mysqli_query($con,$query);
            $i=1;
            while ($data = mysqli_fetch_assoc($result)) {
          ?>
            <script type="text/javascript">
              var cat = new google.maps.LatLng(41.652393,1.691895);
              var mapOptions = {
                  center: cat,
                  zoom: 8,
                  mapTypeId: google.maps.MapTypeId.ROADMAP
                };
              map = new google.maps.Map(document.getElementById('map'), mapOptions);

              var marker<?php echo $i;?> = new google.maps.Marker({
                    position: new google.maps.LatLng(<?php echo $data['lat']; ?>, <?php echo $data['lng']; ?>),
                    map: map,
                    title: <?php echo "'".$data['name']."'"; ?>
              });

              var infowindow<?php echo $i;?> = new google.maps.InfoWindow({
                  content: "<h1><?php echo "".$data['name'].""; ?></h1><p><b>Addres</b><br> <?php echo "".$data['addres'].""; ?></p><p><b>Description</b><br><?php echo "".$data['description'].""; ?></p>"
              });

              google.maps.event.addListener(marker<?php echo $i;?>, 'click', function() {
                  infowindow<?php echo $i;?>.open(map,marker<?php echo $i;?>);
              });
            </script>

            <?php
                  $i++;
                }
              mysqli_close($con);
            ?>
        </div>
      </div>
    </div>
  </body>

nghngh

1 Answers1

0

Just put all the markers on an array, also do the while inside the js, you are creating the map var for every interaction, or create the elements on the js with an ajax, this will improve a lot for performance.

also take a look to this Google Maps JS API v3 - Simple Multiple Marker Example

Community
  • 1
  • 1