繁体   English   中英

我正在尝试使用Google Maps Javascript API添加标记,但它无法正常工作

[英]I'm trying to add a marker using Google Maps Javascript API but it isn't working

这是我获取标记的Javascript代码。 页面正在加载地图,但标记未显示。

function initMap(){
      var options = {
        zoom:13,
        center:{lat:42.3601,lng:-71.0589}//Change these coordinates to change the center
      }
      var map = new google.maps.Map(document.getElementById('map'),options);
    }
    var location = new google.maps.LatLng(42.3601, -71.0589);
    var marker = new google.maps.Marker({
      position:location,
      map:this
    });
    marker.setMap(map);

两个问题:

  1. initMap函数中创建marker (很可能是加载API后运行的回调函数)

  2. 使用google.maps.Map对象的有效值。 (在map里面变量initMap功能将是最好的, this ,你有这大概是window对象)。

function initMap(){
  var options = {
    zoom:13,
    center:{lat:42.3601,lng:-71.0589}//Change these coordinates to change the center
  }
  var map = new google.maps.Map(document.getElementById('map'),options);
  var location = new google.maps.LatLng(42.3601, -71.0589);
  var marker = new google.maps.Marker({
    position:location,
    map:map
  });
}

概念证明小提琴

结果地图的屏幕截图

代码段:

 function initMap() { var options = { zoom: 13, center: { lat: 42.3601, lng: -71.0589 } //Change these coordinates to change the center } var map = new google.maps.Map(document.getElementById('map'), options); var location = new google.maps.LatLng(42.3601, -71.0589); var marker = new google.maps.Marker({ position: location, map: map }); } 
 html, body, #map { height: 100%; margin: 0; padding: 0; } 
 <div id="map"></div> <!-- Replace the value of the key parameter with your own API key. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM