gpt4 book ai didi

Javascript - 将数组作为参数传递

转载 作者:行者123 更新时间:2023-12-03 10:02:48 25 4
gpt4 key购买 nike

我想把这个谷歌地图脚本放入一个js文件中,并将mapLocs数组作为html页面中脚本的参数传递给它。有谁知道如何做到这一点吗?

function initialize(){
var map = new google.maps.Map(document.getElementById("map"),
{
zoom: 13,
center: new google.maps.LatLng(53.408103, -2.979595),
mapTypeId: google.maps.MapTypeId.ROADMAP
});

setMarkers(map, mapLocs);
}

// To be passed in as a parameter?
var mapLocs = [
['Liverpool', 53.408103, -2.979595]
];

function setMarkers(map, locations){
for (var i = 0; i < locations.length; i++){
var places = locations[i];
var myLatLng = new google.maps.LatLng(places[1], places[2]);
var marker = new google.maps.Marker({
position: myLatLng,
draggable: false,
map: map,
title: places[0],
zIndex: places[3]
});
}
}

google.maps.event.addDomListener(window, 'load', initialize);

最佳答案

加载数据后,您可以初始化 map :

google.maps.event.addDomListener(window, 'load', function(){
var locations = getLocations();
initializeMap(locations);
});

修改示例

function initialize(locations) {
var map = new google.maps.Map(document.getElementById("map"),
{
zoom: 13,
center: new google.maps.LatLng(53.408103, -2.979595),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
setMarkers(map, locations);
}

function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var places = locations[i];
var myLatLng = new google.maps.LatLng(places[1], places[2]);
var marker = new google.maps.Marker({
position: myLatLng,
draggable: false,
map: map,
title: places[0],
zIndex: places[3]
});
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Map</title>
<style>
html, body, #map {
height: 100%;
margin: 0px;
padding: 0px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script src="map.js"></script>
</head>
<body>
<div id="map"></div>
<script>
google.maps.event.addDomListener(window, 'load', function () {
//1.load data
var mapLocs = [
['Liverpool', 53.408103, -2.979595]
];
//2.init map
initialize(mapLocs);
});
</script>
</body>
</html>

关于Javascript - 将数组作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30504216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com