2016-12-26 98 views
0

我在使用Google地圖添加標記時遇到了問題,但在我看來,代碼中存在某些內容,如果以下內容太簡單無法實現,請耐心等待:在Google地圖中添加簡單標記時出現問題

<script type="text/javascript"> 
    google.maps.event.addDomListener(window, 'load', init); 

    function init() { 

     var ll = new google.maps.LatLng(12.0633419, 77.0998847); 

     var mapOptions = { 
      zoom: 12, 
      center: ll, 
      styles: [{ 
       featureType:"all", 
       elementType:"all", 
       stylers: [ 
        { invert_lightness:false }, 
        { saturation:0 }, 
        { lightness:0 }, 
        { gamma:0.5 }, 
        { hue:"#2f7ed8" } 
       ] 
      }] 
     }; 

     // add marker to the map 
     var marker = new google.maps.Marker({ 
      position: ll, 
      icon: ll, 
      map: map, 
      title: 'IT DOES NOT WORK!!!!' 
     }); 
     //marker.setMap(map); 
     //marker.setPosition(ll); 

     var mapElement = document.getElementById('map'); 

     var map = new google.maps.Map(mapElement, mapOptions); 
    } 

</script> 
+0

標記看起來不錯,也許你應該在定義變量'map'後添加它吧! – user2314737

+0

@ user2314737感謝提示,不知道爲什麼它沒有工作,但現在它確實,jami0821的答案奏效! – Gery

+1

你需要初始化地圖變量_before_你爲它添加標記。 – geocodezip

回答

1

渲染到#map單元工作時,做這樣:

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

<script type="text/javascript"> 

    function init() { 
    var ll = new google.maps.LatLng(12.0633419, 77.0998847); 

    var map = new google.maps.Map(document.getElementById('map'), { 
     zoom: 4, 
     center: ll 
    }); 

    // add marker to the map 
    var marker = new google.maps.Marker({ 
     position: ll, 
     map: map 
    }); 
    } 

</script> 

還記得在回調(在這種情況下init)使用正確的函數名稱:

<script async defer 
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=init"> 
</script> 
+0

你是最棒的!謝謝!! – Gery