如何在Google Maps中更新一组标记

How to update a set of markers in Google Maps?

本文关键字:一组 更新 Google Maps      更新时间:2023-09-26

我试图从客户端的表单输出更新我在地图中显示的标记集。

我被困的地方是在ShowUser()函数中,最后一条语句是setMarkers(map, stations),我希望标记被改变,但它似乎不起作用。任何帮助吗?

function initialize() {
  var mapOptions = {
    zoom: 5,
    center: new google.maps.LatLng(34.7291, 0.3379)
    }
  var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
  setMarkers(map, stations);
}
  var stations = [
  ['Rafa',40.0,-6.0,0],
  ['Josh',38.5,-1.0,1]
  ];
   function setMarkers(map, locations) {
      var image = ['circle_orange.png','circle_blue .png'];
      for (var i = 0; i < locations.length; i++) {
        var stations = locations[i];
        var myLatLng = new google.maps.LatLng(stations[1], stations[2]);
        var marker = new google.maps.Marker({
          position: myLatLng,
          map: map,
          icon: image[stations[3]],
          title: stations[0],
          zIndex: stations[3],
          optimized: false
        });
        var infowindow = new google.maps.InfoWindow({
            content: "No data available"
        });
        google.maps.event.addListener(marker, 'mouseover', function() {
        infowindow.setContent("We can include any station information, for example: Lat/Long: "+ stations[1]+" , "+stations[2]);
        infowindow.open(map, this);
        });
      }
    }
google.maps.event.addDomListener(window, 'load', initialize);
function showUser(str) {
if (str != ""){
var stations = [
  ['Rafa',50.0,-6.0,0],
  ['Josh',58.5,-1.0,1]
  ];
 document.getElementById("txtHint").innerHTML=stations;
 setMarkers(map, stations);
}
}

正如Molle博士所指出的,问题出在map变量上。它是在initialize()函数内部初始化的,这意味着它不是一个全局变量。Chrome调试器工具是我用来发现问题的方式。下面是一个工作示例的链接,以供参考:

示例