Centering Google Maps on responsive resize with marker

前端 未结 1 547
难免孤独
难免孤独 2021-01-07 06:23

I\'m trying to get Google Maps to keep its center when resizing responsively.

I\'ve managed to get the map to center but can\'t work out how to add my marker back i

1条回答
  •  臣服心动
    2021-01-07 07:09

    Here is a first step to get what you want to do:

    var map; //<-- This is now available to both event listeners and the initialize() function
    var mapCenter; // Declare a variable to store the center of the map
    var centerMarker; // declare your marker
    
    function initialize() {
        var mapOptions = {
            center: new google.maps.LatLng(LAT,LNG),
            zoom: 10,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: false,
            scrollwheel: false,
            keyboardShortcuts: false,
        };
    
        map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    
        // Create a new marker and add it to the map
        centerMarker = new google.maps.Marker({
            position: new google.maps.LatLng(LAT,LNG),
            map: map,
            title: 'Title',
            animation: google.maps.Animation.DROP
        });
    
        mapCenter = map.getCenter(); // Assign the center of the loaded map to the valiable
    }
    
    
    
    google.maps.event.addDomListener(window, 'load', initialize);
    
    google.maps.event.addDomListener(window, "resize", function() {
    
        // Here you set the center of the map based on your "mapCenter" variable
        map.setCenter(mapCenter); 
    });
    

    Edit: Based on @Chad Killingsworth comment: You may want to add an 'idle' event handler to the map to set the mapCenter variable. You can achieve this like this:

    google.maps.event.addListener(map,'idle',function(event) {
        mapCenter = map.getCenter();
    });
    

    Description of the 'idle' event from the doc:

    This event is fired when the map becomes idle after panning or zooming.

    0 讨论(0)
提交回复
热议问题