一个页面上有多个谷歌地图

Multiple Google Maps on a single Page?

本文关键字:谷歌地图 一个      更新时间:2023-09-26

我试图在一个页面上显示多个谷歌地图。这是一个结果页面,是按区域中每个位置动态生成的。每个div都有一个地图类,我想从中运行谷歌地图。截至目前,我只能让它处理一个div的信息。

我知道我需要以某种方式向谷歌地图传递一个数组。但是鉴于我的实现用途,我对如何做到这一点感到困惑。

.HTML

<div class="map" data-address="123 easy st city st zip" data-title="location"></div>
<div class="map" data-address="456 easy st city st zip" data-title="location 2"></div>

jQuery

$('.map').each(function() {
    var geoCode = new google.maps.Geocoder(), 
    container = this;
    geoCode.geocode({'address': $(container).data('address')}, function(results, status) {
    var start_options = 0;
    if (status == google.maps.GeocoderStatus.OK) {
         var mapOptions = {
             zoom: 14,
             center: new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()),
             zoomControl: true,
             scaleControl: false,
             scrollwheel: false,
             disableDefaultUI: true,
             mapTypeId: google.maps.MapTypeId.ROADMAP,
         }
         if (navigator.userAgent.match(/(iPod|iPhone|iPad|Android|Blackberry|Windows Phone|Nokia|HTC|webOS)/)) {
                 mapOptions.draggable=false;
        }
        var map = new google.maps.Map(document.getElementById("map"), mapOptions);
        var marker = new google.maps.Marker({
            position: results[0].geometry.location,
            animation: google.maps.Animation.DROP,
            map: map,
            title: $(this).data('itemTitle')
        });
        google.maps.event.addListener(marker, 'click', toggleBounce);
        function toggleBounce() {
              if (marker.getAnimation() != null) {
                marker.setAnimation(null);
              } else {
                marker.setAnimation(google.maps.Animation.BOUNCE);
              }
        }
        var center;
        function calculateCenter() {
            center = map.getCenter();
        }
        google.maps.event.addDomListener(map, 'idle', function() {
            calculateCenter();
        });
        google.maps.event.addDomListener(window, 'resize', function() {
            map.setCenter(center);
        });
    } else {
        $(this).parent().hide();
    }
});
}); 

在你的 forEach 循环中,你正在使用 document.getElementById("map") .

这是错误的,原因有几个,首先是因为地图

没有 id,它有一个类,其次是因为地图每次都会附加到同一个元素。

您要做的是将地图附加到循环中的当前地图。在你的jQuery循环中,这将是this变量。

方便的是(this经常可以在嵌套函数中更改),循环的第一行将this存储在名为 container 的变量中。

因此,只需将document.getElementById("map")替换为 container ,您应该会得到一个附加到 .map 元素的每个实例的不同映射。

  1. 将 ID 属性分配给您的div
  2. 将谷歌地图代码包装在一个带有一个参数的函数中>容器
  3. 调用函数
函数 getGoogleMap(container){    谷歌代码    像这样使用容器参数    geoCode.geocode({'address': $("#" + container).data('address')});    左右    var map = new google.maps.Map(document.getElementById(container), mapOptions);}getGoogleMap("map1");