使用Google地图添加简单标记时出现问题

时间:2016-12-26 20:05:28

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

我在使用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>

1 个答案:

答案 0 :(得分: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>