显示位置的变化在谷歌地图上没有重新加载地图一次又一次


Show change of location on Google map without reloading the map again and again

每隔30秒,我希望在不重新加载地图的情况下重新加载谷歌地图上的位置。我已经做了以下工作:

  1. 使用gps设备的URL获取其内容。
  2. 从Url获取经纬度
  3. 在地图上显示经纬度。
我的代码是:
 <?php
    // hard coded latitude and longitude for an example
    $latitude = 28.70956;
    $longitude = 70.00767;
//In my code i have to fetch it from url every 30 seconds. And then Show them on the map
?>
<!doctype html>
<html>
    <head>
        <script type="text/javascript" src="http://maps.googleapis.com/maps/api
/js?sensor=false"></script>
        <script type="text/javascript">
        var map;
        function initialize() {
            // Set static latitude, longitude value
            var latlng = new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>);
            // Set map options
            var myOptions = {
                zoom: 16,
                center: latlng,
                panControl: true,
                zoomControl: true,
                scaleControl: true,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            // Create map object with options
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        <?php

                echo "addMarker(new google.maps.LatLng(".$latitude.", ".$longitude."), map);";
        ?>
        }
        function addMarker(latLng, map) {
            var marker = new google.maps.Marker({
                position: latLng,
                map: map,
                draggable: true, // enables drag & drop
                animation: google.maps.Animation.DROP
            });
            return marker;
        }
        </script>
    </head>
    <body onload="initialize()">
        <div style="float:left; position:relative; width:1519px; border:0px #000 solid;">
            <div id="map_canvas" style="width:950px;height:900px;border:solid black 1px;"></div>
        </div>
    </body>
</html>

在这段代码中,我正在执行获取位置并在地图上显示它的所有步骤。但是我怎样才能在一段固定的时间后动态地获得位置呢?我的问题不包含任何硬编码值,每次值需要从URL获取

您可以使用setInterval和Ajax调用的组合。如果php变量每次都在变化,则需要在不加载页面的情况下使用Ajax获取数据。类似这样的内容(如果您使用JQuery)。

setInterval(function() {
    var coords = getLatLng(); // Grab the coordinates from url
    updateMapMarker(coords); // Similar to what you've got
}, 30000); // 30 seconds
function getLatLng() {
    $.ajax({
        url: "your/route/that/returns/coordinates",
        success: function(data) {
            return [data.x, data.y];
        },
    });
}

点击这里查看JQuery Ajax:http://api.jquery.com/jquery.ajax/