我试图让用户选择他们想要在地图上显示的内容,这些选择将决定我将哪个Google Maps样式ID与拉出地图的脚本链接相关联。html文档中的脚本链接如下所示
<script
async
src="https://maps.googleapis.com/maps/api/js?key=**MYAPIKEY**&map_ids=**MYMAPID**&callback=initMap"
></script>js文件中的函数如下所示
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: lat, lng: lng },
zoom: 15,
mapId: "MYMAPID",
});
}
如果我只使用一个mapID,这一切都工作得很好。地图ID在JS文件和HTML中都需要匹配,所以如果我想让用户选择可以让他们查看5个地图中的1个的选项,那么我如何才能使其工作呢?
发布于 2021-04-02 06:49:58
您可以在接口引导中包含多个mapIds:
(为清楚起见,添加了空格)
<script
src="https://maps.googleapis.com/maps/api/js?
key=AIzaSyBIwzALxUPNbatRBj3Xi1Uhp0fFzwWNBkE
&callback=initMap&libraries=
&v=beta
&map_ids=dea1fd60813b4e75,6a25ac9af0b8a3a2,2635966e05b3c0d6"
async
></script>使用.setOptions方法时,mapId似乎不能动态更改(至少目前是这样),但您可以使用新的mapId重新构造映射。
代码片段:
let map;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8,
mapId: "dea1fd60813b4e75"
});
google.maps.event.addDomListener(document.getElementById('grey'), 'click', function() {
// map.setOptions({mapId:"6a25ac9af0b8a3a2"})
map = new google.maps.Map(document.getElementById("map"), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8,
mapId: "6a25ac9af0b8a3a2"
});
});
google.maps.event.addDomListener(document.getElementById('classic'), 'click', function() {
// map.setOptions({mapId:"dea1fd60813b4e75"})
map = new google.maps.Map(document.getElementById("map"), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8,
mapId: "dea1fd60813b4e75"
});
});
google.maps.event.addDomListener(document.getElementById('light'), 'click', function() {
// map.setOptions({mapId:"2635966e05b3c0d6"})
map = new google.maps.Map(document.getElementById("map"), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8,
mapId: "2635966e05b3c0d6"
});
});
}/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 90%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<input id="grey" type="button" value="grey" />
<input id="classic" type="button" value="classic" />
<input id="light" type="button" value="light" />
<div id="map"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=beta&map_ids=dea1fd60813b4e75,6a25ac9af0b8a3a2,2635966e05b3c0d6"
async
></script>
</body>
</html>
https://stackoverflow.com/questions/66909603
复制相似问题