不显示带有本地json文件数据的谷歌地图脚本

Google Map script with local json file data not displaying

本文关键字:数据 文件 谷歌地图 脚本 json 显示      更新时间:2023-09-26

我正在尝试在地图上显示一些json标记。

地图实际上出现了,但没有显示任何指针,地图的位置也偏离了

这是js代码:

<script>
    $('#map_canvas').gmap().bind('init', function() { 
    // This URL won't work on your localhost, so you need to change it
    // see http://en.wikipedia.org/wiki/Same_origin_policy
    $.getJSON( 'locations.json', function(data) { 
        $.each( data.markers, function(i, marker) {
            $('#map_canvas').gmap('addMarker', { 
                'position': new google.maps.LatLng(marker.latitude, marker.longitude), 
                'bounds': true 
            }).click(function() {
                $('#map_canvas').gmap('openInfoWindow', {'content': marker.content }, this);
            });
        });
    });
});
</script>

这里是json文件的内容:

{"locations":[{"id":"14","location":"(50.8765125,
 -1.1504182944499557)"}]}

代码有什么问题吗?

根据json文件的结构,我认为您正在尝试访问data.markers中每个项的未定义属性。locations是具有两个属性的对象数组:idStringlocations是长度为2的array。那么为什么要使用这个代码呢?

marker.latitude
marker.longitude
marker.content

也许你应该试试

marker.location[0]
marker.location[1]

首先,您应该确认您的json输出:

$.getJSON( 'locations.json', function(data) { 
    console.log(data);
}

把它贴在你的问题上。。。

如果可以的话,试试这样:

$.each( data.markers, function(i, marker) {
        $('#map_canvas').gmap('addMarker', { 
            'position': new google.maps.LatLng(marker.location[0], marker.location[1]), 
            'bounds': true 
        }).click(function() {
            $('#map_canvas').gmap('openInfoWindow', {'content': marker.id }, this);
        });
    });

事实上,我不知道为什么你也使用data.marker而不是data.locations