This paper proposes an online optimal active power flow for local battery energy storage systems (BESS), which are installed at feeder nodes, based on self-organizing hierarchical particle swarm optimization with time-varying acceleration coefficients to minimize power transmission loss in a middle voltage 6.6 KV photovoltaic-supplied microgrid. In addition, a central BESS, which is installed at an interconnection point, minimizes power flow from the utility to the microgrid through the interconnection point, and coordinates with a load ratio control transformer to stabilize local node voltages in the microgrid. The central BESS is designed to operate as a distribution static compensator when batteries in the central battery energy storage system are fully charged or fully discharged. Loop and radial structures of MG are studied to evaluate the effective of proposed method. MATLAB/Simulink is used to simulate the microgrid model. A conventional control method and the proposed control method are compared to evaluate its effectiveness.