2

我正在尝试制作带有标记的谷歌地图 api,它将显示某些地方的纬度和经度。我正在尝试使用 json 文件执行此操作,但它不起作用.. 这是我的代码..

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Cluster Map</title>

    <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js" type="text/javascript"></script>

    <script type="text/javascript">
        var map;
        var markers = [];

        function initialize() {
            geocoder = new google.maps.Geocoder();
            var center = new google.maps.LatLng(43.474144,-112.03866);
            map = new google.maps.Map(document.getElementById('map'), {
                zoom: 7,
                center: center,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });
            markMultiple();
        }

        function markMap(latLng, content){
            var marker = new google.maps.Marker({
                position: latLng
            });
            google.maps.event.addListener(marker, 'click', function() {
                infowindow.setContent(content);
                infowindow.open(map, marker);
            });

            markers.push(marker);
        }
        function markMultiple(){
            $.parseJSON('test.json', function(data) {
                $.each(data.markers, function(i, obj) {
                    var latLng =  new google.maps.LatLng(obj.lat,obj.lng);
                    var content = obj.id + ':' + obj.lat + ',' + obj.lng;

                    markMap(latLng, content);
                });
            });


             var markerCluster = new MarkerClusterer(map, markers);
        }



        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</head>
<body>
    <div id="map-container">
        <div id="map"></div>
    </div>
</body>

请帮我..

4

1 回答 1

0

工程师是对的,你需要使用 $.getJSON 方法,$.parseJSON 接受一个 JSON 字符串,它不加载外部文件。

getJSON:http: //api.jquery.com/jQuery.getJSON/ parseJSON:http ://api.jquery.com/jQuery.parseJSON/

我将您的代码放在 jsFiddle 中,它正在使用 getJSON 和替代测试 JSON 文件(您没有提供您正在使用的原始 test.json)。

$.getJSON('test.json', function(data) {
                $.each(data.markers, function(i, obj) {
                    var latLng =  new google.maps.LatLng(obj.lat,obj.lng);
                    var content = obj.id + ':' + obj.lat + ',' + obj.lng;

                    markMap(latLng, content);
                });
            });

http://jsfiddle.net/WYfjv/

如果您的代码不工作,可能您的 JSON 格式不正确(尝试 JSONLINT 来测试它)。另外,如果您已经在改进,我建议您使用普通的 for 循环而不是 $.each :)

于 2013-09-03T17:47:03.940 回答