Refactor import kml to handle multiple polygons #141

This commit is contained in:
Kendrick Chan 2019-03-10 19:47:33 +08:00
parent f93b675976
commit d24be90314
2 changed files with 30 additions and 36 deletions

View file

@ -15,7 +15,7 @@ class ImportKMLFileCommand extends Command
{
protected function configure()
{
$this->setName('supportedarea:add')
$this->setName('supportedarea:import')
->setDescription('Extracts map data of the supported area from the KML file and saves to database')
->setHelp('Gets the coordinates of the supported area and saves to the database')
->addArgument('file', InputArgument::REQUIRED, 'Path to the KML file');
@ -31,14 +31,6 @@ class ImportKMLFileCommand extends Command
protected function execute(InputInterface $input, OutputInterface $output)
{
$kml_file = $input->getArgument('file');
try
{
$fh = fopen($kml_file, "r");
}
catch (Exception $e)
{
throw new Exception('The file "' . $kml_file . '" could not be read.');
}
$this->importer->getMapData($kml_file);
}

View file

@ -23,9 +23,7 @@ class KMLFileImporter
public function getMapData($fh)
{
$coordinate_array = array();
$point_array = array();
$supported_area = new SupportedArea();
$placemark_name = '';
$reader = new XMLReader();
$reader->open($fh);
@ -39,42 +37,46 @@ class KMLFileImporter
if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == "name")
{
$placemark_name = $reader->readInnerXML();
$supported_area->setName($placemark_name);
}
if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == "coordinates")
{
$coordinates = $reader->readInnerXML();
// clean and parse the coordinates data from KML
$coordinates = preg_replace('/\s\s+/', ',', $coordinates);
$parsed_coordinates = explode(',', $coordinates);
// each polygon is a new area
$supported_area = new SupportedArea();
$supported_area->setName($placemark_name);
for ($x = 0; $x < sizeof($parsed_coordinates); $x++)
$point_array = [];
$coordinates = $reader->readInnerXML();
// get each line
$coord_split = explode("\n", $coordinates);
// go through all the coordinates
foreach ($coord_split as $coord)
{
if (($x%3 != 0) && ($parsed_coordinates[$x] != ""))
{
$coordinate_array[] = $parsed_coordinates[$x];
}
// skip blank lines
$coord_trim = trim($coord);
if (strlen($coord_trim) <= 0)
continue;
// echo "$coord_trim\n";
$point_split = explode(',', $coord_trim);
$point_array[] = new Point($point_split[0], $point_split[1]);
}
// create an array of Points for the Polygon constructor
$i = 0;
while($i < sizeof($coordinate_array))
{
$point_array[] = new Point($coordinate_array[$i], $coordinate_array[++$i]);
$i++;
}
$area = new Polygon(array(new LineString($point_array)));
$area = new Polygon([new LineString($point_array)]);
$supported_area->setCoverageArea($area);
// add supported area
$this->em->persist($supported_area);
}
}
break;
}
}
$reader->close();
// add supported area
$em = $this->em;
$em->persist($supported_area);
$em->flush();
$this->em->flush();
}
}