【问题标题】:set marker google maps javascript api设置标记谷歌地图javascript api
【发布时间】:2016-04-08 10:24:47
【问题描述】:

我正在尝试使用 google maps javascript api 创建以下内容:页面加载后,应在用户位置设置标记,现在可以使用。之后,应该在用户点击地图的地方添加一个标记,并删除前一个标记。一个标记应该只在地图上。现在以前的标记不会被删除,而其他标记不会被添加我不想要的。我该怎么做才能在地图上始终拥有一个标记?

var markers = [];
    function initMap() {
      var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -34.397, lng: 150.644},
        zoom: 7
      });
      var infoWindow = new google.maps.InfoWindow({map: map});

      // Try HTML5 geolocation.
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          var pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
          };

          map.setCenter(pos);


      // This event listener will call addMarker() when the map is clicked.
      map.addListener('click', function(event) {
        deleteMarkers();
addMarkers(event.latLng);


      });
      addMarkers(pos);
      // Adds a marker to the map and push to the array.
      function addMarkers(location) {
      var marker = new google.maps.Marker({
        position: location,
        map: map
      });
      markers.push(marker);
    }
  // Sets the map on all markers in the array.
  function setMapOnAll(map) {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(map);
  }
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
  setMapOnAll(null);
}


    // Deletes all markers in the array by removing references to them.
    function deleteMarkers() {
        clearMarkers();
      marker = [];
    }


        }, function() {
          handleLocationError(true, infoWindow, map.getCenter());
        });

      } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
      }

    }

【问题讨论】:

  • 我在发布代码Uncaught ReferenceError: markers is not defined时收到一个javascript错误@
  • 当我修复它并将原始标记推到数组上时,它对我有用。
  • 哦,对不起,我没有注意到你的 cmets。你会这么好,并发布工作代码作为答案吗?
  • 使用我的实际代码,我得到“未捕获的类型错误:marker.push 不是函数”
  • 我自己搞定了,但感谢您的帮助:)

标签: javascript google-maps google-maps-api-3 marker


【解决方案1】:

看看here我相信你很接近:)

你只是将你的标记数组设置为空,而不是实际清除标记​​p>

【讨论】:

  • 谢谢,但我从这个例子中制作了我以前的代码:D
  • 再看一下这个例子,然后按照删除标记按钮的 onclick 处理程序。您可以看到它调用了 ClearMarkers(),后者又调用了 SetMapOnAll(map),它在其中循环遍历标记并使用 SetMap() 为每个标记再次设置地图。
  • 好的,我已经更新了我的代码,但现在 onclick 事件不起作用:D
  • 看看你在 onClick 事件上做了什么。您首先说要删除标记,然后调用 addmarker() ,这是您第一次创建“标记”的地方。所以当您第一次单击地图时,您的预期行为是它会清除所有现有标记,然后清除时添加一个buttttttttt,就像嘿,你说的这个标记是什么,你想让我清除然后抛出错误并且不做你想做的事
  • 现在的问题是 deleteMarker() 正在尝试删除一个尚未创建的标记。看看@geocodezip 的评论,它指出它是“固定的”,然后添加到标记数组中。我相信它是通过在 addMarker() 函数之外创建标记来“修复”的,所以当调用 deleteMarker() 函数时,它不会抛出一个错误,说它没有定义:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
相关资源
最近更新 更多