从外部js文件编辑现有的谷歌地图

时间:2015-03-27 14:04:26

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

我想从带有外部js文件的页面编辑所有谷歌地图。 假设我在每个页面都有5个页面,每个页面有3个谷歌地图。 我想在每个谷歌地图中添加一个圆圈。 如何从每个页面加载的外部javascript文件中执行此操作?

1 个答案:

答案 0 :(得分:1)

您的基页包含多个地图和外部JS文件:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var maps = [];
function drawMaps(){
    for(var i = 1; i<4;i++){
        drawMap(i);
    }
}
function drawMap(num){
    var mapcontainer=document.getElementById("map"+num);
    var options={
        center: new google.maps.LatLng(40.266323, -73.996579),
        zoom:8,
        maptypeid:google.maps.MapTypeId.ROADMAP 
    };
    var map=new google.maps.Map(mapcontainer,options);
    maps.push(map);
    var circle=new google.maps.Circle({
        map:map,
        center:new google.maps.LatLng(40.266323, -73.996579),
        radius:10000,
        fillColor:"blue",
        border:0,
        strokeWeight:0
    });
}

window.addEventListener("load", drawMaps); 
</script>
<script src="externalJS.js"></script>
</head>
<html>
<body>
    <div style="height:400px;width:400px" id="map1"></div> 
    <div style="height:400px;width:400px" id="map2"></div> 
    <div style="height:400px;width:400px" id="map3"></div>

</body>
</html>

请注意该数组用作所有地图的可访问bin。还要注意窗口监听器的“加载”。

外部JS文件内容:

function addToAllMaps(){
    if(maps!=undefined){
        for (var i in maps){
            var map = maps[i];
            var circle=new google.maps.Circle({
                    map:map,
                    center:new google.maps.LatLng(40.266323, -73.996579),
                    radius:1000000,
                    fillColor:"red",
                    border:0,
                    strokeWeight:0
                });
        }
    }
}
window.addEventListener("load", addToAllMaps); 

请注意它如何引用maps数组并将循环中的每个红色圆应用。还要注意加载窗口监听器。通过使用此事件,我们可以按照定义事件的顺序添加多个事件,在本例中是脚本加载的顺序。

相关问题