如何在 javascript 谷歌地图上添加多个标记?

时间:2021-04-29 08:15:06

标签: angular google-maps google-maps-markers

嗨,我正在尝试在我的应用程序上添加标记,但仍然无法在我的地图上查看标记,这是我的代码:

TS:

loadMap(){

    var locations = [
      ['Bondi Beach', -33.890542, 151.274856, 4],
      ['Coogee Beach', -33.923036, 151.259052, 5],
      ['Cronulla Beach', -34.028249, 151.157507, 3],
      ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
      ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];

    //  alert('hi');
      //  let latLng = new google.maps.LatLng(13.08784, 80.27847);
     
       let mapOptions = {
         center: new google.maps.LatLng(-33.92, 151.25),
         zoom: 10,
         mapTypeId: google.maps.MapTypeId.ROADMAP
       }
       
       var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: this.map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(Map, marker);
        }
      })(marker, i));


       this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
   
     }
    }

如何查看 Google 地图上的标记?有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

查看评论...

function loadMap() {

  var locations = [
    ['Bondi Beach', -33.890542, 151.274856, 4],
    ['Coogee Beach', -33.923036, 151.259052, 5],
    ['Cronulla Beach', -34.028249, 151.157507, 3],
    ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
    ['Maroubra Beach', -33.950198, 151.259302, 1]
  ];

  let mapOptions = {
    center: new google.maps.LatLng(-33.92, 151.25),
    zoom: 10,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  
  // Moved this line up here
  this.map = new google.maps.Map(document.getElementById('map'), mapOptions); // changed the "native element" to a standard DOM element for the sake of this example

  var infowindow = new google.maps.InfoWindow();

  var marker, i;

  for (i = 0; i < locations.length; i++) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i][1], locations[i][2]),
      map: this.map // You are using this.map here so it needs to be created before
    });

    google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function() {
        infowindow.setContent(locations[i][0]);
        infowindow.open(Map, marker);
      }
    })(marker, i));
  }
}

loadMap();
#map {
  height: 180px;
}
<div id="map"></div>
<script src="//maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>