Gery
Gery

Reputation: 9036

Problems adding a simple marker with Google Maps

I have problems adding a marker with Google Maps, it seems to me that there is something in the code that I am missing, please bear with me if the following is too simple to achieve:

 <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>

Upvotes: 0

Views: 84

Answers (1)

jami0821
jami0821

Reputation: 311

Rendering into the #map element works when done this way:

<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>

Also remember to use the correct function name in the callback (init in this case):

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

Upvotes: 1

Related Questions