0

I have function that is called after full loading of page. This function create Google Map object:

function initMap() {
var map = new google.maps.Map(mapDiv, {
            center: {lat: 0, lng: 0},
            zoom: 5,
            mapTypeId: 'roadmap'
        });
}

Below this function there is method click:

$(function() {
    $( ".click" ).click(function() {
        // How to get instance map here?
    });
});

How I can get access to object var map in $( ".click" )

0

2 Answers 2

3

You could add return statement to your function initMap() :

function initMap() {
    var map = new google.maps.Map(mapDiv, {
        center: {lat: 0, lng: 0},
        zoom: 5,
        mapTypeId: 'roadmap'
    });

    return map;
}

$(function() {
    var map = initMap();

    $( ".click" ).click(function() {
         // use map here
     });
});

Hope this helps.

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

6 Comments

I can not initialize several time initMap(), because this function is called automatically when page loaded.
What you mean by because this function is called automatically when page loaded.? from where?
When I call init again, it reloads map, this is problem
From where you call init the first time ?
From <script src...>
|
1

You can put var outside the function:

var map;

function initMap() {
    map = new google.maps.Map(mapDiv, {
        center: {lat: 0, lng: 0},
        zoom: 5,
        mapTypeId: 'roadmap'
    });
}

$(function() {
    $( ".click" ).click(function() {
        map // you can access map here :)

    });
});

If you need to check is map have been init, check is map == undefined or not.

Reference: https://developers.google.com/maps/documentation/javascript/examples/polyline-complex

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.