dennis ramli dennis ramli - 18 days ago 16
MySQL Question

multiple marker on googlemaps from php and mysql

i try to make multiple markers on googlemaps and taking data from database.
this is my code

http://pastebin.com/w4pvLyK5
but this code only show 1 values from database
how can i show a multiple markers with database?

Answer

The initial sql query has a redundant where clause due to 1=1 but I assume that is for testing. The markers variable in the original code is being over-written on each iteration through the loop so the array will only have one item.

<?php
    /* lat/lng data will be added to this array */
    $locations=array();
    $query =  $db->query('SELECT * FROM tbl_kabkot WHERE 1=1 AND latitude !=0 AND longitude !=0');
        while( $row = $query->fetch() ){

            $nama_kabkot = $row['nama_kabkot'];
            $longitude = $row['longitude'];                              
            $latitude = $row['latitude'];

            /* Each row is added as a new array */
            $locations[]=array( 'name'=>$nama_kabkot, 'lat'=>$latitudem, 'lng'=>$longitude );
        }
        /* Convert data to json */
        $markers = json_encode( $locations );
?>
<script type='text/javascript'>
    <?php
        echo "var markers=$markers;\n";

    ?>

    function initMap() {

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

        var map = new google.maps.Map(document.getElementById("peta"),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>
Comments