谷歌地图api ajax视口标记管理

时间:2014-07-15 05:24:13

标签: javascript ajax google-maps google-maps-api-3

我在使用google maps API实现视口标记管理方面遇到了一些麻烦。我可以在这里找到以下文档:

https://developers.google.com/maps/articles/toomanymarkers#viewportmarkermanagement

我与之合作的部分名为"视口标记管理。"

我可以按照代码执行此操作:

function showMarkers() {

    var bounds = map.getBounds();

    // Call you server with ajax passing it the bounds
    // In the ajax callback delete the current markers and add new markers
}

我不知道我需要使用哪些代码来完成注释掉的行上的指令。我现在正在从mySQL数据库中提取标记信息,如果这很重要的话。我不确定我是否遗漏了某些内容,或者Google文档是否足够全面。感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

我将使用jQuery.ajax(),PHP和MySQL给你一个例子,假设你正在使用它。

基本上,您需要侦听地图的bounds_changed事件,将地图边界发送到后端,使用边界查询数据库,返回正确的标记,清除地图中的标记并更新用新的标记。

以下是一个示例JS代码:

var markers = [];

function showMarkers() {

    for (var i = 0; i < markers.length; i++) {

        markers[i].setMap(null);
    }

    var bounds = map.getBounds();

    // Call you server with ajax passing it the bounds
    // In the ajax callback delete the current markers and add new markers

    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();

    $.ajax({

        url: 'your_backend_page.php',
        cache: false,
        data: {
            'fromlat': southWest.lat(),
            'tolat': northEast.lat(),
            'fromlng': southWest.lng(),
            'tolng': northEast.lng()
        },

        dataType: 'json',
        type: 'GET',

        async: false,

        success: function (data) {

            if (data) {

                $.each(data, function (i, item) {

                    createMarker(item);
                });
            }
        }
    });
}

function createMarker(item) {

    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(item.lat, item.lng),
        map: map,
        draggable: false
    });

    markers.push(marker);
    marker.setMap(map);
}

然后在您的后端页面中,使用参数(fromlat,tolat等)和echo json_encode();结果查询数据库。

showMarkers()地图事件监听器调用bounds_changed函数。如果您不了解事件监听器,请参阅documentation

代码未经测试,但您明白了!