javascript - 谷歌地图更新标记位置而不删除它们

标签 javascript php google-maps marker

我已经初始化了谷歌地图 API v3 并使用 setInterval 重新加载 xml 标记列表并将它们显示在 map 上,因此我能够在 map 上实时更新标记位置,甚至显示它们正在移动。

这基本上是通过删除所有标记,然后在每次重新加载新数据时重新创建它们来实现的。

我想在这段代码中实现的是,而不是删除标记,更新它们的位置,这应该有助于消除每个页面重新加载时的闪烁,我确实找到了其他答案,这些答案对我特定的方式没有帮助已经做到了。

另一件事是,目前我正在根据某个类(class)值更改如下所示的标记图标/图像,如何将其更改为具有多个条件,例如类(class) x = image = x.jpg (等等)在这里我什至想定义如果 speed = x 那么图像 xy.jpg 所以总共有两个问题。

 <script>
// COUNTER 
var k=1;
function myFunction()
{
setInterval(function(){
document.getElementById('spanSecond').innerHTML=10-k;
k++;
if(k>10){ k=1; timeout(); }
},1000);
}
myFunction();

var num=<?php echo $num;?>; 
// In the following example, markers appear when the user clicks on the map.
// The markers are stored in an array.
// The user can then click an option to hide, show or delete the markers.
var map;
var markers = [];

function initialize() {
  var haightAshbury = new google.maps.LatLng(<?php echo $cLat;?>, <?php echo $cLong; ?>);
  var mapOptions = {
    zoom: 5,
    center: haightAshbury,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);



timeout();    
}


function timeout() { 


 downloadUrl("all__xml.php?UID=1", function(data) {
        var xml = data.responseXML;
        deleteMarkers();
        var markers = xml.documentElement.getElementsByTagName("marker");       

         for (var i = 0; i < markers.length; i++) { 
              var name = markers[i].getAttribute("name");
              var course = markers[i].getAttribute("course");
              var dt_image = markers[i].getAttribute("dt_image");
              var time = markers[i].getAttribute("deviceTime");
              var speed = markers[i].getAttribute("speed");
              var label = markers[i].getAttribute("deviceId");
              var tdiff = markers[i].getAttribute("tdiff");
            var Lat=parseFloat(markers[i].getAttribute("lat"));
            var Lng=parseFloat(markers[i].getAttribute("lng")); 
            var point = new google.maps.LatLng(Lat,Lng);

  if(tdiff>=2)
  { 
  var Acc="Off";
  speed=0; 
  }
  else var Acc="On"; 

  // data sending stop before 2 min => Acc off
  if(speed>1) {
  var status=Math.round(speed*1.852) + " moving"; 
  }
  else { 
  var status="stopped"; // moving status according to speed
  speed=0;
  }

  var html ='<div style="margin:1px !important; font-size:12px;">' + "<b>" + name + "</b> <br/>Angle : " + course + "<br/> Last Updated : " + time + "<br/> Acc : " + Acc + "<br/> Speed : " + Math.round(speed*1.852) + " kmph<br/>Lat : " + Lat + "<br/>Lng : " + Lng + "<br/>" + "<a href=tracking.php?DID=" + label + ">Tracking</a>" + " " + "<a href=playback.php?PlayBackDeviceId=" + label + "&Reset=1>Play Back</a>" + " " + "<a href=daily_distance_report.php?vehicle="+ label +">Reports</a>" + " " + "<a href=draw_geo_fence.php?deviceid="+ label+"&mapLat="+ Lat +"&mapLong="+ Lng +">Geo-Fence</a>"  + '</div>' ;

 //document.getElementById("status"+label).innerHTML=status; // show status in div tag



// Add a marker when click on the map

    addMarker(point,dt_image,course,html,name,i);

            }// loop end here     


   });   // downloadUrl end here 
}

// Add a marker to the map and push to the array.
function addMarker(location,image,course,html,name,i) {
    if(course<=22.5)
        {
            image = "images/"+image+"0.png"; // 0 angle img
        }
        else if (course<=67.5)
        {
            image = "images/"+image+"45.png"; // 45 angle img   
        }
        else if (course<=112.5)
        {
            image = "images/"+image+"90.png"; // 90 angle img   
        }
        else if (course<=157.5)
        {
            image = "images/"+image+"135.png"; // 135 angle img 
        }
        else if (course<=202.5)
        {
            image = "images/"+image+"180.png"; // 180 angle img 
        }       
        else if (course<=247.5)
        {
            image = "images/"+image+"225.png"; // 225 angle img 
        }
        else if (course<=292.5)
        {
            image = "images/"+image+"270.png"; // 270 angle img
        }       
        else
        {
            image = "images/"+image+"315.png"; // 315 angle img 
        }



  var marker = new MarkerWithLabel({
    position: location,
    icon:image,
    labelContent: name,
    labelAnchor: new google.maps.Point(22, 0),
    labelClass: "labels", // the CSS class for the label
    labelStyle: {opacity: 0.75},
    map: map    
  });

var infoWindow = new google.maps.InfoWindow({maxWidth:400});
google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
markers.push(marker); 


}

// Sets the map on all markers in the array.
function setAllMap(map) {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(map);
    // Try update value here
  }
}

// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
  setAllMap(null);
  markers = [];
}

google.maps.event.addDomListener(window, 'load', initialize);

    function downloadUrl(url, callback) {
      var request = window.ActiveXObject ?
          new ActiveXObject('Microsoft.XMLHTTP') :
          new XMLHttpRequest;

      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          request.onreadystatechange = doNothing;
          callback(request, request.status);
        }
      };


      request.open('GET', url, true);
      request.send(null);

    }
    function doNothing() {}



///////////////////////////////////////////////////////////////

var geocoder = new google.maps.Geocoder();
//get geo location by name
function GetAddressByGoogle(t, lat, lng) {
    if (!geocoder) {
        geocoder = new google.maps.Geocoder();
    }
    if (lat != 0) {
        var latlng = new google.maps.LatLng(lat, lng);
        geocoder.geocode({ 'latLng': latlng }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
            document.getElementById(t).innerHTML=results[0].formatted_address;
                }
            } 
        });
    }
}




</script>

最佳答案

尝试使用marker.setPosition:

var point = new google.maps.LatLng(Lat,Lng);
marker.setPosition(point);

如果您有多个隐藏者,则循环遍历每个标记并将其设置为相关点。

关于javascript - 谷歌地图更新标记位置而不删除它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33383825/

相关文章:

javascript - Uncaught Error : [$injector:modulerr] on attempting to load a pdf print page

javascript - 对于不加载页面而是提供文件的表单,我如何检测表单提交何时完成?

php - 如何将单个变量从php页面传递到html

google-maps - 使用 Selenium IDE 单击 Google map

javascript - 在 React 中设置状态

javascript - 哪个 jquery 事件用于自动完成?

php - Mysql编码问题

php - Drupal 模块将菜单项添加到主链接?

android - 获取用户位置并将其存储在 Android 变量中

Android map 扩展出错了