Python Forum
Visualize data using KML files - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Visualize data using KML files (/thread-26232.html)



Visualize data using KML files - annelewis - Apr-24-2020

Hello. I'm not quite sure how to amend my code below to get the output to a kml format file.

Question:
Write a function PrintLocation which takes four parameters, a file name containing animal location data, a distance in kilometres, and the latitude and longitude of the location. It should output, to a file called “output.kml”, in kml format all animals found within the distance of the specified location. Your script should call PrintLocation with the data file “Mammal.txt”, a distance of 15.0, a latitude of 51.452884 and longitude of -0.973906 (Reading).

What I have:
import math
  
def LineToList(FileName):
    FileIn = open(FileName, "r")
    DataList = []
    for Line in FileIn:
        Line = Line.rstrip().split("\t")
        DataList.append(Line)
    FileIn.close()
    return DataList
 
def CalculateDistance(Lat1, Lon1, Lat2, Lon2):
  
    Lat1 = float(Lat1)
    Lon1 = float(Lon1)
    Lat2 = float(Lat2)
    Lon2 = float(Lon2)
  
    nDLat = (Lat1 - Lat2) * 0.017453293
    nDLon = (Lon1 - Lon2) * 0.017453293
  
    Lat1 = Lat1 * 0.017453293
    Lat2 = Lat2 * 0.017453293
  
    nA = (math.sin(nDLat/2) ** 2) + math.cos(Lat1) * math.cos(Lat2) * (math.sin(nDLon/2) ** 2 )
    nC = 2 * math.atan2(math.sqrt(nA),math.sqrt( 1 - nA ))
    nD = 6372.797 * nC
  
    return nD
  
def PrintLocation(FileName, dist, Lat, Lon):
  
   #Input:
       #FileName = a file name containing animal location data (str)
       #dist = a distance in kilometres (float)
       #Lat = Latitude (float)
       #Lon = Longitude (float)
   #Output:
       #returns number of animals found in the area (int)
  
    DataList = LineToList("Mammal.txt")
    PrintLocation = 0
    animalList = list()
    for Line in DataList:
        if CalculateDistance(Line[1], Line[2], 51.452884, -0.973906)<=15:
            PrintLocation += 1
    return PrintLocation


var = PrintLocation("Mammal.txt", 15, 51.452884, -0.973906)
print(var)
Can anyone guide me on what to do? Many thanks.


RE: Visualize data using KML files - Jeff900 - Apr-24-2020

Ar you familiar with KML yourself? I did some research since your last thread, and saw it is just a XML file. But probaly with a specific data structure, to standardize things.

So in fact you only have to find out how to handle a XML file with Python. And you can trust me on this, you don't have to find out a thing, except a decent library to use.