简体   繁体   中英

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

This is my Javascript code to obtain the marker. The page is loading the map but the marker doesn't appear.

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

Two issues:

  1. create the marker inside your initMap function (which most likely is the callback function that runs once the API is loaded)

  2. use a valid value for the google.maps.Map object. (the map variable inside the initMap function would be best, this where you have it is probably the window object).

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

结果地图的屏幕截图

code snippet:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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