多个Google地图,同一页面上有标记

时间:2015-09-09 09:42:12

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

我想将3个不同的谷歌地图插入网站的页面,还包括标记。

以下脚本将带有标记的Google地图放在名为#william_harvey的div中。然后我想要两个额外的和不同的地图在其他名为#chaucer和#kims的div中显示标记但是无法使其工作。有什么建议吗?

 <script>
 function initMap() {
      var myLatLng = {lat: -25.363, lng: 131.044};
      var map1 = new google.maps.Map(document.getElementById('william_harvey'), {
        zoom: 4,
        center: myLatLng
      });
      var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        title: 'Hello World!'
      });
    }
        </script>
        <script async defer
            src="https://maps.googleapis.com/maps/api/js?signed_in=true&callback=initMap"></script> 

2 个答案:

答案 0 :(得分:3)

initMap转换函数与参数mapId。然后使用div id调用该函数。 像这样:

function mapCreate(id)
{
      var myLatLng = {lat: -25.363, lng: 131.044};
      var map1 = new google.maps.Map(document.getElementById(id), {
        zoom: 4,
        center: myLatLng
      });
      var marker = new google.maps.Marker({
        position: myLatLng,
        map: map1,
        title: 'Hello World!'
      });
}

mapCreate('chaucer');
mapCreate('kims');

JsFiddle

如果您使用不同的行为图,请使用数组。

答案 1 :(得分:2)

制作3个单独的google.maps.Map个对象,三个单独的google.maps.Marker个对象,并将每个标记添加到其关联的地图中。

proof of concept fiddle

代码段

var william_harvey = {
  lat: 51.143183,
  lng: 0.915349
};
var chaucer = {
  lat: 51.261797,
  lng: 1.087446
};
var kims = {
  lat: 51.286869,
  lng: 0.556317
};

function initMap() {
  var myLatLng = {
    lat: -25.363,
    lng: 131.044
  };
  var map1 = new google.maps.Map(document.getElementById('william_harvey'), {
    zoom: 14,
    center: william_harvey
  });
  var marker1 = new google.maps.Marker({
    position: william_harvey,
    map: map1,
    title: 'Hello World!'
  });
  var map2 = new google.maps.Map(document.getElementById('chaucer'), {
    zoom: 14,
    center: chaucer
  });
  var marker2 = new google.maps.Marker({
    position: chaucer,
    map: map2,
    title: 'Hello World!'
  });
  var map3 = new google.maps.Map(document.getElementById('kims'), {
    zoom: 14,
    center: kims
  });
  var marker2 = new google.maps.Marker({
    position: kims,
    map: map3,
    title: 'Hello World!'
  });

}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body,
#william_harvey,
#chaucer,
#kims {
  height: 300px;
  width: 500px;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="william_harvey" style="border: 2px solid #3872ac;"></div>
<div id="chaucer" style="border: 2px solid #3872ac;"></div>
<div id="kims" style="border: 2px solid #3872ac;"></div>