Google Maps API v3 - 无法创建位置标记

时间:2015-09-03 05:14:42

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

尝试在嵌入的Google地图上执行简单的位置标记。一切看起来都正确,但不起作用。



<link rel="stylesheet" type="text/css" href="default.css"/>
<script src="https://maps.googleapis.com/maps/api/js"></script>
    <script>
      function initialize() {
        var mapCanvas = document.getElementById('map');
        var mapOptions = {
          center: new google.maps.LatLng(40.0501322,-82.914233),
          zoom: 13,
          mapTypeId: google.maps.MapTypeId.HYBRID
        }
        var map = new google.maps.Map(mapCanvas, mapOptions)
      }
      
      
      google.maps.event.addDomListener(window, 'load', initialize);
      
       var marker = new google.maps.Marker({  
      position: new google.maps.LatLng(40.0496714,-82.9121331),  
      map: map  
    });          
    </script></head>
&#13;
&#13;
&#13;

地图正常加载,但未找到标记。

2 个答案:

答案 0 :(得分:0)

您需要在初始化函数内(地图变量存在的位置)创建标记。

&#13;
&#13;
function initialize() {
  var mapCanvas = document.getElementById('map');
  var mapOptions = {
    center: new google.maps.LatLng(40.0501322, -82.914233),
    zoom: 13,
    mapTypeId: google.maps.MapTypeId.HYBRID
  }
  var map = new google.maps.Map(mapCanvas, mapOptions)
  var marker = new google.maps.Marker({
    position: new google.maps.LatLng(40.0496714, -82.9121331),
    map: map
  });
}
google.maps.event.addDomListener(window, 'load', initialize);
&#13;
html,
body,
#map {
  height: 100%;
  width: 100%;
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

是的,您需要在代码的initialize()方法中初始化标记对象。一种方法是geocodezip如何演示。如果你想编写模块化代码,还有一种方法。

<script type="text/javascript">

    // Standard google maps function
    function initialize() {
        var myLatlng = new google.maps.LatLng(40.0501322, -82.914233);
        var myOptions = {
            zoom: 12,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        TestMarker();
    }

    // Function for adding a marker to the page.
    function addMarker(location) {
        marker = new google.maps.Marker({
            position: location,
            map: map
        });
    }

    // Testing the addMarker function
    function TestMarker() {
           GoldenGatePark = new google.maps.LatLng(37.7699298, -122.4469157);
           addMarker(GoldenGatePark);
    }
</script>

您已在 TestMarker函数中添加了一个标记,并在 initialize()方法中调用 TestMarker函数。您只需在 TestMarker函数代码中更改 LatLng 的值即可。