Support

Account

Home Forums ACF PRO Keep Google Map centered on resize Reply To: Keep Google Map centered on resize

  • Would the following addition to the function make sense? At least it works but would there be a more elegant solution?

    function center_map( map ) {
    	// vars
    	var bounds = new google.maps.LatLngBounds();
     
    	// loop through all markers and create bounds
    	$.each( map.markers, function( i, marker ){
    		var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );
    		bounds.extend( latlng );
    	});
     
    	// only 1 marker?
    	if (map.markers.length == 0 ) {
          map.setCenter(new google.maps.LatLng(49.45203,11.07675));
          map.setZoom( 12 );
    	}
    	else if( map.markers.length === 1 ) {
    		// set center of map
    	    map.setCenter( bounds.getCenter() );
    	    map.setZoom( 16 );
    	}
    	else
    	{
    		// fit to bounds
    		map.fitBounds( bounds );
    	}
      google.maps.event.addDomListener(window, "resize", function() {
          google.maps.event.trigger(map, "resize");
           map.setCenter( bounds.getCenter() );
      });
    }