Thursday 23 May 2019

arcgis desktop - Convert XY points to a line?



Someone mistakenly saved a GPS track as waypoints and then sent them along to me in a .csv file. They want a line back (shapefile). What's the simplest method to convert this to a line? Available tools are Arcmap, gdal/ogr and qgis more or less in order of preference. I'd rather not install an additional tool; an online conversion service would be okay.


Latitude,Longitude,Date,Time,ampm,,,
60.71586,-135.07476,25/07/2010,9:26:15,PM,,,,,
60.71637,-135.07563,25/07/2010,9:26:12,PM,,,,,
60.71648,-135.07612,25/07/2010,9:26:11,PM,,,,,
60.71664,-135.07707,25/07/2010,9:26:09,PM,,,,,
60.71672,-135.07756,25/07/2010,9:26:08,PM,,,,,

Answer



It seems like the crucial thing you want here is for the points in the line to be sorted by the time of capture, spread across three column rows. While you could organise the data in a spreadsheet, I often find writing a quick script provides the most flexibility:


import csv

from datetime import datetime
try:
from osgeo import ogr
except ImportError:
import ogr

SHP_FILENAME = "output.shp"
CSV_FILENAME = "input.csv"

r = csv.reader(open(CSV_FILENAME, 'r'), delimiter=',', quotechar=None)

header = dict(((str, i) for i, str in enumerate(r.next())))

# load data rows into memory
rows = [row for row in r]

# sort by date and time ascending
rows.sort(key=lambda row: datetime.strptime(
(row[header['Date']] + ' ' + row[header['Time']] + ' ' +
row[header['ampam']]),
'%d/%m/%Y %I:%M:%S %p'))


# Create new shapefile
ogr.UseExceptions()
ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource(SHP_FILENAME)
layer = ds.CreateLayer("data", None, ogr.wkbLineString)

# Create a new line geometry
line = ogr.Geometry(type=ogr.wkbLineString)

# Add GPS points to line

lon_idx, lat_idx = header['Longitude'], header['Latitude']
for row in rows:
line.AddPoint(float(row[lon_idx]), float(row[lat_idx]))

# Add line as a new feature to the shapefile
feature = ogr.Feature(feature_def=layer.GetLayerDefn())
feature.SetGeometryDirectly(line)
layer.CreateFeature(feature)

# Cleanup

feature.Destroy()
ds.Destroy()

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...