用谷歌地图api画圆圈

Rob*_*lds 0 html javascript google-maps

我有这个简单的代码:

<!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&amp;libraries=visualization&amp;callback=initMap" async="async" defer="defer"></script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我的目标是当我点击按钮时在巴黎上画一个红色圆圈。问题是当我单击按钮时,什么也没有发生。

我不明白的是,当我设置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
  });
}
Run Code Online (Sandbox Code Playgroud)

圆就画好了。有人可以解释一下吗?

geo*_*zip 6

map 变量是 initialize 函数的局部变量。要在 HTML 单击函数(用于按钮)中使用它,它需要在全局范围内(HTML 单击函数运行的地方)。要修复它,请删除var在 initialize 函数之外声明它的 :

// map variable in global scope
var map;
//Initialise la map
function initMap() {
  // initialize the map variable
  map = new google.maps.Map(document.getElementById('map'), {
  // ...
Run Code Online (Sandbox Code Playgroud)

工作代码片段:

// map variable in global scope
var map;
//Initialise la map
function initMap() {
  // initialize the map variable
  map = new google.maps.Map(document.getElementById('map'), {
  // ...
Run Code Online (Sandbox Code Playgroud)
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}
Run Code Online (Sandbox Code Playgroud)