Get google.maps.Map instance from a HTMLElement

后端 未结 5 617
故里飘歌
故里飘歌 2021-01-31 07:21

I have an existing map on a page. I can select that element using something along the lines of document.getElementById() to get the HTMLElement javascript object. Is it possible

5条回答
  •  旧巷少年郎
    2021-01-31 08:19

    You can get google.maps.Map object from DOM Element, with a slight trick.

    When you initialize map object, you need to store the object on element's data attribute.

    Example:

    $.fn.googleMap = function (options) {
        var _this = this;
    
        var settings = $.extend({}, {
            zoom: 5,
            centerLat: 0,
            centerLon: 0
        }, options);
    
        this.initialize = function () {
            var mapOptions = {
                zoom: settings.zoom
            };
    
            var map = new google.maps.Map(_this.get(0), mapOptions);
            // do anything with your map object here,
            // eg: centering map, adding markers' events
    
            /********************************************
             * This is the trick!
             * set map object to element's data attribute
             ********************************************/
            _this.data('map', map);
    
            return _this;
        };
        // ... more methods
    
        return this;
    };
    

    After you define a map element, eg:

    var mapCanvas = $('#map-canvas');
    var map = mapCanvas.googleMap({
        zoom: 5,
        centerLat: 0,
        centerLong: 0
    });
    // ... add some pre-load initiation here, eg: add some markers
    // then initialize map
    map.initialize();
    

    you can then get the map object later on by using element's ID, eg:

    var mapCanvas = $('#map-canvas');
    $('.location').on('click', function () {
        // google map takes time to load, so it's better to get
        // the data after map is rendered completely
        var map = mapCanvas.data("map");
        if (map) {
            map.panTo(new google.maps.LatLng(
                $(this).data('latitude'),
                $(this).data('longitude')
                ));
        }
    });
    

    By using this method, you can have multiple maps with different behaviors on a page.

提交回复
热议问题