当新标记位置插入数据库时​​,更新谷歌地图上的多个标记位置

时间:2016-11-03 12:11:08

标签: javascript php codeigniter google-maps google-maps-api-3

我正在开发“从Google数据库动态自动更新Google地图上的多个标记位置”。当我刷新页面时,该时间标记自动更新。但是当我在数据库中插入新位置(lat,lng)时,每次我想更新谷歌地图上的标记位置。它就像现场跟踪系统。

脚本:

<?php
include('header.php');

$query = $this->db->query("SELECT m.*, d.name FROM `map` as m  LEFT JOIN device as d ON d.id = m.device_id WHERE m.id IN ( SELECT MAX(id) FROM `map` GROUP BY device_id);");
$result = $query->result();

?>

<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyAbaTTWnkEvs_H4uKBDv_-OLN_wMYxjx0M" type="text/javascript"></script>

<!--main content start-->
<section id="main-content">
    <section class="wrapper">
        <!-- page start-->
        <div class="row">
            <div class="col-lg-12">
                <!--breadcrumbs start -->
                <ul class="breadcrumb">
                    <li class="active"><a href=""><i class="fa fa-home"></i> Home</a></li>
                </ul>
                <!--breadcrumbs end -->
            </div>
        </div>
        <div class="row">
            <div class="col-lg-12">
                <section class="panel">
                    <header class="panel-heading"> Timeline <span class="tools pull-right"></span></header>
                    <div class="panel-body profile-activity">

                        <div id="map_2385853" style="width: 100%; height: 655px;"></div>

                        <input type="button" value="Reload markers" id="reloadMarkers" class="form-control">

                    </div>
                </section>
            </div>
        </div>
        <!-- page end-->
    </section>
</section>
<!--main content end-->

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">

    var map = new google.maps.Map(document.getElementById('map_2385853'), {
        zoom: 5,
        maxZoom: 8,
        minZoom: 1,
        streetViewControl: false,
        center: new google.maps.LatLng(20.5937, 78.9629),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    //initial dataset for markers
    var locs = {

        1: { info:'Demo', lat:31.933517, lng:74.910278 },
        2: { info:'Demo', lat:32.073266 , lng:76.997681 },
        3: { info:'Demo', lat:32.23139 , lng:78.425903 },

    };

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

    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: "<?php echo base_url().'index.php/home/index'; ?>",//The resource that delivers loc data.
            dataType: "json"//The type of data tp be returned by the server.
        },
        delay: 10000,//(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.

    function myTimer() {

        var testLocs = {

            <?php $count = 1; if(empty($result)){ } else {
            foreach ($result as $map){ ?>
            <?php echo $count++; ?>: { info:'<?php echo $map->name; ?>', lat:<?php echo $map->latitude; ?>, lng:<?php echo $map->longitude; ?> },
            <?php } } ?>
        };

        setMarkers(testLocs);
    }
    var myVar = setInterval(function(){ myTimer() }, 3000);

</script>

<?php include('footer.php'); ?>

修改

我已经关注了这个JSFiddle链接。 JSFiddle

1 个答案:

答案 0 :(得分:2)

删除var ajax ...代码并使用下面的

window.setInterval(function(){
        getnewmarker(); /// call your function here
}, 5000);


// Ajex call wchich set updated data
function getnewmarker()
{
    var url = "<?php echo site_url('index.php/home/index'); ?>";  // your url

    $.ajax({
            url: url,
            type: 'post',
            data: {},
            dataType : 'json',
            success: function(data) {

                locs = data;
                setMarkers(locs);

            },

        });// end ajax call
}

确保您的控制器(由ajax调用)将返回数组的json(echo json_encode($ array))具有类似

的结构
$array = array(
            '1' => array( "info"=>'Demo', "lat"=>31.933517, "lng"=>74.910278 ),
            '2' => array( "info"=>'Demo', "lat"=>32.073266 , "lng"=>76.997681 ),
            '3' => array( "info"=>'Demo', "lat"=>32.23139 , "lng"=>78.425903 ),
    );