我有这个简单的代码:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Google Map API on xhtml</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
<head>
<body>
<script>
//Initialise la map
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
scrollwheel: true,
mapTypeControl: false,
center: {lat: 48.8534100, lng: 2.3488000},
zoom: 13,
streetViewControl: false,
zoomControl:true
});
}
function drawOnclick() {
alert("clicked");
var antennasCircle = new google.maps.Circle({
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: map,
center: {lat: 48.8534100, lng: 2.34},
radius: 1000* 100
});
}
</script>
<input id="clickMe" type="button" value="clickme" onclick="drawOnclick();" />
<div id="map">
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBbns5KFelTGVj8E8FHdlJfdM9lEHHo4OA&libraries=visualization&callback=initMap" async="async" defer="defer"></script>
</body>
</html>
我的目标是在点击按钮时在巴黎上画一个红色圆圈。问题是,当我点击按钮时,没有任何反应。
我不明白的是,当我按照以下方式设置initMap
时:
//Initialise la map
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
scrollwheel: true,
mapTypeControl: false,
center: {lat: 48.8534100, lng: 2.3488000},
zoom: 13,
streetViewControl: false,
zoomControl:true
});
var antennasCircle = new google.maps.Circle({
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: map,
center: {lat: 48.8534100, lng: 2.34},
radius: 100
});
}
绘制圆圈。有人可以解释一下吗?
答案 0 :(得分:4)
map变量是initialize函数的本地变量。要在HTML单击功能(对于按钮)中使用它,它需要位于全局范围内(HTML单击函数运行的位置)。要解决此问题,请删除在初始化函数之外声明它的var
:
// map variable in global scope
var map;
//Initialise la map
function initMap() {
// initialize the map variable
map = new google.maps.Map(document.getElementById('map'), {
// ...
工作代码段
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<script>
// map variable in global scope
var map;
//Initialise la map
function initMap() {
// initialize the map variable
map = new google.maps.Map(document.getElementById('map'), {
scrollwheel: true,
mapTypeControl: false,
center: {
lat: 48.8534100,
lng: 2.3488000
},
zoom: 13,
streetViewControl: false,
zoomControl: true
});
}
function drawOnclick() {
// alert("clicked");
var antennasCircle = new google.maps.Circle({
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: map,
center: {
lat: 48.8534100,
lng: 2.34
},
radius: 1000 * 100
});
map.fitBounds(antennasCircle.getBounds());
}
</script>
<input id="clickMe" type="button" value="clickme" onclick="drawOnclick();" />
<div id="map">
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBbns5KFelTGVj8E8FHdlJfdM9lEHHo4OA&libraries=visualization&callback=initMap" async="async" defer="defer"></script>