javascript - 加载多个谷歌地图实例

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

这是目前我将 Google map 实例加载到 map div 中的方式。

我想添加另一个 ID 为 map2 的 div 来保存另一个 google map 实例,我该怎么做?

<script type="text/javascript"> 
  var map;
  function initialize() {
    var myLatlng = new google.maps.LatLng(33.33333,44.44444);
    var myOptions = {
      zoom: 14,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map"), myOptions);


    var marker = new google.maps.Marker({
        position: myLatlng, 
        map: map, 
        title:"If this is your exact location, press \"Add this location\""
    });
    google.maps.event.addListener(marker, 'click', function() {
      map.setZoom(8);
    });
  }


</script> 
<div id="map"></div>

最佳答案

如果您想通过 JavaScript 执行此操作

var map2 = document.createElement('div');
map2.id = "map2";

document.body.innerHTML += map2;

然后使用不同的div id调用初始化函数;,即map2;

编辑:您确定没有错误地调用该函数吗?

<script type="text/javascript"> 

  function initialize(mapNum) {
    var map;
    var myLatlng = new google.maps.LatLng(33.33333,44.44444);
    var myOptions = {
      zoom: 14,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map"+mapNum), myOptions);


    var marker = new google.maps.Marker({
        position: myLatlng, 
        map: map, 
        title:"If this is your exact location, press \"Add this location\""
    });
    google.maps.event.addListener(marker, 'click', function() {
      map.setZoom(8);
    });
  }


initialize(1);
initialize(2);

</script> 
<div id="map1"></div>
<div id="map2"></div>

关于javascript - 加载多个谷歌地图实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5398056/

相关文章:

javascript - 如何从使用 Google Maps API 的站点恢复地理位置列表

Javascript - 使用 RegExp 进行替换时遇到问题

javascript - polymer 数据绑定(bind) : how to access data in nested template?

javascript - 等待谷歌地图方向服务时禁用按钮

python - geopy 类型错误 : geocode() missing 1 required positional argument: 'query'

java - 为Google map 创建插件

javascript - Google Maps API : markerwithlabel. js - 未捕获的 ReferenceError:未定义谷歌

javascript - 谷歌地图 API v3; Web 服务请求和使用 for-loop 显示多个位置

javascript - 如何将数组数据传递到 React 中的另一个页面?

javascript - 无法复制 Jquery Mobile 自动完成演示