【问题标题】:Allow user to create only one Google Maps marker at a time允许用户一次只创建一个谷歌地图标记
【发布时间】:2012-09-22 23:16:52
【问题描述】:

我有以下代码,允许用户单击地图上的某个位置,并记录他们单击的任何位置的 GPS 位置。它在后端正常工作,但每当用户点击不止一次时,它就会在地图上留下多个标记。它始终保留最后一个位置,因此它可以工作,但对于不知道后端发生了什么的用户来说,这有点令人困惑。我可以做一些小技巧来做到这一点,以便每当用户单击创建新标记时,旧标记就会被删除?

代码:

    var map;
var GPSlocation;


function initialize() {
  var haightAshbury = new google.maps.LatLng(37.7699298, -93.4469157);
  var mapOptions = {
    zoom: 4,
    center: haightAshbury,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };
  map =  new google.maps.Map(document.getElementById("map"), mapOptions);

  google.maps.event.addListener(map, 'click', function(event) {
    addMarker(event.latLng);
  });
}

function addMarker(location) {
//I save the location right here
    GPSlocation = location;
    document.getElementById("GPSlocation").value = GPSlocation;
    marker = new google.maps.Marker({
    position: location,
    map: map
  });
}

【问题讨论】:

    标签: javascript google-maps-api-3 geolocation google-maps-markers


    【解决方案1】:

    通过在你的函数之外声明它来使标记成为一个全局变量:

    var marker;
    function addMarker(location) {
        GPSlocation = location;
        document.getElementById("GPSlocation").value = GPSlocation;
        marker = new google.maps.Marker({
            position: location,
            map: map
        });
    }
    

    您还可以通过仅更新标记的位置而不是创建新对象来提高效率:

    var marker;
    function addMarker(location) {
        GPSlocation = location;
        document.getElementById("GPSlocation").value = GPSlocation;
        if (!marker) {
            marker = new google.maps.Marker({
                position: location,
                map: map
            });
        } else {
            marker.setPosition(location);
        }
    }
    

    【讨论】:

    • 嗯,我确实做到了,但由于某种原因,地图现在甚至无法渲染......我会在早上尝试调试它
    • @exployre 你可能已经猜到了,但我的第二个例子中有一个错误,现在已经更正了。
    【解决方案2】:

    只需使用google.maps.Marker 实例的setPosition 方法即可:

    var map,
        GPSlocation,
        marker;  // <-- Added
    
    // ... snip ...
    
    function addMarker(location) {
        // ... snip ...
        if (!marker) {
            // Create the marker if it doesn't exist
            marker = new google.maps.Marker({
            position: location,
            map: map
            });
        }
        // Otherwise, simply update its location on the map.
        else { marker.setPosition(location); }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-16
      • 1970-01-01
      • 2021-01-23
      • 2016-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-31
      相关资源
      最近更新 更多