I just started playing around with python and I like what I see so far. I just completed an application in Lazarus that extracts data from the KML file generated by an application on my Blackberry. It surprised me that it seemed to take me a few hours to achieve what I feel have taken longer to do in Pascal.

SO, I thought I will post the python code here. As I am learning python, I opted not to use any XML libraries as I need to get to know the basic python code first. The script has no GUI. This will be the next thing to learn of course.

The script works as follows:

  1. Remove all new line chars to have one long string of xml tags
  2. Find <coordinates > and copy coordinates until </coordinates > to string
  3. KML data looks like ” long,lat,altitude  long,lat,altitude … long,lat,altitude “. I use tuples to work with comma and space separated values.
  4. Use for loop to go through coords values and use Haversine formula to calculate distance between cords.
  5. Save all these values to file.

Future impovements will be:

  1. Implement a GUI
  2. Batch convert KML files
  3. Use google API to reverse geocode addresses

Haversine Formula

def haversine(lat1, lon1, lat2, lon2):

#R = 6372.8

R = 6378.137

# In kilometers

dLat = math.radians(lat2 - lat1)

dLon = math.radians(lon2 - lon1)

lat1 = math.radians(lat1)

lat2 = math.radians(lat2)

a = math.sin(dLat / 2) * math.sin(dLat / 2) + math.sin(dLon / 2) * math.sin(dLon / 2) * math.cos(lat1) * math.cos(lat2)

c = 2 * math.asin(math.sqrt(a))

return R * c

Leave a Reply

− 3 = three