0

I am trying to display multiple markers on Google maps using data (lat and lng) from a MySQL database. When I run a foreach loop to return these markers on the map, it returns only the last row. What might be the problem?

<?php
require_once "db/db_handle.php";
$select = "SELECT * FROM map";
$data = $db->query($select);
?>
<!DOCTYPE html>
<html>
  <head>
    <style>
      #map {
        height: 400px;
        width: 100%;
       }
    </style>
  </head>
  <body>
    <h3>My Google Maps Demo</h3>
    <div id="map"></div>
    <?php foreach ($data as $key) {
      echo $key['lat'];
    ?>
    <script>
      function initMap() {
        var uluru = {lat: <?php echo $key['lat']; ?>, lng: <?php echo $key['lng']; ?>};
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 12,
          center: uluru
        });
        var marker = new google.maps.Marker({
          position: uluru,
          map: map
        });
        var contentString = '<?php echo $key['address']; ?>';

        var infowindow = new google.maps.InfoWindow({
          content: contentString
        });

        var marker = new google.maps.Marker({
          position: uluru,
          map: map,
          title: 'Uluru (Address)'
        });
        marker.addListener('click', function() {
          infowindow.open(map, marker);
        });
      }
    </script>
    <?php  } ?>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=myKey&callback=initMap">
    </script>
  </body>
</html>
2
  • you are including whole script in loop i.e every time loop is executed a new instance of map is generated move the map outside loop and just marker inside loop Commented Feb 7, 2017 at 7:39
  • How do I do that? Commented Feb 7, 2017 at 7:42

1 Answer 1

1

It will be very easy to fetch all the lat and long.

require_once "db/db_handle.php";
$select = "SELECT * FROM map";
$data = $db->query($select);
foreach ($data as $key)
            $locations[]=array( 'name'=>'Location Name', 'lat'=>$key['lat'], 'lng'=>$key['lng'] );
}
/* Convert data to json */
$markers = json_encode( $locations ); 

Then set the google map markers using the php variable markers.

<script type='text/javascript'>
        <?php
            echo "var markers=$markers;\n";

        ?>
     function initMap() {

            var latlng = new google.maps.LatLng(-33.92, 151.25); // default location
            var myOptions = {
                zoom: 10,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                mapTypeControl: false
            };

            var map = new google.maps.Map(document.getElementById('map'),myOptions);
            var infowindow = new google.maps.InfoWindow(), marker, lat, lng;
            var json=JSON.parse( markers );

            for( var o in json ){

                lat = json[ o ].lat;
                lng=json[ o ].lng;
                name=json[ o ].name;

                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(lat,lng),
                    name:name,
                    map: map
                }); 
                google.maps.event.addListener( marker, 'click', function(e){
                    infowindow.setContent( this.name );
                    infowindow.open( map, this );
                }.bind( marker ) );
            }
        }

Overall code will be :

 require_once "db/db_handle.php";
    $select = "SELECT * FROM map";
    $data = $db->query($select);
    foreach ($data as $key)
                $locations[]=array( 'name'=>'Location Name', 'lat'=>$key['lat'], 'lng'=>$key['lng'] );
    }
    /* Convert data to json */
    $markers = json_encode( $locations );
    ?>
    <!DOCTYPE html>
    <html>
      <head>
        <style>
          #map {
            height: 400px;
            width: 100%;
           }
        </style>
      </head>
      <body>
        <h3>My Google Maps Demo</h3>
        <div id="map"></div>
        <script type='text/javascript'>
        <?php
            echo "var markers=$markers;\n";

        ?>

        function initMap() {

            var latlng = new google.maps.LatLng(-33.92, 151.25); // default location
            var myOptions = {
                zoom: 10,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                mapTypeControl: false
            };

            var map = new google.maps.Map(document.getElementById('map'),myOptions);
            var infowindow = new google.maps.InfoWindow(), marker, lat, lng;
            var json=JSON.parse( markers );

            for( var o in json ){

                lat = json[ o ].lat;
                lng=json[ o ].lng;
                name=json[ o ].name;

                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(lat,lng),
                    name:name,
                    map: map
                }); 
                google.maps.event.addListener( marker, 'click', function(e){
                    infowindow.setContent( this.name );
                    infowindow.open( map, this );
                }.bind( marker ) );
            }
        }
        </script>
        <script async defer
        src="https://maps.googleapis.com/maps/api/js?key=myKey&callback=initMap">
        </script>
      </body>
    </html>
Sign up to request clarification or add additional context in comments.

1 Comment

The above answer didn't quite work for me. I needed to add/change const result = JSON.stringify(markers); var json = JSON.parse(result); to get rid of an invalid json error message in the console.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.