|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Coordinate Factory |
|
4
|
|
|
* |
|
5
|
|
|
* @author Marcus Jaschen <[email protected]> |
|
6
|
|
|
* @license https://opensource.org/licenses/GPL-3.0 GPL |
|
7
|
|
|
* @link https://github.com/mjaschen/phpgeo |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
namespace Location\Factory; |
|
11
|
|
|
|
|
12
|
|
|
use Location\Coordinate; |
|
13
|
|
|
use Location\Ellipsoid; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Coordinate Factory |
|
17
|
|
|
* |
|
18
|
|
|
* @author Marcus Jaschen <[email protected]> |
|
19
|
|
|
* @license https://opensource.org/licenses/GPL-3.0 GPL |
|
20
|
|
|
* @link https://github.com/mjaschen/phpgeo |
|
21
|
|
|
*/ |
|
22
|
|
|
class CoordinateFactory implements GeometryFactoryInterface |
|
23
|
|
|
{ |
|
24
|
|
|
/** |
|
25
|
|
|
* Creates a Coordinate instance from the given string. |
|
26
|
|
|
* |
|
27
|
|
|
* The string is parsed by a regular expression for a known |
|
28
|
|
|
* format of geographical coordinates. |
|
29
|
|
|
* |
|
30
|
|
|
* The simpler formats are tried first, before the string is |
|
31
|
|
|
* checked for more complex coordinate represenations. |
|
32
|
|
|
* |
|
33
|
|
|
* @param string $string formatted geographical coordinate |
|
34
|
|
|
* @param \Location\Ellipsoid $ellipsoid |
|
35
|
|
|
* |
|
36
|
|
|
* @return \Location\Coordinate |
|
37
|
|
|
*/ |
|
38
|
|
|
public static function fromString($string, Ellipsoid $ellipsoid = null) |
|
39
|
|
|
{ |
|
40
|
|
|
// The most simple format: decimal degrees without cardinal letters, |
|
41
|
|
|
// e. g. "52.5, 13.5" or "53.25732 14.24984" |
|
42
|
|
|
if (preg_match('/(-?\d{1,2}\.?\d*)[, ]\s*(-?\d{1,3}\.?\d*)/', $string, $match)) { |
|
43
|
|
|
return new Coordinate($match[1], $match[2], $ellipsoid); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
// Decimal degrees with cardinal letters, e. g. "N52.5, E13.5" or |
|
47
|
|
|
// "40.2S, 135.3485W" |
|
48
|
|
|
if (preg_match('/([NS]?\s*)(\d{1,2}\.?\d*)(\s*[NS]?)[, ]\s*([EW]?\s*)(\d{1,2}\.?\d*)(\s*[EW]?)/i', $string, $match)) { |
|
49
|
|
|
$latitude = $match[2]; |
|
50
|
|
|
if (trim(strtoupper($match[1])) === 'S' || trim(strtoupper($match[3])) === 'S') { |
|
51
|
|
|
$latitude = - $latitude; |
|
52
|
|
|
} |
|
53
|
|
|
$longitude = $match[5]; |
|
54
|
|
|
if (trim(strtoupper($match[4])) === 'W' || trim(strtoupper($match[6])) === 'W') { |
|
55
|
|
|
$longitude = - $longitude; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
return new Coordinate($latitude, $longitude, $ellipsoid); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
throw new \InvalidArgumentException("Format of coordinates was not recognized"); |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|