Python Version: 2.6.6

Some part of the content of the KML file:

<Placemark>
<name>1</name>
<Style><LineStyle><color>ff0000ff</color></LineStyle><PolyStyle><fill>0</fill></PolyStyle></Style>
<ExtendedData><SchemaData schemaUrl=”#out”>
<SimpleData name=”Name”>1</SimpleData>
</SchemaData></ExtendedData>
<Polygon><outerBoundaryIs><LinearRing><coordinates>-2.708420581620357,34.031776223583954 -2.708420581620357,34.029081277731592 -2.705725635767999,34.029081277731592 -2.705725635767999,34.031776223583954 -2.708420581620357,34.031776223583954</coordinates></LinearRing></outerBoundaryIs></Polygon>
</Placemark>

as you can see we want to extract GPS coordinates in betweem <coordinates> and </coordinates>.

 

Here is the code:

Function name: Find_Polygon_Geometry

Input: a line at a time in KML file

Output: a list for X-Coordinates and another list for  Y-Coordinates

def Find_Polygon_Geometry(Input_Line):
	First = "<coordinates>"
	Last = "</coordinates>"

	Final_Polygon_Geometry_X = []
	Final_Polygon_Geometry_Y = []
	Result_One_Line = ""
	Result_One_Line = str(find_between(Input_Line, First, Last ))
	#print " ---------------------------------------------------"
	if Result_One_Line != "":
		print 'Result_One_Line: ', Result_One_Line
		Final_Polygon_Geometry = ""
		Result_One_Line = Result_One_Line.split()
		X_Value = 0
		Y_Value = 0
		X_and_Y_List = ""
		for i in range(0, len(Result_One_Line)):
			X_and_Y_List = ""
			X_and_Y_List = Result_One_Line[i].split(",")
			#print 'X_and_Y_List: ', X_and_Y_List
			if len(X_and_Y_List) == 2:
				X_Value = float(X_and_Y_List[0])
				Final_Polygon_Geometry_X.append(X_Value)
				Y_Value = float(X_and_Y_List[1])
				Final_Polygon_Geometry_Y.append(Y_Value)
				
	return Final_Polygon_Geometry_X, Final_Polygon_Geometry_Y

 

Function name: find_between

Input: string, starting boundary and end boundary

Output:the string in between first and last

The function “find_between” is used from the Stackoverflow:

def find_between( s, first, last ):
	try:
		start = s.index( first ) + len( first )
		end = s.index( last, start )
		return s[start:end]
	except ValueError:
		return ""

 

to call the function “Find_Polygon_Geometry” in your main file you can use the following code:

KML_File_Name = "FileName.kml"
Returned_Polygon_Geometry = ""
with open(KML_File_Name, 'r') as KML_File:
	for line in KML_File:
		cleand_line = line.strip()
		#print 'cleand_line: ',cleand_line
		Returned_Polygon_Geometry = ""
		Returned_Polygon_Geometry_X , Returned_Polygon_Geometry_Y  = 
                                               Find_Polygon_Geometry(cleand_line)
		# Your code starts here

End!

 

Advertisements