-
Notifications
You must be signed in to change notification settings - Fork 0
/
getGeoCode.php
executable file
·106 lines (89 loc) · 2.78 KB
/
getGeoCode.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#!/usr/bin/php -q
<?
$args = $_SERVER['argv'];
$file = $args[1];
$output = $args[2];
$csvKeyCount = 0;
function getCsv($file){
if(preg_match("/\.csv$/", $file)){
return file($file);
}else{
return false;
}
}
function csv2Array($csv){
$csv = array_map('str_getcsv', $csv);
$csvShift = array_shift($csv);
$arr = array();
// count($csvShift);
foreach ($csv as $c) {
if(count($csvShift) == count($c)){
$arr[] = array_combine($csvShift, $c);
}
}
return $arr;
}
function returnAddress($arr){
$exclude = array('Customer#', 'Customer Name', 'Phone#');
foreach( $exclude as $e){
unset($arr[$e]);
}
return str_replace(' ', '+', join('+', array_values($arr) ));
}
function getGeoLocation($address){
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=$address";
$json = file_get_contents($url);
if($json){
$geo = json_decode($json, true);
return $geo['results'][0]['geometry']['location'];
}else{
return false;
}
}
function convert2Csv($array, $allowKeys = false){
$csv = '';
$firstRow = '';
foreach($array as $key => $row) {
if($key == 0 && $allowKeys){
$firstRow = implode(',', array_keys($row)) . "\r\n";
}
$csv .= implode(',', $row) . "\r\n";
}
return $firstRow . $csv;
}
function export($fileName, $content, $allowKeys = false){
if( $allowKeys ){
file_put_contents($fileName, "$content", FILE_APPEND);
}else{
file_put_contents($fileName, "$content");
}
}
function init($file, $output){
$originalCsv = array();
$newCsv = array();
$export = array();
$allowKeys = count(file($output)) == 0 ? true : false;
$csv = getCsv($file);
if($csv){
$csvArr = csv2Array($csv);
foreach($csvArr as $k => $c){
$address = returnAddress($c);
$geo = getGeoLocation($address);
if($geo){
$csvArr[$k]['lat'] = $geo['lat'];
$csvArr[$k]['lng'] = $geo['lng'];
array_push($newCsv, $csvArr[$k]);
}else{
array_push($originalCsv, $csvArr[$k]);
}
}
$originalCsv = convert2Csv($originalCsv);
$newCsv = convert2Csv($newCsv, $allowKeys);
export($file, $originalCsv);
export($output, $newCsv, !$allowKeys);
}
}
if(count(file($file)) > 0){
init($file, $output);
}
?>