I have a database of postcodes with Eastings/ Northings, is there a php script that can convert these values so I can use them on google maps?
Can I loop through the database and change each value?
Many thanks
Here is an API I wrote to do exactly this:
https://www.getthedata.com/bng2latlong
Syntax:
https://api.getthedata.com/bng2latlong/[easting]/[northing]
Example:
https://api.getthedata.com/bng2latlong/529090/179645
Some very basic PHP code might look like this:
$easting = 529090;
$northing = 179645;
$json = file_get_contents("https://api.getthedata.com/bng2latlong/$easting/$northing");
$arr = json_decode($json, true);
$latitude = $arr['latitude'];
$longitude = $arr['longitude'];
Related
My application collects geolocation point from the user every certain amount of time, I am trying to use these points in order to calculate the distance from the first point through all of the points.
please note that when the user moves in a straight line, the geolocation points do not form a straight line, because the points I collect have a margin of error due to inaccuracy, thus I can't use something like Haversine formula because it will give incorrect value (longer distance than real distance)
and I can't use Google Maps Distance API because it calculates the distance between 2 points only, and it will be so expensive to call it 200 times to calculate distance through all points.
and I want to calculate this value on the server-side because of some security rules I have. so using the google maps SDK in the front end to calculate it is not an option either.
Any idea ...
One option would be to simplify the line, then run the data through the Google Roads API (assuming the travel is on roads), then measure the length of the resulting line (following the roads).
for anyone facing the same problem,I have followed this link
https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/roads/snap
here is my code in PHP
// snap the collected points from user to the nearest road using google API
$fields = array(
'path' => '60.170880,24.942795|60.170879,24.942796|60.170877,24.942796|60.170902,24.942654',
'key' => '<YOUR_KEY_HERE>'
);
$url = "https://roads.googleapis.com/v1/snapToRoads?" . http_build_query($fields, '', '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$response = json_decode($response);
$totalDistance = 0;
$previousPoint = null;
foreach ($response->snappedPoints as $pointOnRoad) {
if(!$previousPoint){
$previousPoint = $pointOnRoad;
continue;
}
$totalDistance += getDistance($pointOnRoad->location->latitude, $pointOnRoad->location->longitude,
$previousPoint->location->latitude, $previousPoint->location->longitude);
}
echo $totalDistance;
// calculate distance between 2 geo points
function getDistance($latitude1, $longitude1, $latitude2, $longitude2) {
$earth_radius = 6371;
$dLat = deg2rad($latitude2 - $latitude1);
$dLon = deg2rad($longitude2 - $longitude1);
$a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * sin($dLon/2) * sin($dLon/2);
$c = 2 * asin(sqrt($a));
$d = $earth_radius * $c;
return $d;
}
We are having similar kind of requirement. There are 2 paths and we need to make sure that each node in 1st path (except start and end) are at least 100 KM away from each other of 2nd path.
Can you please share code snippet or logic behind this.
Using Haversine formula in loop will impact performance. So, please suggest some better solution.
sorry for disturbing...I got json format to build column highcharts that will accept data from user multiple selected via checkbox and retrieve the data result from database based on what they check at checkbox and display by highcharts in form of column chart..
The problem is,I think my json format for column highcharts is not correct can anyone see my code and tell me what wrong with this....below this is the json output and the code..:- Thank u very much for your time..
Let say if I checked 2 checkbox from the checkboxes list (BAT123 & BIO22), this json will displayed like this:
[{"name":"Subject","data":["BAT123"]},{"name":"Result","data":[3.03]}]
[{"name":"Subject","data":["BAT123","BIO222"]},{"name":"Result","data":[3.03,1.05]}]
I know that json format is wrong, I tried to fixed it but still failed..I am a newbie..hope u can try to fix my code below.
Here is the json code:
<?php
if(isset($_GET['iddoc'])) //iddoc is the value from selected checkbox
{
$category = array();
$category['name'] = 'Subject';
$series1 = array();
$series1['name'] = 'Result';
foreach ($_GET['iddoc'] as $iddoc)
{
$query="select * from compareresult where iddocument=$iddoc";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while($r = mysql_fetch_assoc($sql_query))
{
$category['data'][] = $r['subject'];
$series1['data'][] = $r['result'];
}
$result = array();
array_push($result,$category);
array_push($result,$series1);
$jsonTable = json_encode($result, JSON_NUMERIC_CHECK);
echo $jsonTable;
}
}
?>
With the help of #Dr.Molle answer I learnt to do free hand drawing in Google maps. Now I'm trying to get the polygon drawn within a polygon something like in the below SS
I want to get the polygons marked in yellow and green within the black.
I'm not sure whether this is possible or not. Please shed some light on this issue.
Updates: on further research I learnt about a method called containsLocation(point, polygons) which is used to find whether the given lat/lng point is within the polygon or not.
But sadly there is no default method to check polygons within polygon provided by Google maps :(
You can check if a polygon is within another polygon by looping through each point of the inner polygon and testing if it is contained within the outer polygon using containsLocation().
var isPolygonInsidePolygon = function (innerPolygon, outerPolygon) {
var pointsInside = 0;
var pointsOutside = 0;
innerPolygon.getPath().getArray().map(function (x) {
(google.maps.geometry.poly.containsLocation(x, outerPolygon)) ? pointsInside++ : pointsOutside++;
});
return (pointsOutside > 0) ? false : true;
};
The JavaScript map() function may not work in older browsers, IE8 or lower.
This is a GIS question. Google Maps API isn't really a full-blown GIS. If you want an open-source solution, I suggest loading your yellow and green polygons into a PostGIS database. Then you can query the database.
As an example, you can encode the drawn polygon as a POLYGON object which has the format:
POLYGON((lon lat, lon lat, lon lat, lon lat, ... lon lat))
And then send that to a PHP file from javascript like (you'll wrap this in a $.get() command or similar and return json results:
getParcels.php?bounds=POLYGON((lon lat, lon lat, lon lat, lon lat, ... lon lat))
In the PHP file, query the PostGIS database and return the ids of the yellow and green polygons:
<?php
$pgcon = pg_connect ("dbname=gis user=gisuser connect_timeout=5") or die ( 'Can not connect to PG server' );
if (!$pgcon) {
echo "No connection to GIS database.\n";
}
$bounds = urldecode($_GET["bounds"];
$ewkt = 'SRID=4326;' . $bounds);
$json = ''; // this will contain your output
// Here I am returning the polygon geometry and the parcelID...
$query .= <<<EOD
SELECT
ST_AsGeoJSON(the_geom) as geom,
parid
FROM
parcels
WHERE
ST_Intersects(the_geom, ST_GeomFromEWKT( $1 ));
EOD;
$result = pg_query_params($pgcon, $query, array($ewkt));
if($result) {
$json = '{"type":"FeatureCollection", "features":[';
while($row = pg_fetch_assoc($result)) {
$json .= '{"geometry":' . $row['geom'] . ',';
$json .= '"type":"Feature","properties":{"parid":"' . $row['parid'] . '"}},';
}
$json = substr($json, 0,-1).']}';
}
echo $json;
?>
This will return the parcels that intersect your polygon using the ST_Intersects command in PostGIS.
An alternative implementation working from #chris-smith solution that might be faster, since it doesn't keep looping if it finds an outside point:
function isPolygonInsidePolygon( innerPolygon, outerPolygon ) {
var points = innerPolygon.getPath().getArray();
for( var i = 0; i < points.length; i++ ){
if( ! google.maps.geometry.poly.containsLocation( points[i], outerPolygon) ){
return false;
}
}
return true;
}
I noticed that my google geocoding has been deprecated and has brought my website to its knees. I could really use someone's help figuring out this last piece of the puzzle. I had the old code that produced a single output "$Coords" that the rest of my website is dependent upon. Could you please help me figure out how to make the new api have the same output. Here was my old code:
$address = str_replace('#', '', $address);
$address = str_replace(' ', '+', $address);
$XMLUrl = 'http://maps.google.com/maps/geo?q='.$address.'&key='.$api.'&sensor=false&output=xml&oe=utf8';
$XMLUrl = 'http://maps.googleapis.com/maps/api/geocode/xml?address='.$address.'&sensor=false';
$XMLContents = file_get_contents($XMLUrl);
$XML = new SimpleXMLElement($XMLContents);
$Coords = explode(',',$XML->Response->Placemark->Point->coordinates);
return $Coords;
Here is what I have for the new code. I just can't figure out how to have it output as $Coords:
$address = str_replace('#', '', $address);
$address = str_replace(" ", "+", $address);
$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=$region");
$json = json_decode($json);
$lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
$long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
The rest of the website depends upon the geocoding stored as $Coords and not as $lat or $long. I really really appreciate any help I can get.
I needed to save it as an array. Duh
$Coords = $long.', '.$lat;
$Coords = explode(',',$Coords);
I want use mysql_data_seek with PDO from google search I found that it should looks like this:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
however it's not work, what I do wrong?
this is my code:
$query = "SELECT name,age FROM users";
$q = $db->prepare($query);
$q->execute();
$q->setFetchMode(PDO::FETCH_ASSOC);
$arrayData = $q->fetchAll();
foreach ($arrayData as $row){
echo $row['name'] ." ";
echo $row['age'] ."<br>";
}
$result = $q->fetch(PDO::FETCH_OBJ,PDO::FETCH_ORI_ABS,4);
var_dump($result);
I just want get the 5th row in object form from the last run query. I don't want run this query again (as some guys told me) I just want the results from sql buffer.
the var_dump result is: bool(false)
any ideas?
EDIT:
thanks for your answers and sorry but maybe I don't explain myself as well. I like the trick with JSON but the point is that the 5th row is example. I just want use the result of the query from the buffer with PDO exactly as I did it with mysql_data_seek in regular mysql (change the cursor). is it possible? I like all the tricks but that not what I look for.
the PDO 'cursor' default is PDO::CURSOR_FWDONLY that means that cursor can't back to zero like it happens with mysql_data_seek to allow cursor back to zero it necessary define use 'scrollable cursor'
example:
$db->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
before use it like this:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
$result = $arrayData[4];
is all you need.
If you want the 5th row result you can do like this:
$result = json_decode(json_encode($arrayData[4]), FALSE);
var_dump($result);
or something like this:
$object = new stdClass();
foreach ($array as $key => $value)
{
$object->$key = $value;
}
Just curious! why do you need the object form?
EDIT (this will give the object form of the 5th row):
$index = 0;
$fifthRow = new stdClass();
while($row = $q->fetch())
{
if($index++==4)
$fifthRow = json_decode(json_encode($row), FALSE);
}
You could do it like this:
$c = 1;
$saved=null;
while($row = $q->fetch()){
if($c==4){
$saved = clone $row;
};
$c++;
somethingelse;
}
$saved will then contain the 4th element as an object with almost no extra overhead calculations.