In order to make the initial horizontal alignment of railway line more practical and meet the design code, a method for automatic generation of railway horizontal alignment was proposed based on knowledge reasoning and optimal route analysis in raster data format. First, the Dijkstra algorithm was improved by using Knight's neighboring pattern of 16 cells and taking account, in a construction cost model, of the influence of design slope on the bridge and tunnel construction costs and target speed of railway line on its length concerning cost. Then, the improved Dijkstra algorithm was used to propose an optimal route among the existing control points. Finally, by gradual dichotomy and automatic configuration of the horizontal curve, the vectorized optimal route was converted to an initial horizontal alignment that meets the design code. An actual application in a GIS-based railway location intelligent environment manifested that the proposed method can generate a satisfactory initial railway horizontal alignment. Compared with the conventional method, the proposed method can save more than 90% time in the design of local railway horizontal alignment.