如何使用API​​ V3在每页上显示多个Google地图

时间:2010-11-02 02:29:31

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

我有以下脚本。我想让两个地图出现在页面上,但无论我尝试什么,我只能得到第一个地图initialize()来显示......第二个地图没有。有什么建议? (另外,我无法在代码中添加它,但第一个地图显示在<div id="map_canvas"></div><div id="route"></div>中 谢谢!

<script type="text/javascript"> 
// Create a directions object and register a map and DIV to hold the 
// resulting computed directions

var map;
var directionsPanel;
var directions;

function initialize() {
  map = new GMap(document.getElementById("map_canvas"));
  map.setCenter(new GLatLng(41.1255275,-73.6964801), 15);
  directionsPanel = document.getElementById("route");
  directions = new GDirections(map, directionsPanel);
  directions.load("from: Armonk Fire Department, Armonk NY to: <?php echo $LastCallGoogleAddress;?> ");

  map.addControl(new GSmallMapControl());
  map.addControl(new GMapTypeControl());
}

</script> 


<div id="map_canvas2" style="width:200px; height:200px;"></div>
<div id="route2"></div>

<script type="text/javascript"> 
// Create a directions object and register a map and DIV to hold the 
// resulting computed directions

var map2;
var directionsPanel2;
var directions2;

function initialize2() {
  map2 = new GMap(document.getElementById("map_canvas2"));
  map2.setCenter(new GLatLng(41.1255275,-73.6964801), 15);
  directionsPanel2 = document.getElementById("route2");
  directions2 = new GDirections(map2, directionsPanel2);
  directions2.load("from: ADDRESS1 to: ADDRESS2 ");

  map2.addControl(new GSmallMapControl());
  map2.addControl(new GMapTypeControl());
}

</script> 

<script type="text/javascript">
function loadmaps(){
    initialize();
    initialize2();  
}
</script>

11 个答案:

答案 0 :(得分:63)

以下是我使用Google Map API V3在同一页面上生成多个地图的方法。请注意,这是一个解决上述问题的袖口代码。

HTML位

<div id="map_canvas" style="width:700px; height:500px; margin-left:80px;"></div>
<div id="map_canvas2" style="width:700px; height:500px; margin-left:80px;"></div>

用于地图初始化的Javascript

<script type="text/javascript">
var map, map2;

function initialize(condition) {
    // create the maps
    var myOptions = {
        zoom: 14,
        center: new google.maps.LatLng(0.0, 0.0),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    map2 = new google.maps.Map(document.getElementById("map_canvas2"), myOptions);
}
</script> 

答案 1 :(得分:13)

我刚刚将谷歌地图添加到我公司的CMS产品中。我的代码允许页面中有多个地图。

备注:

  • 我使用jQuery
  • 我将地址放在内容中,然后解析出来以动态生成地图
  • 我在地图中添加了标记和InfoWindow

<强> HTML:

<div class="block maps first">
    <div class="content">
        <div class="map_canvas">
            <div class="infotext">
                <div class="location">Middle East Bakery & Grocery</div>
                <div class="address">327 5th St</div>
                <div class="city">West Palm Beach</div>
                <div class="state">FL</div>
                <div class="zip">33401-3995</div>
                <div class="country">USA</div>
                <div class="phone">(561) 659-4050</div>
                <div class="zoom">14</div>
            </div>
        </div>
    </div>
</div>
<div class="block maps last">
    <div class="content">
        <div class="map_canvas">
            <div class="infotext">
                <div class="location">Global Design, Inc</div>
                <div class="address">3434 SW Ash Pl</div>
                <div class="city">Palm City</div>
                <div class="state">FL</div>
                <div class="zip">34990</div>
                <div class="country">USA</div>
                <div class="phone"></div>
                <div class="zoom">17</div>
            </div>
        </div>
    </div>
</div>

<强>代码:

$(document).ready(function() {
    $maps = $('.block.maps .content .map_canvas');
    $maps.each(function(index, Element) {
        $infotext = $(Element).children('.infotext');

        var myOptions = {
            'zoom': parseInt($infotext.children('.zoom').text()),
            'mapTypeId': google.maps.MapTypeId.ROADMAP
        };
        var map;
        var geocoder;
        var marker;
        var infowindow;
        var address = $infotext.children('.address').text() + ', '
                + $infotext.children('.city').text() + ', '
                + $infotext.children('.state').text() + ' '
                + $infotext.children('.zip').text() + ', '
                + $infotext.children('.country').text()
        ;
        var content = '<strong>' + $infotext.children('.location').text() + '</strong><br />'
                + $infotext.children('.address').text() + '<br />'
                + $infotext.children('.city').text() + ', '
                + $infotext.children('.state').text() + ' '
                + $infotext.children('.zip').text()
        ;
        if (0 < $infotext.children('.phone').text().length) {
            content += '<br />' + $infotext.children('.phone').text();
        }

        geocoder = new google.maps.Geocoder();
        geocoder.geocode({'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                myOptions.center = results[0].geometry.location;
                map = new google.maps.Map(Element, myOptions);
                marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    title: $infotext.children('.location').text()
                });
                infowindow = new google.maps.InfoWindow({'content': content});
                google.maps.event.addListener(map, 'tilesloaded', function(event) {
                    infowindow.open(map, marker);
                });
                google.maps.event.addListener(marker, 'click', function() {
                    infowindow.open(map, marker);
                });
            } else {
                alert('The address could not be found for the following reason: ' + status);
            }
        });
    });
});

答案 2 :(得分:6)

这是另一个例子,如果你有long和lat,在我的情况下使用Umbraco谷歌地图数据类型包并输出一个带有“map”类的div列表,例如。

<div class="map" id="UK">52.21454000000001,0.14044490000003407,13</div>

我的JavaScript使用基于Cultiv Razor examples

的Google Maps API v3
$('.map').each(function (index, Element) {
    var coords = $(Element).text().split(",");
    if (coords.length != 3) {
        $(this).display = "none";
        return;
    }
    var latlng = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
    var myOptions = {
        zoom: parseFloat(coords[2]),
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: false,
        mapTypeControl: true,
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL
        }
    };
    var map = new google.maps.Map(Element, myOptions);

    var marker = new google.maps.Marker({
        position: latlng,
        map: map
    });
});

答案 3 :(得分:5)

OP需要两张特定的地图,但如果您想在一个页面上拥有动态数量的地图(例如零售商地点列表),您需要转到另一条路线。 Google maps API的标准实现将地图定义为全局变量,这不会使用动态数量的地图。这是我的代码,在没有全局变量的情况下解决这个问题:

function mapAddress(mapElement, address) {
var geocoder = new google.maps.Geocoder();

geocoder.geocode({ 'address': address }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        var mapOptions = {
            zoom: 14,
            center: results[0].geometry.location,
            disableDefaultUI: true
        };
        var map = new google.maps.Map(document.getElementById(mapElement), mapOptions);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
    } else {
        alert("Geocode was not successful for the following reason: " + status);
    }
});
}

只需将每张地图的ID和地址传递给函数,即可绘制地图并标记地址。

答案 4 :(得分:5)

取自这些示例 - guideimplementation

  1. 使用相应的<div>
  2. 设置您的id
  3. 包含foundation来电的Google地图选项。
  4. 包括foundationrem js lib。
  5. 示例 -

    index.html -

    <div class="row">
       <div class="large-6 medium-6 ">
          <div id="map_canvas" class="google-maps">
          </div>
       </div>
       <br>
       <div class="large-6 medium-6 ">
          <div id="map_canvas_2" class="google-maps"></div>
       </div>
    </div>
    <script src="/js/foundation.js"></script>
    <script src="/js/google_maps_options.js"></script>
    <script src="/js/rem.js"></script>
    <script>
       jQuery(function(){
           setTimeout(initializeGoogleMap,700);
       });
    </script>
    

    google_maps_options.js -

    function initializeGoogleMap()
    {
        $(document).foundation();
        var latlng = new google.maps.LatLng(28.561287,-81.444465);
        var latlng2 = new google.maps.LatLng(28.507561,-81.482359);
    
        var myOptions =
        {
            zoom: 13,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
    
        var myOptions2 =
        {
            zoom: 13,
            center: latlng2,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
    
    
        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
        var map2 = new google.maps.Map(document.getElementById("map_canvas_2"), myOptions2);
    
    
        var myMarker = new google.maps.Marker(
        {
            position: latlng,
            map: map,
            title:"Barnett Park"
       });
    
        var myMarker2 = new google.maps.Marker(
        {
            position: latlng2,
            map: map2,
            title:"Bill Fredrick Park at Turkey Lake"
        });
    
    
    }
    

答案 5 :(得分:4)

我需要使用动态位置加载动态数量的Google地图。所以我最终得到了类似的东西。希望能帮助到你。我在地图div上添加LatLng作为数据属性。

所以,只需用类“maps”创建div。每个地图画布都可以有这样的各种ID和LatLng。当然,您可以设置各种数据属性进行缩放等等......

也许代码可能更干净,但它对我很有用。

<div id="map123" class="maps" data-gps="46.1461154,17.1580882"></div>
<div id="map456" class="maps" data-gps="45.1461154,13.1080882"></div>

  <script>
      var map;
      function initialize() {
        // Get all map canvas with ".maps" and store them to a variable.
        var maps = document.getElementsByClassName("maps");

        var ids, gps, mapId = '';

        // Loop: Explore all elements with ".maps" and create a new Google Map object for them
        for(var i=0; i<maps.length; i++) {

          // Get ID of single div
          mapId = document.getElementById(maps[i].id);

          // Get LatLng stored in data attribute. 
          // !!! Make sure there is no space in data-attribute !!!
          // !!! and the values are separated with comma !!!
          gps = mapId.getAttribute('data-gps');

          // Convert LatLng to an array
          gps = gps.split(",");

          // Create new Google Map object for single canvas 
          map = new google.maps.Map(mapId, {
            zoom: 15,
            // Use our LatLng array bellow
            center: new google.maps.LatLng(parseFloat(gps[0]), parseFloat(gps[1])),
            mapTypeId: 'roadmap',
            mapTypeControl: true,
            zoomControlOptions: {
                position: google.maps.ControlPosition.RIGHT_TOP
            }
          });

          // Create new Google Marker object for new map
          var marker = new google.maps.Marker({
            // Use our LatLng array bellow
            position: new google.maps.LatLng(parseFloat(gps[0]), parseFloat(gps[1])),
            map: map
          });
        }
      }
  </script>

答案 6 :(得分:2)

您尚未定义id =“map_canvas”的div,您只有id =“map_canvas2”和id =“route2”。 div id需要匹配GMap()构造函数中的参数。

答案 7 :(得分:1)

您可以尝试nex方法 css

 .map {
            height: 300px;
            width: 100%;
        }

HTML

@foreach(var map in maps)
{
  <div id="map-@map.Id" lat="@map.Latitude" lng="@map.Longitude" class="map">
  </div>
}

的JavaScript

 <script>
    var maps = [];
    var markers = [];
    function initMap() {
        var $maps = $('.map');
        $.each($maps, function (i, value) {
            var uluru = { lat: parseFloat($(value).attr('lat')), lng: parseFloat($(value).attr('lng')) };

            var mapDivId = $(value).attr('id');

            maps[mapDivId] = new google.maps.Map(document.getElementById(mapDivId), {
                zoom: 17,
                center: uluru
            });

            markers[mapDivId] = new google.maps.Marker({
                position: uluru,
                map: maps[mapDivId]
            });
        })
    }
</script>

<script async defer
        src="https://maps.googleapis.com/maps/api/js?language=ru-Ru&key=YOUR_KEY&callback=initMap">
</script>

答案 8 :(得分:0)

我有一个特殊的问题,我有一个单页应用程序,需要以不同的div显示不同的地图,每次一个。我解决它不是一个非常美丽的方式,而是一个功能方式。我没有使用显示属性隐藏DOM元素,而是使用可见性属性来执行此操作。通过这种方法,Google Maps API可以毫不费力地了解我已经实例化地图的div的维度。

答案 9 :(得分:0)

var maps_qty;
for (var i = 1; i <= maps_qty; i++)
    {
        $(".append_container").append('<div class="col-lg-10 grid_container_'+ (i) +'" >' + '<div id="googleMap'+ i +'" style="height:300px;"></div>'+'</div>');
        map = document.getElementById('googleMap' + i);
        initialize(map,i);
    }

// Intialize Google Map with Polyline Feature in it.

function initialize(map,i)
    {
        map_index = i-1;
        path_lat_long = [];
        var mapOptions = {
            zoom: 2,
            center: new google.maps.LatLng(51.508742,-0.120850)
        };

        var polyOptions = {
            strokeColor: '#000000',
            strokeOpacity: 1.0,
            strokeWeight: 3
        };

        //Push element(google map) in an array of google maps
        map_array.push(new google.maps.Map(map, mapOptions));
        //For Mapping polylines to MUltiple Google Maps
        polyline_array.push(new google.maps.Polyline(polyOptions));
        polyline_array[map_index].setMap(map_array[map_index]);
    }

// For Resizing Maps Multiple Maps.

google.maps.event.addListener(map, "idle", function()
    {
      google.maps.event.trigger(map, 'resize');
    });

map.setZoom( map.getZoom() - 1 );
map.setZoom( map.getZoom() + 1 );

答案 10 :(得分:-2)

看看我最近制作的Laravel捆绑包!

<小时/> https://github.com/Maghrooni/googlemap

它可以帮助您在页面中创建一个或多个地图!

你可以在

找到课程
src/googlemap.php

请先阅读自述文件,如果您想在一个页面中放置多个地图,请不要忘记传递不同的ID