如何通过一些Google Maps标记打开Web链接?

时间:2019-01-10 21:30:48

标签: javascript google-maps marker

我可以通过

从标记打开Web链接
google.maps.event.addListener(marker, "click", function() {
window.open('http://example.com/');
});

但是,如果我需要放置100个标记以及100个指向Google Maps的链接怎么办? 我的带有坐标和链接的数组看起来像这样

var point = [[52.7081444444445, 58.6677361111111, "Sib/2377/index.html"],
[52.7039611111111, 58.668425, "Sib/2378/index.html"],
[52.6993166666667, 58.6680305555556, "Sib/2379/index.html"],
[52.6946277777778, 58.6679416666667, "Sib/2380/index.html"],
[52.6947833333333, 58.6755555555556, "Sib/2381/index.html"]];

1 个答案:

答案 0 :(得分:0)

将URL添加为标记(.url)的属性。使用this.url

打开窗口
  for (var i = 0; i < points.length; i++) {
    var point = points[i];
    var marker = new google.maps.Marker({
      position: {
        lat: point[0],
        lng: point[1]
      },
      map: map,
      url: point[2]
    });
    google.maps.event.addListener(marker, "click", function() {
      window.open(this.url);
    });
  }

proof of concept fiddle

代码段:

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: {
      lat: -33.9,
      lng: 151.2
    }
  });
  setMarkers(map);
}

// Data for the markers consisting of a Latitude, a Longitude and a URL.
var points = [
  [52.7081444444445, 58.6677361111111, "http://www.google.com"],
  [52.7039611111111, 58.668425, "http://www.yahoo.com"],
  [52.6993166666667, 58.6680305555556, "http://maps.google.com"],
  [52.6946277777778, 58.6679416666667, "http://maps.google.com?q=52.6946277777778,58.6679416666667"],
  [52.6947833333333, 58.6755555555556, "http://maps.google.com?q=52.6947833333333,58.6755555555556"]
];

function setMarkers(map) {
  var bounds = new google.maps.LatLngBounds();
  // Adds markers to the map.
  for (var i = 0; i < points.length; i++) {
    var point = points[i];
    var marker = new google.maps.Marker({
      position: {
        lat: point[0],
        lng: point[1]
      },
      map: map,
      url: point[2]
    });
    google.maps.event.addListener(marker, "click", function() {
      window.open(this.url);
    });
    bounds.extend(marker.getPosition());
  }
  map.fitBounds(bounds);
}
html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>