1

我正在尝试在谷歌地图上创建一个标记以显示用户当前位置。使用以下代码我可以做到这一点,但每次 watchPosition 刷新它都会创建一个新点。每次添加新点时如何清除以前的标记?

// Geolocation
var win = function(position) {
    var iconimage = new google.maps.MarkerImage('images/current_location_small.png',
        new google.maps.Size(15, 15),
        new google.maps.Point(0,0),
        new google.maps.Point(7, 7)
    );
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
    var myLatlng = new google.maps.LatLng(lat, long);
    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        icon: iconimage
    });

    marker.setMap(map);
};

var watchID = navigator.geolocation.watchPosition(win);
4

2 回答 2

3

您可以在函数之外声明您的标记并使用该setPosition(LatLng)方法

// Geolocation
var marker=null;
var win = function(position) {

    var lat = position.coords.latitude;
    var long = position.coords.longitude;
    var myLatlng = new google.maps.LatLng(lat, long);
    if(marker==null){
         var iconimage = new google.maps.MarkerImage('images/current_location_small.png',
             new google.maps.Size(15, 15),
             new google.maps.Point(0,0),
             new google.maps.Point(7, 7)
         );
        marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            icon: iconimage
        });
        marker.setMap(map);
    }else{
        marker.setPosition(myLatlng);
    }
};

var watchID = navigator.geolocation.watchPosition(win);
于 2013-03-21T03:32:42.310 回答
1

或如评论 setnull 中所述,然后重绘。当然,屏幕会闪烁,它会以 gps 更新的速度重绘,删除下面我的代码中的 if 行,你会不断地画出轨迹

var watchID = navigator.geolocation.watchPosition(function(position) {

  // Get current position
  pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);

  // Redefine current location marker
  if (typeof(marker) != "undefined") marker.setMap(null);
  marker = new google.maps.Marker({
     position: pos,
     map: map,
     title: 'you are here',
     icon : user
  },watchOptions);

 }); //end constant watchPosition
于 2014-07-29T08:49:53.640 回答