【问题标题】:Google maps api ajax viewport marker managementGoogle maps api ajax 视口标记管理
【发布时间】:2014-09-05 04:29:26
【问题描述】:

我在使用 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 数据库中提取标记信息。我不确定我是否遗漏了什么,或者谷歌文档是否不够全面。任何帮助表示赞赏!

【问题讨论】:

  • 哪一部分你不明白? AJAX 请求? MySQL 查询?删除/加载新标记的回调?
  • AJAX 请求和删除/加载新标记的回调是我坚持的。
  • 好的。你在使用 jQuery 吗?或者你能用吗?

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


【解决方案1】:

我会给你一个使用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(); 结果查询您的数据库。

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

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

【讨论】:

    猜你喜欢
    • 2012-02-23
    • 2013-04-12
    • 2015-07-16
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    • 2011-10-30
    相关资源
    最近更新 更多