Как нарисовать живую полилинию в Google Maps API

Я использую Карты Google с кодом ниже, чтобы:

  • отобразить карту с GPS-трек (полилинии), которая генерируется из данных MySQL. Линия пассивна.
  • отобразить фактический маркер. Макрер обновляется каждые 2 секунды.

Я хочу продолжать рисовать ломаную линию.

Я могу представить, что мне нужно добавить новые данные маркера в существующий массив с данными полилинии, но я не знаю, как это сделать. Буду признателен за любую помощь

<script>
var locations = {};//A repository for markers (and the data from which they were contructed).

//initial dataset for markers
var locs = {
    1: { info:'11111. Some random info here', lat:50.03, lng:20.20 },
    2: { info:'22222. Some random info here', lat:46.0553, lng:14.5144 },
    3: { info:'33333. Some random info here', lat:-33.7333, lng:151.0833 },
    4: { info:'44444. Some random info here', lat:27.9798, lng:-81.731 }
};
var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 13,
    maxZoom: 30,
    minZoom: 6,
    streetViewControl: false,
    center: new google.maps.LatLng(<?=$last_position; ?>),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});


//////////////////// Passive Tracks
var flightPlanCoordinates = [

    //get data from PHP
    <?php foreach ($gps_data as $data): ?>
        <?php echo "{lat: ".$data['lat'].", lng: ".$data['lon']."},"; ?>
    <?php endforeach ?>

    ];

var flightPath = new google.maps.Polyline({
  path: flightPlanCoordinates,
  geodesic: true,
  strokeColor: '#0000FF',
  strokeOpacity: 0.7,
  strokeWeight: 4
});

flightPath.setMap(map);

//////////////////// End Tracks


var infowindow = new google.maps.InfoWindow();

var auto_remove = true;//When true, markers for all unreported locs will be removed.

function setMarkers(locObj) {
    if(auto_remove) {
        //Remove markers for all unreported locs, and the corrsponding locations entry.
        $.each(locations, function(key) {
            if(!locObj[key]) {
                if(locations[key].marker) {
                    locations[key].marker.setMap(null);
                }
                delete locations[key];
            }
        });
    }

    $.each(locObj, function(key, loc) {
        if(!locations[key] && loc.lat!==undefined && loc.lng!==undefined) {
            //Marker has not yet been made (and there's enough data to create one).

            //Create marker
            loc.marker = new google.maps.Marker({
                position: new google.maps.LatLng(loc.lat, loc.lng),
                map: map
            });

            //Attach click listener to marker
            google.maps.event.addListener(loc.marker, 'click', (function(key) {
                return function() {
                    if(locations[key]) {
                        infowindow.setContent(locations[key].info);
                        infowindow.open(map, locations[key].marker);
                    }
                }
            })(key));

            //Remember loc in the `locations` so its info can be displayed and so its marker can be deleted.
            locations[key] = loc;
        }
        else if(locations[key] && loc.remove) {
            //Remove marker from map
            if(locations[key].marker) {
                locations[key].marker.setMap(null);
            }
            //Remove element from `locations`
            delete locations[key];
        }
        else if(locations[key]) {
            //Update the previous data object with the latest data.
            $.extend(locations[key], loc);
            if(loc.lat!==undefined && loc.lng!==undefined) {
                //Update marker position (maybe not necessary but doesn't hurt).
                locations[key].marker.setPosition(
                    new google.maps.LatLng(loc.lat, loc.lng)
                );
            }
            //locations[key].info looks after itself.
        }
    });
}

var ajaxObj = {//Object to save cluttering the namespace.
    options: {
        url: "<?=base_url(); ?>gps/get_markers/",//The resource that delivers loc data.
        dataType: "json"//The type of data tp be returned by the server.
    },
    delay: 2000,//(milliseconds) the interval between successive gets.
    errorCount: 0,//running total of ajax errors.
    errorThreshold: 5,//the number of ajax errors beyond which the get cycle should cease.
    ticker: null,//setTimeout reference - allows the get cycle to be cancelled with clearTimeout(ajaxObj.ticker);
    get: function() { //a function which initiates 
        if(ajaxObj.errorCount < ajaxObj.errorThreshold) {
            ajaxObj.ticker = setTimeout(getMarkerData, ajaxObj.delay);
        }
    },
    fail: function(jqXHR, textStatus, errorThrown) {
        console.log(errorThrown);
        ajaxObj.errorCount++;
    }
};

//Ajax master routine
function getMarkerData() {
    $.ajax(ajaxObj.options)
      .done(setMarkers) //fires when ajax returns successfully
      .fail(ajaxObj.fail) //fires when an ajax error occurs
      .always(ajaxObj.get); //fires after ajax success or ajax error
}

setMarkers(locs);//Create markers from the initial dataset served with the document.
ajaxObj.get();//Start the get cycle.


</script>
<!-- map-->

0 ответов

Другие вопросы по тегам