且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过while循环插入谷歌地图?

更新时间:2023-01-17 16:21:57

This is 100% working for me i've tested this code

<?php
$arr='';
$connection = mysqli_connect('localhost', 'root', '', 'users');


    function currentUsers($connection){
        $sql = "SELECT * FROM user";
        $result = mysqli_query($connection, $sql);
        $x= 0;
        if(mysqli_num_rows($result) > 0){
            while($row = mysqli_fetch_assoc($result)) {
                $userID = $row['id'];
                $firstName = $row['firstname'];
                $country = $row['country'];
                $arr[] = array($row['latitude'],$row['longitude'],$x);
                echo '<div style="width:100%;"> 
                            <div style="width:250px; height: 150px; float :left;">
                                <h3>'. $userID. ". ". $firstName. " ". $country. '</h3>
                            </div>
                            <div id  = "map_'.$x.'"  style="width:250px;height: 150px;">   </div>
                      </div>';
                       $x++;
            }
        echo '<script> var mymaps ='.json_encode($arr).'</script>';

        }else{
            echo "Currently there are no users!";
        }

        mysqli_close($connection);
    }
    currentUsers($connection);
?>

<script type="text/javascript" src="http://maps.google.com/maps/api/js"></script>

<script>
var maps = []; 

function initialize(id, myLatLng) { 
    geocoder = new google.maps.Geocoder();
    var mapOptions = {
        zoom: 9,
        center: myLatLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    maps[id] = new google.maps.Map(document.getElementById('map_'+id), 
        mapOptions);

    var marker = new google.maps.Marker({
       map: maps[id],
       position: myLatLng,
       title: 'Hello World!'
    });
}

$(document).ready(function(){
    for( var i = 0; i < mymaps.length; i++)
    {
        var x = parseFloat(mymaps[i][0]);
        var y = parseFloat(mymaps[i][1]);
        var myLatLng = {lat: x, lng: y};
        google.maps.event.addDomListener(window, 'load', initialize(mymaps[i][2],myLatLng)); // two calls
    }

});
</script>