我正在尝试使用Google Maps Javascript API添加标记,但是它不起作用

时间:2019-04-08 16:27:22

标签: javascript google-maps-api-3 google-maps-markers

这是我获取标记的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 个答案:

答案 0 :(得分:0)

两个问题:

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

  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
  });
}

proof of concept fiddle

screenshot of resulting 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>