How to dynamically add data to google maps API?

后端 未结 2 1294
迷失自我
迷失自我 2021-01-28 23:10

I have got a map that I want to have a feed of lat/long data getting pushed to the map data array. I have the function to get the data, but am having trouble getting that to be

相关标签:
2条回答
  • 2021-01-28 23:47

    You need to actually add the item to the map. Right now, you're only adding an item to your DATA array. You need to call addMarker with the new data as well.

    You seem to want to add these markers to the map at an interval so they drop onto the map over time, while also being able to query for new markers from your server.

    Try code like this:

    var ID='0';
    var DATA=[];
    function getData(){
        var url = 'http://us7.fieldagent.net/api/newResponses/';
        $.post(url,{'id':ID},function(data){
            if(data.status_id == 0){
                ID = data.id;
                console.log('Last Id: '+data.id);
                var new_data = data.responses;
    
                var count = 0
                $.each(new_data,function(i,v){
                    count += 1;
                    var coord = 'new google.maps.LatLng('+v.lat+','+v.lon+'),';
                    DATA.push(coord);
                });
                console.log('Added '+count+' responses..');
                if (count > 0) addMarker(); //call addMarker if there are new markers
            }
        });
    }
    $(document).ready(function(){
        getData();
        setInterval(getData,20*1000);
    });
    
    function addMarker(){
        if (DATA.length == 0) return; //exit if DATA is empty
        markers.push(new google.maps.Marker({
            position: DATA.shift(), //take the first item in DATA
            map: map,
            draggable: false,
            icon: 'fatie.svg',
            animation: google.maps.Animation.DROP
        }));
        if (DATA.length > 0) setTimeout(addMarker, 500); //call again if needed
    }
    
    0 讨论(0)
  • 2021-01-28 23:51

    Create a Method which does two things.

    1. Add to the Array
    2. Add the Item to the map
    0 讨论(0)
提交回复
热议问题