【问题标题】:Show only the current location marker using watchPosition使用 watchPosition 仅显示当前位置标记
【发布时间】:2014-07-29 16:49:53
【问题描述】:

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

【问题讨论】:

    标签: javascript google-maps mobile gps cordova


    【解决方案1】:

    您可以在函数之外声明您的标记并使用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);
    

    【讨论】:

    • 很高兴为您提供帮助,以供将来参考 marker.setMap(null) 从地图中删除标记 :)
    • @kevmc 这个答案没有意义,因为您放置的代码没有使用 marker.serMap(null)
    【解决方案2】:

    或如 cmets 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-20
      • 1970-01-01
      • 2015-08-08
      • 2020-06-14
      相关资源
      最近更新 更多