Determine if coordinate is inside region (MKMapView, solve in PHP) - php

I'm using MKMapView and I send my php program the visible region (center lat, center lon, span lat, span lon). I need to determine if a coordinate is inside that region using php. I'm hoping there's a standard formula somewhere, but I haven't found one. I'll keep trying to come up with a formula, but it's surprisingly complicated (hopefully not as much as the haversine, which I don't believe I could have figured out myself).

lets try this logic
$topRightLongitude = $centerLongitude + $spanLongitude/2;
if($topRightLongitude > 180 and ($pointLongitude < 0))
$topRightLongitude = $topRightLongitude - 360; // (180*2) - positive becomes negative
$bottomLeftLongitude = $centerLongitude - $spanLongitude/2;
if($bottomLeftLongitude< -180 and ($pointLongitude > 0))
$bottomLeftLongitude= 360 + $bottomLeftLongitude; // now is negative and will become positive
$topRightLatitude = $centerLatitude + $spanLatitude/2;
if($topRightLatitude > 90 and ($pointLatitude < 0))
$topRightLatitude = $topRightLatitude - 180; // (90*2) - positive becomes negative
$bottomLeftLatitude = $centerLatitude - $spanLatitude/2;
if($bottomLeftLatitude< -90 and ($pointLatitude > 0))
$bottomLeftLatitude= 180 + $bottomLeftLongitude; // now is negative and will become positive
if you have
$centerLongitude = 179;
$spanLongitude = 20;
$pointLongitude = -179;
results
$topRightLongitude = -171;
$bottomLeftLongitude = 169;
so your point is in if you test like this:
if($pointLongitude < $topRightLongitude &&
$pointLongitude > $bottomLeftLongitude &&
$pointLatitude < $topRightLatitude &&
$pointLatitude > $bottomLeftLatitude){
echo 'in';
}else{
echo 'out';
}

My Solution
$top = $c_lat + ($d_lat / 2.0);
$bottom = $c_lat - ($d_lat / 2.0);
$left = $c_lon - ($d_lon / 2.0);
$right = $c_lon + ($d_lon / 2.0);
if($left < -180)
{
$second_left = $left + 360.0;
$second_right = 180.0;
$left = -180;
}
elseif($right > 180)
{
$second_right = $right - 360.0;
$second_left = -180.0;
$right = 180.0;
}
$inside = false;
if($t_lat > $bottom && $t_lat < $top && $t_lon > $left && $t_lon < $right)
$inside = true;
else if($second_right && $second_left)
{
if($t_lat > $bottom && $t_lat < $top && $t_lon > $second_left && $t_lon < $second_right)
$inside = true;
}
if($inside)
{
}
This seems to work with MKMapView since the region latitudes are always between -90 and 90.

This logic should work:
if ( ($X > $center_lat - $span_lat/2) &&
($X < $center_lat + $span_lat/2) &&
($Y > $center_lon - $span_lon/2) &&
($Y < $center_lon + $span_lon/2) ) {
echo "It's inside!";
} else {
echo "It's outside ...";
}

I had worked a solution for my own problem before, but for decimal values of coordinates and it works. May be if you can convert deg to decimal it might work.
I have renamed the variable according to your problem.
Here's the logic.
if
(
(
($lat - $spanLat) < $centerLat &&
$centerLat < ($lat+ $spanLat)
) &&
(
($long - $spanLong) < $centerLong &&
$centerLong < ($long + $spanLong)
)
)

Related

Calculating Longitude Center Over 180th Meridian

I am computing a simple average of latitude/longitude pairs to get the centerpoint (as projected on a flat plane) and I am struggling to develop an algorithm to correctly account for the 180th Meridian. I am developing this in PHP.
I'm computing a simple average, adding up all of the longitudes and dividing by the count. However, in a situation where there is, for example, a -175 and 175 point, it returns an average of 0, whereas I need a value of 180.
Once approach I tried was to add 360 to all negative values, take the average, and then subtract 360. This fixes the problem over the 180th Meridian, but it creates the same issue over the Prime Meridian (0 Meridian).
$neg_lng_flag = false;
//calculate centerpoint
$i = 0;
while($i < $vertice_count) {
$lat_sum += $vertice_obj[$i]->lat;
//if lng is negative, add 360
if($vertice_obj[$i]->lng < 0) {
$lng_sum += $vertice_obj[$i]->lng + 360;
$neg_lng_flag = true;
} else {
$lng_sum += $vertice_obj[$i]->lng;
}
$i++;
}
$avg_lat = round($lat_sum / $vertice_count,2);
$avg_lng = round($lng_sum / $vertice_count,2);
if($neg_lng_flag) {
$avg_lng = $avg_lng - 360;
if($avg_lng < -180) {
$avg_lng = $avg_lng + 180;
}
}
I am not sure what I can do to come up with a consistent algorithm to return a true center longitudal point for all scenarios. I have not been able to find a robust solution either here or through Google more generally. I would appreciate any outside consideration/ideas. Thank you.
I was able to come up with a robust solution for my purposes. In my case, I just needed to calculate the minimum and maximum Longitude coordinates, and if the difference exceeded 180, I knew to shift the negative values by +360, then calculate the average. If the average was greater than 180, I needed to subtract 360, and if it was less than -180 I needed to add 360.
//COMPUTE LONGITUDAL MIDPOINT
function getLngMidpoint($vertice_obj) {
//get min and max vals
$i = 0;
while($i < count($vertice_obj)) {
$min = $vertice_obj[$i]->lng;
$max = $vertice_obj[$i]->lng;
if($vertice_obj[i]->lng > $max) {
$max = $vertice_obj[$i]->lng;
}
if($vertice_obj[$i]->lng < $min) {
$min = $vertice_obj[$i]->lng;
}
$i += 1;
}
$shift = 0;
//check if distance between min and max > 180. If so, need to shift
if(($max - $min) > 180) {
//shift all lng by 180
$shift = 360;
}
$i = 0;
$sum_lng = 0;
while($i < count($vertice_obj)) {
if($vertice_obj[$i] < 0) {
$sum_lng += $vertice_obj[$i]->lng + $shift;
} else {
$sum_lng += $vertice_obj[$i]->lng;
}
$i += 1;
}
$avg_lng = $sum_lng / count($vertice_obj);
if($avg_lng > 180) {
$avg_lng = $avg_lng - 360;
}
if($avg_lng < -180) {
$avg_lng = $avg_lng + 360;
}
return $avg_lng;
}

PHP - Number of units between two numbers

I'm trying to find the number of units between 2 numbers that are under zero between 0 and a limit and over that limit. Here is my function. It works fine until I have to work with some huge numbers which takes a lot of time to process. I am trying to find a way to execute this code without using a loop.
public function getBetween($num1, $num2) {
$limit = 500000;
$array = array(0,0,0);
if ($num1 >= $num2) {
$low = $num2;
$high = $num1;
} else {
$low = $num1;
$high = $num2;
}
for($i=$low; $i < $high; $i++) {
if ($i < 0) {
$array[0]++;
} elseif ($i >= 0 && $i < $limit) {
$array[1]++;
} else {
$array[2]++;
}
}
return $array;
}
I have started to split my loop into elseif statements but this is getting messy really quick and I will also have to eventually be able to set more than one limit which will become impossible to use.
if ($low < 0 && $high < 0) {
} elseif ($low < 0 && $high >= 0 && $high < $limit) {
} elseif ($low < 0 && $high >= $limit) {
} elseif ($low >= 0 && $low < $limit && $high < 0) {
} elseif ($low >= 0 && $low < $limit && $high >= 0 && $high < $limit) {
} elseif ($low >= 0 && $low < $limit && $high >= $limit) {
} elseif ($low >= $limit && $high < 0) {
} elseif ($low >= $limit && $high >= 0 && $high < $limit) {
} elseif ($low >= $limit && $high >= $limit) {
}
I am trying to find a clean way to do it. Any ideas?
EDIT
Here is an example of the array I'm trying to get.
If my limit was 500, $num1 = -100 and $num2 = 700 i would get the array
$array[0] = 100
$array[1] = 500
$array[2] = 200
I didn't test it (didn't run a PHP script but I tried it "manually" with a few examples).
You still have loops, but only one iteration per limit (instead of one per unit).
// Example datas
$limits = array(0, 500, 800);
$low = -100;
$high = 1000;
$splittedResults = array();
// Get total of units
$totalUnits = abs($high - $low);
$totalCounted = 0;
foreach($limits as $limit) {
if ($low > $limit) {
// Nothing under the limit
$nbUnderLimit = 0;
} elseif($high < $limit) {
// Both values under the limit
$nbUnderLimit = $totalUnits;
} else {
// $low under the limit and $high over it
$nbUnderLimit = abs($limit - $low);
}
// Here we know how much units are under current limit in total.
// We want to know how much are between previous limit and current limit.
// Assuming that limits are sorted ascending, we have to remove already counted units.
$nbBetweenLimits = $nbUnderLimit - $totalCounted;
$splittedResults[] = $nbBetweenLimits;
$totalCounted += $nbBetweenLimits;
}
// Finally, number of units that are over the last limit (the rest)
$splittedResults[] = $totalUnits - $totalCounted;
You could create an array of the numbers with range() and use array_filter
$count = sizeof(array_filter (range(0,800), function($value){ return ($value > 500); }));
And one for < as well etc.
You only need to define range array once, separately.

Implementing python slice notation

I'm trying to reimplement python slice notation in another language (php) and looking for a snippet (in any language or pseudocode) that would mimic the python logic. That is, given a list and a triple (start, stop, step) or a part thereof, determine correct values or defaults for all parameters and return a slice as a new list.
I tried looking into the source. That code is far beyond my c skills, but I can't help but agree with the comment saying:
/* this is harder to get right than you might think */
Also, if something like this is already done, pointers will be greatly appreciated.
This is my test bench (make sure your code passes before posting):
#place your code below
code = """
def mySlice(L, start=None, stop=None, step=None):
or
<?php function mySlice($L, $start=NULL, $stop=NULL, $step=NULL) ...
or
function mySlice(L, start, stop, step) ...
"""
import itertools
L = [0,1,2,3,4,5,6,7,8,9]
if code.strip().startswith('<?php'):
mode = 'php'
if code.strip().startswith('def'):
mode = 'python'
if code.strip().startswith('function'):
mode = 'js'
if mode == 'php':
var, none = '$L', 'NULL'
print code, '\n'
print '$L=array(%s);' % ','.join(str(x) for x in L)
print "function _c($s,$a,$e){if($a!==$e)echo $s,' should be [',implode(',',$e),'] got [',implode(',',$a),']',PHP_EOL;}"
if mode == 'python':
var, none = 'L', 'None'
print code, '\n'
print 'L=%r' % L
print "def _c(s,a,e):\n\tif a!=e:\n\t\tprint s,'should be',e,'got',a"
if mode == 'js':
var, none = 'L', 'undefined'
print code, '\n'
print 'L=%r' % L
print "function _c(s,a,e){if(a.join()!==e.join())console.log(s+' should be ['+e.join()+'] got ['+a.join()+']');}"
print
n = len(L) + 3
start = range(-n, n) + [None, 100, -100]
stop = range(-n, n) + [None, 100, -100]
step = range(-n, n) + [100, -100]
for q in itertools.product(start, stop, step):
if not q[2]: q = q[:-1]
actual = 'mySlice(%s,%s)' % (var, ','.join(none if x is None else str(x) for x in q))
slice_ = 'L[%s]' % ':'.join('' if x is None else str(x) for x in q)
expect = eval(slice_)
if mode == 'php':
expect = 'array(%s)' % ','.join(str(x) for x in expect)
print "_c(%r,%s,%s);" % (slice_, actual, expect)
if mode == 'python':
print "_c(%r,%s,%s);" % (slice_, actual, expect)
if mode == 'js':
print "_c(%r,%s,%s);" % (slice_, actual, expect)
how to use it:
save into a file (test.py)
place your python, php or javascript code between """s
run python test.py | python or python test.py | php or python test.py | node
Here's a straight port of the C code:
def adjust_endpoint(length, endpoint, step):
if endpoint < 0:
endpoint += length
if endpoint < 0:
endpoint = -1 if step < 0 else 0
elif endpoint >= length:
endpoint = length - 1 if step < 0 else length
return endpoint
def adjust_slice(length, start, stop, step):
if step is None:
step = 1
elif step == 0:
raise ValueError("step cannot be 0")
if start is None:
start = length - 1 if step < 0 else 0
else:
start = adjust_endpoint(length, start, step)
if stop is None:
stop = -1 if step < 0 else length
else:
stop = adjust_endpoint(length, stop, step)
return start, stop, step
def slice_indices(length, start, stop, step):
start, stop, step = adjust_slice(length, start, stop, step)
i = start
while (i > stop) if step < 0 else (i < stop):
yield i
i += step
def mySlice(L, start=None, stop=None, step=None):
return [L[i] for i in slice_indices(len(L), start, stop, step)]
This is what I came up with (python)
def mySlice(L, start=None, stop=None, step=None):
answer = []
if not start:
start = 0
if start < 0:
start += len(L)
if not stop:
stop = len(L)
if stop < 0:
stop += len(L)
if not step:
step = 1
if stop == start or (stop<=start and step>0) or (stop>=start and step<0):
return []
i = start
while i != stop:
try:
answer.append(L[i])
i += step
except:
break
return answer
Seems to work - let me know what you think
Hope it helps
This is a solution I came up with in C# .NET, maybe not the prettiest, but it works.
private object[] Slice(object[] list, int start = 0, int stop = 0, int step = 0)
{
List<object> result = new List<object>();
if (step == 0) step = 1;
if (start < 0)
{
for (int i = list.Length + start; i < list.Length - (list.Length + start); i++)
{
result.Add(list[i]);
}
}
if (start >= 0 && stop == 0) stop = list.Length - (start >= 0 ? start : 0);
else if (start >= 0 && stop < 0) stop = list.Length + stop;
int loopStart = (start < 0 ? 0 : start);
int loopEnd = (start > 0 ? start + stop : stop);
if (step > 0)
{
for (int i = loopStart; i < loopEnd; i += step)
result.Add(list[i]);
}
else if (step < 0)
{
for (int i = loopEnd - 1; i >= loopStart; i += step)
result.Add(list[i]);
}
return result.ToArray();
}
I've written a PHP port based on the C code, optimized for step sizes -1 and 1:
function get_indices($length, $step, &$start, &$end, &$size)
{
if (is_null($start)) {
$start = $step < 0 ? $length - 1 : 0;
} else {
if ($start < 0) {
$start += $length;
if ($start < 0) {
$start = $step < 0 ? -1 : 0;
}
} elseif ($start >= $length) {
$start = $step < 0 ? $length - 1 : $length;
}
}
if (is_null($end)) {
$end = $step < 0 ? -1 : $length;
} else {
if ($end < 0) {
$end += $length;
if ($end < 0) {
$end = $step < 0 ? - 1 : 0;
}
} elseif ($end >= $length) {
$end = $step < 0 ? $length - 1 : $length;
}
}
if (($step < 0 && $end >= $start) || ($step > 0 && $start >= $end)) {
$size = 0;
} elseif ($step < 0) {
$size = ($end - $start + 1) / $step + 1;
} else {
$size = ($end - $start - 1) / $step + 1;
}
}
function mySlice($L, $start = NULL, $end = NULL, $step = 1)
{
if (!$step) {
return false; // could throw exception too
}
$length = count($L);
get_indices($length, $step, $start, $end, $size);
// optimize default step
if ($step == 1) {
// apply native array_slice()
return array_slice($L, $start, $size);
} elseif ($step == -1) {
// negative step needs an array reversal first
// with range translation
return array_slice(array_reverse($L), $length - $start - 1, $size);
} else {
// standard fallback
$r = array();
for ($i = $start; $step < 0 ? $i > $end : $i < $end; $i += $step) {
$r[] = $L[$i];
}
return $r;
}
}
This is based on #ecatmur's Python code ported again to PHP.
<?php
function adjust_endpoint($length, $endpoint, $step) {
if ($endpoint < 0) {
$endpoint += $length;
if ($endpoint < 0) {
$endpoint = $step < 0 ? -1 : 0;
}
}
elseif ($endpoint >= $length) {
$endpoint = $step < 0 ? $length - 1 : $length;
}
return $endpoint;
}
function mySlice($L, $start = null, $stop = null, $step = null) {
$sliced = array();
$length = count($L);
// adjust_slice()
if ($step === null) {
$step = 1;
}
elseif ($step == 0) {
throw new Exception('step cannot be 0');
}
if ($start === null) {
$start = $step < 0 ? $length - 1 : 0;
}
else {
$start = adjust_endpoint($length, $start, $step);
}
if ($stop === null) {
$stop = $step < 0 ? -1 : $length;
}
else {
$stop = adjust_endpoint($length, $stop, $step);
}
// slice_indices()
$i = $start;
$result = array();
while ($step < 0 ? ($i > $stop) : ($i < $stop)) {
$sliced []= $L[$i];
$i += $step;
}
return $sliced;
}
I can't say there's no bug in the codes, but it had past your test program :)
def mySlice(L, start=None, stop=None, step=None):
ret = []
le = len(L)
if step is None: step = 1
if step > 0: #this situation might be easier
if start is None:
start = 0
else:
if start < 0: start += le
if start < 0: start = 0
if start > le: start = le
if stop is None:
stop = le
else:
if stop < 0: stop += le
if stop < 0: stop = 0
if stop > le: stop = le
else:
if start is None:
start = le-1
else:
if start < 0: start += le
if start < 0: start = -1
if start >= le: start = le-1
if stop is None:
stop = -1 #stop is not 0 because we need L[0]
else:
if stop < 0: stop += le
if stop < 0: stop = -1
if stop >= le: stop = le
#(stop-start)*step>0 to make sure 2 things:
#1: step != 0
#2: iteration will end
while start != stop and (stop-start)*step > 0 and start >=0 and start < le:
ret.append( L[start] )
start += step
return ret

Part of pascal function

I'm trying to rewrite a pascal program to PHP, and don't understand what this part of pascal function do:
while (u[3] <> 1) and (u[3]<>0) and (v[3]<>0)do
begin
q:=u[3] div v[3];
for i:=1 to 3 do
begin
t:=u[i]-v[i]*q;
u[i]:=v[i];
v[i]:=t;
{writeln('u',i,'=',u[i],' v',i,'=',v[i]); }
end;
end;
if u[1]<0 then u[1]:=n+u[1];
rae:=u[1];
Please help to rewrite it to PHP.
Thanks.
A very literal translation of that code, should be this one:
while ($u[3] != 1 && $u[3] != 0 && $v[3] != 1 )
{
$q = floor($u[3] / $v[3]);
for ($i = 1; $i <= 3; $i++)
{
$t = $u[$i] - $v[$i] * $q;
$u[$i] = $v[$i];
$v[$i] = $t;
//writeln('u',i,'=',u[i],' v',i,'=',v[i]);
}
}
if ($u[1] < 0 )
$u1] = $n + $u[1];
$rae = $u[1];
Of course, u and v are arrays. Sorry for not giving any more info, but it's been like 10 years since Pascal and I last saw each other, but we had a profound romance for a long time, since I feel inlove for to hotties(C# and PHP) :)
while ($u[3] != 1) && ($u[3] != 0) && ($v[3] != 0) {
$q = floor($u[3] / $v[3]);
for ($i = 1; $i <= 3; $i++) {
$t = $u[$i] - $v[$i] * $q;
$u[$i] = $v[$i];
$v[$i] = $t;
echo "u$i={$u[$i]} v$i={$v[$i]}\n";
}
}
if ($u[1] < 0) {
$u[1] = $n + $u[1];
}
$rae = $u[1];
2 small corrections to David's code:
while ($u[3] != 1 && $u[3] != 0 && $v[3] != 1 )
should be
while ($u[3] != 1 && $u[3] != 0 && $v[3] != 0 )
and
for ($i = 1; $i < 3; $i++)
i never reaches the value of 3
for ($i = 1; $i <= 3; $i++)
May be the Writeln can be translated to
echo 'u'.$i.'='.$u[$i].' v'.$i.'='.$v[$i];
When you do the translation of arrays, take into account that arrays in php uses 0 as the first index.
$u= array( 3, 5, 22 )
echo u[1]; // prints 5
while($u[3] != 1 && $u[3] != 0 && $v[3] != 0)
{
$q = ($u[3] - ($u[3] % $v[3]) ) / $v[3]; //just the same as floor($u[3]/$v[3]), but i want to use % here :)
for ($i = 1; $i <= 3; $i++)
{
$t = $u[$i] - $v[$i]*$q;
$u[$i] = $v[$i];
$v[$i] = $t;
echo '<br />u'.$i.'='.$u[$i].' v'.$i.'='.$v[$i];
}
}
if ($u[1] < 0) $u[1] = $n + $u[1];
$rae = $u[1];
I dont know pascal But i have tried :)
while ($u[3]!=1 && $u[3]!=0 && $v[3]!=0) [
$q=floor($u[3]/ $v[3]);
for ($i=1;$i<3;$i++) {
$t=$u[$i]-$v[$i]*$q;
$u[$i]=$v[$i];
$v[$i]=$t;
echo "u".$i."=".$u[$i]."v".$i."=".$v[$i];
}
if ($u[1]<0) {
$u[1]=$n+$u[1];
}
$rae=$u[1];
In php variable Name Start With $
No Begin End used here in php only braces :)

PHP extract GPS EXIF data

I would like to extract the GPS EXIF tag from pictures using php.
I'm using the exif_read_data() that returns a array of all tags + data :
GPS.GPSLatitudeRef: N
GPS.GPSLatitude:Array ( [0] => 46/1 [1] => 5403/100 [2] => 0/1 )
GPS.GPSLongitudeRef: E
GPS.GPSLongitude:Array ( [0] => 7/1 [1] => 880/100 [2] => 0/1 )
GPS.GPSAltitudeRef:
GPS.GPSAltitude: 634/1
I don't know how to interpret 46/1 5403/100 and 0/1 ? 46 might be 46° but what about the rest especially 0/1 ?
angle/1 5403/100 0/1
What is this structure about ?
How to convert them to "standard" ones (like 46°56′48″N 7°26′39″E from wikipedia) ? I would like to pass thoses coordinates to the google maps api to display the pictures positions on a map !
This is my modified version. The other ones didn't work for me. It will give you the decimal versions of the GPS coordinates.
The code to process the EXIF data:
$exif = exif_read_data($filename);
$lon = getGps($exif["GPSLongitude"], $exif['GPSLongitudeRef']);
$lat = getGps($exif["GPSLatitude"], $exif['GPSLatitudeRef']);
var_dump($lat, $lon);
Prints out in this format:
float(-33.8751666667)
float(151.207166667)
Here are the functions:
function getGps($exifCoord, $hemi) {
$degrees = count($exifCoord) > 0 ? gps2Num($exifCoord[0]) : 0;
$minutes = count($exifCoord) > 1 ? gps2Num($exifCoord[1]) : 0;
$seconds = count($exifCoord) > 2 ? gps2Num($exifCoord[2]) : 0;
$flip = ($hemi == 'W' or $hemi == 'S') ? -1 : 1;
return $flip * ($degrees + $minutes / 60 + $seconds / 3600);
}
function gps2Num($coordPart) {
$parts = explode('/', $coordPart);
if (count($parts) <= 0)
return 0;
if (count($parts) == 1)
return $parts[0];
return floatval($parts[0]) / floatval($parts[1]);
}
This is a refactored version of Gerald Kaszuba's code (currently the most widely accepted answer). The result should be identical, but I've made several micro-optimizations and combined the two separate functions into one. In my benchmark testing, this version shaved about 5 microseconds off the runtime, which is probably negligible for most applications, but might be useful for applications which involve a large number of repeated calculations.
$exif = exif_read_data($filename);
$latitude = gps($exif["GPSLatitude"], $exif['GPSLatitudeRef']);
$longitude = gps($exif["GPSLongitude"], $exif['GPSLongitudeRef']);
function gps($coordinate, $hemisphere) {
if (is_string($coordinate)) {
$coordinate = array_map("trim", explode(",", $coordinate));
}
for ($i = 0; $i < 3; $i++) {
$part = explode('/', $coordinate[$i]);
if (count($part) == 1) {
$coordinate[$i] = $part[0];
} else if (count($part) == 2) {
$coordinate[$i] = floatval($part[0])/floatval($part[1]);
} else {
$coordinate[$i] = 0;
}
}
list($degrees, $minutes, $seconds) = $coordinate;
$sign = ($hemisphere == 'W' || $hemisphere == 'S') ? -1 : 1;
return $sign * ($degrees + $minutes/60 + $seconds/3600);
}
According to http://en.wikipedia.org/wiki/Geotagging, ( [0] => 46/1 [1] => 5403/100 [2] => 0/1 ) should mean 46/1 degrees, 5403/100 minutes, 0/1 seconds, i.e. 46°54.03′0″N. Normalizing the seconds gives 46°54′1.8″N.
This code below should work, as long as you don't get negative coordinates (given that you get N/S and E/W as a separate coordinate, you shouldn't ever have negative coordinates). Let me know if there is a bug (I don't have a PHP environment handy at the moment).
//Pass in GPS.GPSLatitude or GPS.GPSLongitude or something in that format
function getGps($exifCoord)
{
$degrees = count($exifCoord) > 0 ? gps2Num($exifCoord[0]) : 0;
$minutes = count($exifCoord) > 1 ? gps2Num($exifCoord[1]) : 0;
$seconds = count($exifCoord) > 2 ? gps2Num($exifCoord[2]) : 0;
//normalize
$minutes += 60 * ($degrees - floor($degrees));
$degrees = floor($degrees);
$seconds += 60 * ($minutes - floor($minutes));
$minutes = floor($minutes);
//extra normalization, probably not necessary unless you get weird data
if($seconds >= 60)
{
$minutes += floor($seconds/60.0);
$seconds -= 60*floor($seconds/60.0);
}
if($minutes >= 60)
{
$degrees += floor($minutes/60.0);
$minutes -= 60*floor($minutes/60.0);
}
return array('degrees' => $degrees, 'minutes' => $minutes, 'seconds' => $seconds);
}
function gps2Num($coordPart)
{
$parts = explode('/', $coordPart);
if(count($parts) <= 0)// jic
return 0;
if(count($parts) == 1)
return $parts[0];
return floatval($parts[0]) / floatval($parts[1]);
}
I know this question has been asked a long time ago, but I came across it while searching in google and the solutions proposed here did not worked for me. So, after further searching, here is what worked for me.
I'm putting it here so that anybody who comes here through some googling, can find different approaches to solve the same problem:
function triphoto_getGPS($fileName, $assoc = false)
{
//get the EXIF
$exif = exif_read_data($fileName);
//get the Hemisphere multiplier
$LatM = 1; $LongM = 1;
if($exif["GPSLatitudeRef"] == 'S')
{
$LatM = -1;
}
if($exif["GPSLongitudeRef"] == 'W')
{
$LongM = -1;
}
//get the GPS data
$gps['LatDegree']=$exif["GPSLatitude"][0];
$gps['LatMinute']=$exif["GPSLatitude"][1];
$gps['LatgSeconds']=$exif["GPSLatitude"][2];
$gps['LongDegree']=$exif["GPSLongitude"][0];
$gps['LongMinute']=$exif["GPSLongitude"][1];
$gps['LongSeconds']=$exif["GPSLongitude"][2];
//convert strings to numbers
foreach($gps as $key => $value)
{
$pos = strpos($value, '/');
if($pos !== false)
{
$temp = explode('/',$value);
$gps[$key] = $temp[0] / $temp[1];
}
}
//calculate the decimal degree
$result['latitude'] = $LatM * ($gps['LatDegree'] + ($gps['LatMinute'] / 60) + ($gps['LatgSeconds'] / 3600));
$result['longitude'] = $LongM * ($gps['LongDegree'] + ($gps['LongMinute'] / 60) + ($gps['LongSeconds'] / 3600));
if($assoc)
{
return $result;
}
return json_encode($result);
}
This is an old question but felt it could use a more eloquent solution (OOP approach and lambda to process the fractional parts)
/**
* Example coordinate values
*
* Latitude - 49/1, 4/1, 2881/100, N
* Longitude - 121/1, 58/1, 4768/100, W
*/
protected function _toDecimal($deg, $min, $sec, $ref) {
$float = function($v) {
return (count($v = explode('/', $v)) > 1) ? $v[0] / $v[1] : $v[0];
};
$d = $float($deg) + (($float($min) / 60) + ($float($sec) / 3600));
return ($ref == 'S' || $ref == 'W') ? $d *= -1 : $d;
}
public function getCoordinates() {
$exif = #exif_read_data('image_with_exif_data.jpeg');
$coord = (isset($exif['GPSLatitude'], $exif['GPSLongitude'])) ? implode(',', array(
'latitude' => sprintf('%.6f', $this->_toDecimal($exif['GPSLatitude'][0], $exif['GPSLatitude'][1], $exif['GPSLatitude'][2], $exif['GPSLatitudeRef'])),
'longitude' => sprintf('%.6f', $this->_toDecimal($exif['GPSLongitude'][0], $exif['GPSLongitude'][1], $exif['GPSLongitude'][2], $exif['GPSLongitudeRef']))
)) : null;
}
The code I've used in the past is something like (in reality, it also checks that the data is vaguely valid):
// Latitude
$northing = -1;
if( $gpsblock['GPSLatitudeRef'] && 'N' == $gpsblock['GPSLatitudeRef'] )
{
$northing = 1;
}
$northing *= defraction( $gpsblock['GPSLatitude'][0] ) + ( defraction($gpsblock['GPSLatitude'][1] ) / 60 ) + ( defraction( $gpsblock['GPSLatitude'][2] ) / 3600 );
// Longitude
$easting = -1;
if( $gpsblock['GPSLongitudeRef'] && 'E' == $gpsblock['GPSLongitudeRef'] )
{
$easting = 1;
}
$easting *= defraction( $gpsblock['GPSLongitude'][0] ) + ( defraction( $gpsblock['GPSLongitude'][1] ) / 60 ) + ( defraction( $gpsblock['GPSLongitude'][2] ) / 3600 );
Where you also have:
function defraction( $fraction )
{
list( $nominator, $denominator ) = explode( "/", $fraction );
if( $denominator )
{
return ( $nominator / $denominator );
}
else
{
return $fraction;
}
}
To get the altitude value, you can use the following 3 lines:
$data = exif_read_data($path_to_your_photo, 0, TRUE);
$alt = explode('/', $data["GPS"]["GPSAltitude"]);
$altitude = (isset($alt[1])) ? ($alt[0] / $alt[1]) : $alt[0];
In case you need a function to read Coordinates from Imagick Exif here we go, I hope it saves you time. Tested under PHP 7.
function create_gps_imagick($coordinate, $hemi) {
$exifCoord = explode(', ', $coordinate);
$degrees = count($exifCoord) > 0 ? gps2Num($exifCoord[0]) : 0;
$minutes = count($exifCoord) > 1 ? gps2Num($exifCoord[1]) : 0;
$seconds = count($exifCoord) > 2 ? gps2Num($exifCoord[2]) : 0;
$flip = ($hemi == 'W' or $hemi == 'S') ? -1 : 1;
return $flip * ($degrees + $minutes / 60 + $seconds / 3600);
}
function gps2Num($coordPart) {
$parts = explode('/', $coordPart);
if (count($parts) <= 0)
return 0;
if (count($parts) == 1)
return $parts[0];
return floatval($parts[0]) / floatval($parts[1]);
}
I'm using the modified version from Gerald Kaszuba but it's not accurate.
so i change the formula a bit.
from:
return $flip * ($degrees + $minutes / 60);
changed to:
return floatval($flip * ($degrees +($minutes/60)+($seconds/3600)));
It works for me.
This is a javascript port of the PHP-code posted #Gerald above. This way you can figure out the location of an image without ever uploading the image, in conjunction with libraries like dropzone.js and Javascript-Load-Image
define(function(){
function parseExif(map) {
var gps = {
lng : getGps(map.get('GPSLongitude'), data.get('GPSLongitudeRef')),
lat : getGps(map.get('GPSLatitude'), data.get('GPSLatitudeRef'))
}
return gps;
}
function getGps(exifCoord, hemi) {
var degrees = exifCoord.length > 0 ? parseFloat(gps2Num(exifCoord[0])) : 0,
minutes = exifCoord.length > 1 ? parseFloat(gps2Num(exifCoord[1])) : 0,
seconds = exifCoord.length > 2 ? parseFloat(gps2Num(exifCoord[2])) : 0,
flip = (/w|s/i.test(hemi)) ? -1 : 1;
return flip * (degrees + (minutes / 60) + (seconds / 3600));
}
function gps2Num(coordPart) {
var parts = (""+coordPart).split('/');
if (parts.length <= 0) {
return 0;
}
if (parts.length === 1) {
return parts[0];
}
return parts[0] / parts[1];
}
return {
parseExif: parseExif
};
});
short story.
First part N
Leave the grade
multiply the minutes with 60
devide the seconds with 100.
count the grades,minuts and seconds with eachother.
Second part E
Leave the grade
multiply the minutes with 60
devide the seconds with ...1000
cöunt the grades, minutes and seconds with each other
i have seen nobody mentioned this: https://pypi.python.org/pypi/LatLon/1.0.2
from fractions import Fraction
from LatLon import LatLon, Longitude, Latitude
latSigned = GPS.GPSLatitudeRef == "N" ? 1 : -1
longSigned = GPS.GPSLongitudeRef == "E" ? 1 : -1
latitudeObj = Latitude(
degree = float(Fraction(GPS.GPSLatitude[0]))*latSigned ,
minute = float(Fraction(GPS.GPSLatitude[0]))*latSigned ,
second = float(Fraction(GPS.GPSLatitude[0])*latSigned)
longitudeObj = Latitude(
degree = float(Fraction(GPS.GPSLongitude[0]))*longSigned ,
minute = float(Fraction(GPS.GPSLongitude[0]))*longSigned ,
second = float(Fraction(GPS.GPSLongitude[0])*longSigned )
Coordonates = LatLon(latitudeObj, longitudeObj )
now using the Coordonates objecct you can do what you want:
Example:
(like 46°56′48″N 7°26′39″E from wikipedia)
print Coordonates.to_string('d%°%m%′%S%″%H')
You than have to convert from ascii, and you are done:
('5\xc2\xb052\xe2\x80\xb259.88\xe2\x80\xb3N', '162\xc2\xb04\xe2\x80\xb259.88\xe2\x80\xb3W')
and than printing example:
print "Latitude:" + Latitude.to_string('d%°%m%′%S%″%H')[0].decode('utf8')
>> Latitude: 5°52′59.88″N

Categories