使用watchPosition仅显示当前位置标记

时间:2013-03-21 03:07:18

标签: javascript google-maps mobile gps cordova

我正在尝试在Google地图上创建单个标记,以显示用户当前位置。使用以下代码我能够做到这一点,但每次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);

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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