【问题标题】:Google map markers are not displaying with ajax json data谷歌地图标记不显示 ajax json 数据
【发布时间】:2015-02-20 20:05:32
【问题描述】:

我从数据库表中获取latitudelongitude 并尝试在ajax success 上显示标记。我收到latitude & longitude json 格式,但是当尝试循环时,标记不显示。

我的 JSON 数据:

[
    {"latitude":"23.046100780353495","longitude":"72.56860542227514"},
    {"latitude":"23.088427701737665","longitude":"72.49273109366186"},
    {"latitude":"23.061264193197644","longitude":"72.68224525381811"},
    {"latitude":"22.977212139977677","longitude":"72.52191352774389"},
    {"latitude":"23.002180435752084","longitude":"72.47590827872045"},
    {"latitude":"23.108638843843046","longitude":"72.49444770743139"}
]

带有 Ajax 代码的 Google 地图:

<script type="text/javascript">
// Check DOM Ready
$(document).ready(function() {

    // Execute
    (function() {
        // Map options
        var options = {
            zoom: 6,
            center: new google.maps.LatLng(23.039567700000000000, 72.566004499999960000), // Centered
            mapTypeId: google.maps.MapTypeId.TERRAIN,
            mapTypeControl: false
        };

        // Init map
        var map = new google.maps.Map(document.getElementById('map_canvas'), options);

        $.ajax({
            url: 'get-locations.php',
            success:function(data){
                var obj = JSON.parse(data);
                var totalLocations = obj.length;

                for (var i = 0; i < totalLocations; i++) {

                    // Init markers
                    var marker = new google.maps.Marker({
                        position: new google.maps.LatLng(obj[i].latitude + ',' + obj[i].longitude),
                        map: map,
                        title: 'Click Me ' + i
                    });

                    // Process multiple info windows
                    (function(marker, i) {
                        // add click event
                        google.maps.event.addListener(marker, 'click', function() {
                            infowindow = new google.maps.InfoWindow({
                                content: 'Hello, World!!'
                            });
                            infowindow.open(map, marker);
                        });
                    })(marker, i);

                }

            }
        });
    })();
});
</script>

当我尝试传递静态latitude & longitude 时,循环标记内会显示:

position: new google.maps.LatLng(23.046100780353495,72.56860542227514),

但不能使用动态循环。

知道为什么不显示标记吗?

谢谢。

【问题讨论】:

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


    【解决方案1】:

    您将坐标错误地传递给google.maps.LatLng 构造函数。应该有两个参数用逗号分隔,但您将它们连接为字符串。

    代码应如下所示:

    position: new google.maps.LatLng(obj[i].latitude, obj[i].longitude)
    

    【讨论】:

      猜你喜欢
      • 2014-01-25
      • 2019-01-20
      • 2014-10-08
      • 2013-08-26
      • 1970-01-01
      相关资源
      最近更新 更多