Google Maps API点击网址事件无效

时间:2018-03-05 08:11:33

标签: javascript php html google-maps google-maps-api-3

我在谷歌地图上创建了一些标记,并且当我点击它(标记)时想要打开国家的php页面,但我不知道它为什么不这样做。这是我的代码的布局:

<script>
  function initMap() {
    var germany = {lat: 51.268917, lng:  9.591616};
    var russia = {lat: 55.765237, lng: 37.582553};
  var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 2,
      center: germany
    });
var marker = new google.maps.Marker({
      position: germany,
      map: map,
      title:'Germany',
      url:'Germany.php',
      animation:google.maps.Animation.DROP
    });
var marker = new google.maps.Marker({
      position: russia,
      map: map,
      title:'Russia',
      animation:google.maps.Animation.DROP
    });
google.maps.event.addListener(marker, 'click', function() 
   {window.location.href = marker.url;});
  }
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?
key=My_API_Key&callback=initMap">
</script>

1 个答案:

答案 0 :(得分:1)

我实际上无法添加评论,但您可以试试这个。我为我工作。你也可以整理一下。

    <script>
  function callMyUrl(element){
    alert('I am from ' + element.title);
  }

  function initMap() {
    var germany = {lat: 51.268917, lng:  9.591616};
    var russia = {lat: 55.765237, lng: 37.582553};
  var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 2,
      center: germany
    });

var location = [
  {title: 'Germany', lat: 51.268917, lng:  9.591616 },
  {title: 'Russia', lat: 55.765237, lng: 37.582553 }
]

  location.forEach(function(element){
    var marker;
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(element.lat, element.lng),
      title: element.title,
      map: map
    });
    return google.maps.event.addListener(marker, 'click', function() {
      callMyUrl(element);
    });
  });
}
</script>