Итерация по файлу JSON для отображения нескольких полилиний - PullRequest
2 голосов
/ 02 января 2012

Я пытаюсь отобразить карту с несколькими полилиниями, которые извлекаются из внешнего ресурса JSON.Каждая запись JSON имеет несколько описательных полей, а также поле, содержащее массив LatLngs.Код, кажется, получает данные JSON просто отлично и анализирует их соответствующим образом.Затем я перебираю каждую запись, отображающую полилинию, но по какой-то причине не могу отобразить ее на карте.Я впервые использую Google Maps API.Я, вероятно, делаю что-то глупое, но, просмотрев столько примеров, сколько смог найти, не могу найти ничего явно неправильного.Все предложения с благодарностью получены.

Основа для кода для отображения полилиний была взята из следующего примера: http://code.google.com/intl/no/apis/maps/documentation/javascript/examples/polyline-simple.html

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
     #map_canvas {
        width: 1024px;
        height: 700px;
      }
</style>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

<script type="text/javascript">

function initialize(){
    var latlng = new google.maps.LatLng(0, 23);
    var myOptions = {
      zoom: 4,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    var url = "http://webstore.thedatahub.org/stevesong/afterfibre/testdata2.json?_limit=3";
    var path = [];
        $.getJSON(url, function (data) {

            //  Parse the Linestring field into an array of LatLngs
            $.each(data.data, function(index, record) {
                line = JSON.parse(record.Linestring);

                //  Parse the array of LatLngs into Gmap points
                for(var i=0; i < line.length; i++){
                    path.push(new google.maps.LatLng(line[1],line[0]));
                }
                var polyline = new google.maps.Polyline({
                  path: path,
                  strokeColor: '#ff0000',
                  strokeOpacity: 1.0,
                  strokeWeight: 3
                });

                polyline.setMap(map);

            });

        });
    }

    // google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body onload="initialize()">
  <div id="map_canvas"></div>
</body>
</html>

Ответы [ 2 ]

1 голос
/ 07 января 2012

Спасибо Грегу Малкнехту за предоставленную последнюю часть головоломки.Чтобы каждая запись JSON отображалась уникальным образом, а не одной гигантской ломаной, необходимо повторно инициализировать массив ломаных ПОСЛЕ каждой итерации «.each».Вот окончательная версия, которая, наконец, делает то, что я был после.Спасибо Митч и Грег.

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
     #map_canvas {
        width: 1024px;
        height: 700px;
      }
</style>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

<script type="text/javascript">

function initialize(){
    var latlng = new google.maps.LatLng(0, 23);
    var myOptions = {
      zoom: 4,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    var url = "http://webstore.thedatahub.org/stevesong/afterfibre/testdata2.json?_limit=5";

        $.getJSON(url, function (data) {

            //  Parse the Linestring field into an array of LatLngs
            $.each(data.data, function(index, record) {
                var mypath = new Array();
                line = JSON.parse(record.Linestring);
                //  Parse the array of LatLngs into Gmap points
                for(var i=0; i < line.length; i++){
                    //Tokenise the coordinates
                    var coords = (new String(line[i])).split(",");
                    mypath.push(new google.maps.LatLng(coords[1], coords[0]));
                }
                var polyline = new google.maps.Polyline({
                    path: mypath,
                    strokeColor: '#ff0000',
                    strokeOpacity: 1.0,
                    strokeWeight: 3
                });
                polyline.setMap(map);
            });

        });
    }

    // google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body onload="initialize()">
  <div id="map_canvas"></div>
</body>
</html>
0 голосов
/ 05 января 2012

Проблема не заключалась в маркировке координат при прохождении по «линиям»

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
     #map_canvas {
        width: 1024px;
        height: 700px;
      }
</style>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"         type="text/javascript"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?    sensor=false"></script>

<script type="text/javascript">

function initialize(){
    var latlng = new google.maps.LatLng(0, 23);
    var myOptions = {
      zoom: 4,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    var url = "http://webstore.thedatahub.org/stevesong/afterfibre/testdata2.json?    _limit=3";
    var mypath = new Array();
        $.getJSON(url, function (data) {

            //  Parse the Linestring field into an array of LatLngs
            $.each(data.data, function(index, record) {
                line = JSON.parse(record.Linestring);
        //  Parse the array of LatLngs into Gmap points
        for(var i=0; i < line.length; i++){
        //Tokenise the coordinates
        var coords = (new String(line[i])).split(",");
                    mypath.push(new google.maps.LatLng(coords[1], coords[0]));
        }
                var polyline = new google.maps.Polyline({
                  path: mypath,
                  strokeColor: '#ff0000',
                  strokeOpacity: 1.0,
                  strokeWeight: 3
                });

                polyline.setMap(map);

            });

        });
    }

    // google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body onload="initialize()">
  <div id="map_canvas"></div>
</body>
</html>
...