Aug
18
2012
Calculate KML Distance Using Python
Posted by digeo in Python, tags: Blackberry, KML, Lazarus, pythonIntroduction
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:
- Remove all new line chars to have one long string of xml tags
- Find <coordinates > and copy coordinates until </coordinates > to string
- KML data looks like ” long,lat,altitude long,lat,altitude … long,lat,altitude “. I use tuples to work with comma and space separated values.
- Use for loop to go through coords values and use Haversine formula to calculate distance between cords.
- Save all these values to file.
Future impovements will be:
- Implement a GUI
- Batch convert KML files
- 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
Entries (RSS)