动态添加标记到Google地图

时间:2015-08-31 16:24:22

标签: google-maps

我的Google地图正在加载到正确的纬度和经度。我想在那个纬度和地点放置一个标记。

这是我的代码

    function initialize() {
        var mapCanvas = document.getElementById('map_canvas2');
        var myLatLng = { lat: contactLatitude, lng: contactLongitude };
        var mapOptions = {
            center: new google.maps.LatLng(contactLatitude, contactLongitude),
            zoom: 8,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var map = new google.maps.Map(mapCanvas, mapOptions);
        addMarker(myLatLng, map);
    }

    function addMarker(location, map) {
        var marker = new google.maps.Marker({
            position: location,
            title: 'Home Center'
        });
    }

    google.maps.event.addDomListener(window, 'load', initialize);

一切都显示得很好,但标记没有显示出来。我做错了什么?

1 个答案:

答案 0 :(得分:4)

您没有将标记添加到地图中。之一:

function addMarker(location, map) {
  var marker = new google.maps.Marker({
      position: location,
      title: 'Home Center',
      map:map
  });
}

function addMarker(location, map) {
  var marker = new google.maps.Marker({
      position: location,
      title: 'Home Center',
  });
  marker.setMap(map);
}

proof of concept fiddle

代码段



var contactLatitude = 42;
var contactLongitude = -72;

function initialize() {
  var mapCanvas = document.getElementById('map_canvas2');
  var myLatLng = {
    lat: contactLatitude,
    lng: contactLongitude
  };
  var mapOptions = {
    center: new google.maps.LatLng(contactLatitude, contactLongitude),
    zoom: 8,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(mapCanvas, mapOptions);
  addMarker(myLatLng, map);
}

function addMarker(location, map) {
  var marker = new google.maps.Marker({
    position: location,
    title: 'Home Center',
    map: map
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

html,
body,
#map_canvas2 {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas2" style="border: 2px solid #3872ac;"></div>
&#13;
&#13;
&#13;