绘图线 - Google Maps APIv3

时间:2013-12-19 12:40:27

标签: java javascript google-maps gps setinterval

我想要实现的目标 -

我有2个变量 - Latitude&经度,两者都在后台更新。我想根据变量更新来绘制一条线。

我在想什么 -

  1. 创建阵列路径。
  2. 创建一行。
  3. 使用setInterval
  4. 更新线路的路径

    守则 -

    var poly;
    
    function initialize() {
    
    var Latitude
    var Longitude
    
    Latitude= {code that updates}
    Longitude= {code that updates}
    
    //create map
    var mapOptions = {
    zoom: 8,
    }
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    
    var path = [];
    
    poly = new google.maps.Polyline({
    path: path,
    geodesic: true,
    strokeColor: '#FF0000',
    strokeOpacity: 1.0,
    strokeWeight: 2
    });
    
    poly.setMap(map);
    
    
    
    var myVar = setInterval(function(){updateposition()},2000);
    
    function updateposition(){
    path.push(new google.maps.LatLng(Latitude,Longitude));
    }
    }
    

    问题 - 根本没有出现任何一条线:(

1 个答案:

答案 0 :(得分:0)

更新路径后,需要更新折线的路径属性(poly.setPath(path))。仔细观察您的代码,我不确定您是如何期望Latitude和Longitude更新它们的位置(初始化函数的本地)。

function updateposition(){
  path.push(new google.maps.LatLng(Latitude,Longitude));
  poly.setPath(path);
}

here is an example that updates the polyline from computed coordinates based on the time

var poly;
var Latitude = null;
var Longitude = null;
var map = null;
var  path = [];

function initialize() {
  //create map
  var mapOptions = {
    zoom: 2,
    center:new google.maps.LatLng(0,0)
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  poly = new google.maps.Polyline({
    path: path,
    strokeColor: '#FF0000',
    strokeOpacity: 1.0,
    strokeWeight: 2
  });

  poly.setMap(map);

  var myVar = setInterval(function(){updateposition()},2000);
}
function updateposition(){
   var date = new Date();
   var time = date.getMinutes()*60+date.getSeconds();
   Latitude= 45*Math.sin((time-1800)*Math.PI/1800.0)
   Longitude= (time/10)-180;
   path.push(new google.maps.LatLng(Latitude,Longitude));
   if (path.length == 1) {
     map.setCenter(path[0]);
     map.setZoom(8);
   } else {
     map.setCenter(path[path.length-1]);
   }
   poly.setPath(path);
}
google.maps.event.addDomListener(window, 'load', initialize);