2013-03-14 177 views
0

无法添加标记,可能很简单,但我是新手。谢谢。谷歌地图:无法添加标记

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?&sensor=true"></script> 
    <script type="text/javascript"> 

     function addMarker() { 
      var marker = new google.maps.Marker({ 
       position: new google.maps.LatLng(-34.397, 150.644), 

       title:"Hello World!" 
      }); 
     } 


     function initialize() { 
      var mapOptions = { 
       center: new google.maps.LatLng(-34.397, 150.644), 
       zoom: 8, 
       mapTypeId: google.maps.MapTypeId.ROADMAP 
      }; 
      var map = new google.maps.Map(document.getElementById("map-canvas"), 
      mapOptions); 
     } 
     google.maps.event.addDomListener(window, 'load', initialize); 

     $(document).ready(function() { 
      addMarker(); 
     }) 

    </script> 

回答

3

两个问题,你需要设置地图标记的变量。您的地图变量对于初始化函数是本地的。

  • 在初始化映射之后,从初始化函数(映射存在的地方)调用addMarker函数。

    function addMarker(map) { 
         var marker = new google.maps.Marker({ 
         position: new google.maps.LatLng(-34.397, 150.644), 
         map:map, 
    
         title:"Hello World!" 
         }); 
        } 
    
        function initialize() { 
         var mapOptions = { 
         center: new google.maps.LatLng(-34.397, 150.644), 
         zoom: 8, 
         mapTypeId: google.maps.MapTypeId.ROADMAP 
         }; 
         var map = new google.maps.Map(document.getElementById("map-canvas"), 
         mapOptions); 
         addMarker(map); 
        } 
    

working example

+0

谢谢,这也工作。 – user990717 2013-03-14 15:45:58

1

你必须设置地图属性的标记构造函数或一个新的对象上调用的setMap:

var marker = new google.maps.Marker({ 
      position: new google.maps.LatLng(-34.397, 150.644), 
      map: map, //make your map object global! 
      title:"Hello World!" 
     }); 

marker.setMap(map); 

https://developers.google.com/maps/documentation/javascript/reference#Marker

编辑: 我对评论使地图对象全局显然被忽视,所以在这里它是:

地图对象应该是全球性的,不仅对这种解决方案的缘故,但你会需要它的多种功能,在你的脚本

+0

在文档我读它说:地图(可选)指定要在其上放置标记,所以我有点困惑的Map对象。 – user990717 2013-03-14 15:29:58

+0

地图变量不在范围内。 – geocodezip 2013-03-14 15:30:21

+0

@geocodezip我建议它在地图属性旁边,我应该强调它更多 – slawekwin 2013-03-14 15:36:40