Google地图js标记未显示

时间:2016-05-13 13:53:07

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

我正在尝试将谷歌地图实施到项目中,但我无法将标记显示在地图上。这是我的代码:

HTML:

<div id="map-canvas"></div>

CSS:

#map-canvas {
    border: 1px solid #D8D8D8;
    height: 445px;
    width: 100%;  
}

JS:

function initialize() {
        var myLatLng = {lat: 40.6700, lng: -73.9400};
        var mapCanvas = document.getElementById('map-canvas');
        var mapOptions = {
            center: myLatLng,
            zoom: 13,
            navigationControl: true,
            mapTypeControl: true,
            scaleControl: true,
            scrollwheel: false,
            draggable: true,
          mapTypeId: google.maps.MapTypeId.TERRAIN
        }
        var map = new google.maps.Map(mapCanvas, mapOptions)

        var marker = new google.maps.Marker({
                position: myLatLng,
                map: map-canvas,
                icon: "../images/map.png",
                title: 'Find us here!'
            });
        marker.setMap(map-canvas);
      }
      google.maps.event.addDomListener(window, 'load', initialize);

我已经阅读了一些线程并尝试了多个代码变体,似乎没有任何工作。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

假设您的标记图标可用,则需要将markermap属性设置为google.maps.Map对象。在您的代码中map而非map-canvas

更改:

var marker = new google.maps.Marker({
            position: myLatLng,
            map: map-canvas,
            icon: "../images/map.png",
            title: 'Find us here!'
        });
    marker.setMap(map-canvas);

要:

var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            icon: "../images/map.png",
            title: 'Find us here!'
        });
    marker.setMap(map);

proof of concept fiddle

代码段

function initialize() {
  var myLatLng = {
    lat: 40.6700,
    lng: -73.9400
  };
  var mapCanvas = document.getElementById('map-canvas');
  var mapOptions = {
    center: myLatLng,
    zoom: 13,
    navigationControl: true,
    mapTypeControl: true,
    scaleControl: true,
    scrollwheel: false,
    draggable: true,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  }
  var map = new google.maps.Map(mapCanvas, mapOptions)

  var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    icon: "http://maps.google.com/mapfiles/ms/micons/blue.png",
    title: 'Find us here!'
  });
  marker.setMap(map - canvas);
}
google.maps.event.addDomListener(window, 'load', initialize);
#map-canvas {
  border: 1px solid #D8D8D8;
  height: 445px;
  width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>

答案 1 :(得分:0)

尝试改变:

 var map = new google.maps.Map(mapCanvas, mapOptions)

致:

  var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);