0

I'm trying to use Google MAP API v3 with the following code.

<html>
<head>
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=drawing"></script>
    <script type="text/javascript">
    jQuery( function( $ ) 
    {
        var i = 1;

        initMap( $( '.map' ) );

        function initMap( $map )
        {
            google.maps.event.addDomListener( window, 'load', function()
            {
                var myOptions = {
                    center: new google.maps.LatLng( -16.920334, 145.770859 ),
                    zoom: 12,
                };
                var drawingManager = new google.maps.drawing.DrawingManager();
                var map = new google.maps.Map( $map[0], myOptions );
                drawingManager.setMap( map );
            } );
        }

        $( 'body' ).on( 'click', '.add-map', function()
        {
            i++;
            $( '.maps' ).append( '<div class="map-' + i + '" style="width: 800px; height: 500px;"></div>' );
            initMap( $( '.map-' + i ) );
        } );
    } );
    </script>
</head>
<body>
    <input type="button" class="add-map" value="Add Map">
    <div class="maps">
        <div class="map" style="width: 800px; height: 500px;"></div>
    </div>
</body>
</html>

What i want to do is when user clicks Add Map button, a map will be created dynamically. The default map is loaded but the next map isn't. How can i fix this issue, thank you!

Here is my fiddle demo

6
  • 2
    missing "-" in initMap( $( '.map' + i ) ); Commented Dec 11, 2015 at 12:52
  • Hint: the window has already loaded when you click the button and will never fire the load event again. Commented Dec 11, 2015 at 12:52
  • @ShailendraSharma thank you, I've added - but it can't fix my issue Commented Dec 11, 2015 at 13:00
  • @Adam thank you, is there any solution to make it work? Commented Dec 11, 2015 at 13:02
  • i have already fixed this issue,it's working fine Commented Dec 11, 2015 at 13:02

1 Answer 1

1

This is working fiddle of your code what is wrong with your code is you open a map on window load by initMap( $( '.map' ) ); which run google.maps.event.addDomListener( window, 'load', function() and later you call same function on click that not make any sense , because this line register window load event to run function inside it's block

and appending new map in existing map also not working, that's all hope This may help

it's not complete code just a idea how this will work

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.