javascript - Google map 使用 php 和 jquery 动态显示许多标记

标签 javascript php jquery google-maps google-maps-api-3

我有一个 Google map ,我想将其链接到数据库,以便使用 PHP 和 MySQL 动态显示许多标记。

下面是我的代码

<?php
//This creates an array from the database and allows us to use it later in the jquery
//CREATE SQL STATEMENT
$sql_locations = "SELECT * FROM tbllocations";

//CONNECT TO MYSQL SERVER
require('test-connection.php');

//EXECUTE SQL STATEMENT
$rs_locations = mysqli_query($vconnection, $sql_locations);

//CREATE AN ASSOCIATIVE ARRAY
$rs_locations_rows = mysqli_fetch_assoc($rs_locations);
$place = $rs_location_rows['place'];
$city = $rs_location_rows['city'];
$long = $rs_location_rows['long'];
$lat = $rs_location_rows['lat'];
?>
<div id="map_wrapper">
    <div id="map_canvas" class="mapping"></div>
</div>


<style>

#map_wrapper {
    height: 400px;
}

#map_canvas {
    width: 100%;
    height: 100vh;
}


</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>

jQuery(function($) {
    // Asynchronously Load the map API 
    var script = document.createElement('script');
    script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
    document.body.appendChild(script);
});

function initialize() {
    var map;
    var bounds = new google.maps.LatLngBounds();
    var mapOptions = {
        mapTypeId: 'roadmap'
    };

    // Display a map on the page
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    map.setTilt(45);

    // Multiple Markers
    var markers = [


       <?php do{?>

        ['<?php echo $place . ", " . $city;?>', <?php echo $long . "," . $lat;?>],

        <?php } while($rs_location_rows = mysqli_fetch_assoc($rs_location))?>

        ['Palace of Westminster, London', 51.499633,-0.124755]


        //['London Eye, London', 51.503454,-0.119562],
        //['Palace of Westminster, London', 51.499633,-0.124755]
    ];

    // Info Window Content
    var infoWindowContent = [
        ['<div class="info_content">' +
        '<h3>London Eye</h3>' +
        '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>' +        '</div>'],
        ['<div class="info_content">' +
        '<h3>Palace of Westminster</h3>' +
        '<p>The Palace of Westminster is the meeting place of the House of Commons and the House of Lords, the two houses of the Parliament of the United Kingdom. Commonly known as the Houses of Parliament after its tenants.</p>' +
        '</div>']
    ];

    // Display multiple markers on a map
    var infoWindow = new google.maps.InfoWindow(), marker, i;

    // Loop through our array of markers & place each one on the map  
    for( i = 0; i < markers.length; i++ ) {
        var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
        bounds.extend(position);
        marker = new google.maps.Marker({
            position: position,
            map: map,
            title: markers[i][1]
        });

        // Allow each marker to have an info window    
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
                infoWindow.setContent(infoWindowContent[i][0]);
                infoWindow.open(map, marker);
            }
        })(marker, i));

        // Automatically center the map fitting all markers on the screen
        map.fitBounds(bounds);
    }

    // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
    var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
        this.setZoom(16);
        google.maps.event.removeListener(boundsListener);
    });

}



</script>

问题是我从 php 中的关联数组中获取所有标记变量,如果我回显它们,它们就会显示。然而,当我在 do while 循环中通过 jquery 函数传递它们时,它只在 map 上显示两个标记,而不是所有标记。

我的理论是,我没有在 jquery 中正确编写 for 循环,这导致代码只显示两个标记。

最佳答案

我猜,问题是你定义了变量 $place , $city , $long一旦你就永远不会覆盖它。

所以也许你有两个以上的标记,但除了 [ 'Palace of Westminster, London', 51.499633, -0.124755] 之外的所有标记是相同的标记。

更新:工作示例,注释掉你的sql内容,并在标记数组中写入一些坐标。你必须调整你的infoWindowContent如果您的数据库中有此信息,您也可以将其添加到 php $marker数组或创建一个新数组,例如 $marker在这个例子中。

结果:我得到了所有定义的标记。如果这有效,请尝试删除评论 //从您需要的东西中,如果您仍然遇到问题,请在您的 foreach 中尝试此操作用于调试:

foreach( $rs_locations as $rs_location ) {
  var_dump( $rs_location );
  ......

工作示例:

//This creates an array from the database and allows us to use it later in the jquery
//CREATE SQL STATEMENT
$sql_locations = "SELECT * FROM tbllocations";

//CONNECT TO MYSQL SERVER
//<---------   require('test-connection.php');
//EXECUTE SQL STATEMENT
//<---------   $rs_locations = mysqli_query($vconnection, $sql_locations);

$markers = array(
    // your example['Palace of Westminster, London', 51.499633,-0.124755]
    array(
        'Palace of Westminster, London',
        51.499633,
        -0.124755
    ),
    array(
        'Westminster Abbey, London',
        51.4992453,
        -0.1272561
    ),
    array(
        'QEII Centre, London',
        51.4997296,
        -0.128683
    ),
    array(
        'Winston Churchill Statue, London',
        51.5004308,
        -0.1275243
    ),
    array(
        'Fitzroy Lodge Amature Boxing Club, London',
        51.4954215,
        -0.1154758
    ),
    array(
        'Balham Boxing Club, London',
        51.4419539,
        -0.1336075
    )
);

// use this for your code
//foreach( $rs_locations as $rs_location ) {
//  $markers[] = array(
//      "{$rs_location['place']}, {$rs_location['city']}",
//      $rs_location['long'],
//      $rs_location['lat']
//  );
//}
?>
<div id="map_wrapper">
    <div id="map_canvas" class="mapping"></div>
</div>


<style>

    #map_wrapper {
        height: 400px;
    }

    #map_canvas {
        width: 100%;
        height: 100vh;
    }


</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>

    function initialize() {
        var map;
        var bounds = new google.maps.LatLngBounds();
        var mapOptions = {
            mapTypeId: "roadmap",
            center: new google.maps.LatLng(52.791331, -1.918728), // somewhere in the uk BEWARE center is required
            zoom: 3,
        };

        // Display a map on the page
        map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
        map.setTilt(45);

        // Multiple Markers
        var markers = <?php echo json_encode( $markers ); ?>;

        // Info Window Content
        var infoWindowContent = [
            ['<div class="info_content">' +
            '<h3>London Eye</h3>' +
            '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>' + '</div>'],
            ['<div class="info_content">' +
            '<h3>Palace of Westminster</h3>' +
            '<p>The Palace of Westminster is the meeting place of the House of Commons and the House of Lords, the two houses of the Parliament of the United Kingdom. Commonly known as the Houses of Parliament after its tenants.</p>' +
            '</div>']
        ];

        // Display multiple markers on a map
        var infoWindow = new google.maps.InfoWindow();
        var marker, i;

        // Loop through our array of markers & place each one on the map
        for (i = 0; i < markers.length; i++) {
            var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
            bounds.extend(position);
            marker = new google.maps.Marker({
                position: position,
                map: map,
                title: markers[i][0]
            });

            // Allow each marker to have an info window
            google.maps.event.addListener(marker, 'click', (function (marker, i) {
                return function () {
                    infoWindow.setContent(infoWindowContent[i][0]);
                    infoWindow.open(map, marker);
                }
            })(marker, i));

            // Automatically center the map fitting all markers on the screen
            map.fitBounds(bounds);
        }

        //Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
        var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function (event) {
            this.setZoom(10);
            google.maps.event.removeListener(boundsListener);
        });

    }
    google.maps.event.addDomListener(window, 'load', initialize);


</script>

编辑:删除了重复的 div <div id="map_canvas"></div>从我的例子来看

关于javascript - Google map 使用 php 和 jquery 动态显示许多标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33652498/

相关文章:

jquery - 在 scala.js 中实现 jquery-ui

javascript - Kendo UI Grid 可编辑手动 dataItem.set() 慢/延迟

javascript - 更改日期选择器上的日期格式

javascript - 放大弹出窗口中的混合内容类型

javascript - 使用相同的 css 文档在不同的 html 页面上使用不同的链接颜色

javascript - 如何动态创建参数名称

php - FPDF 背景图像 : what size for a good A4 background

php - 无需下载整个文件即可读取 ID3 标签

javascript - XMLHttpRequest 失败 : {statusText":Not Found","status::404,"responseURL":https://api. parse.com/1/users"Ionic + Parse

php - 具有依赖项的可测试 Controller