I'm trying to create an event site. Users at the moment can search for events within a specified radius of their chosen search location (using Google Geocode).
I have a custom DB Query, which works fine, except I want the distance of the event to display on the front end of the site also, so users know how far away each event is from them.
Here's the custom query function I have at the moment:
function location_posts_where( $where ) {
// if user has input a location
if( isset($_POST['where']) != '' ) :
// check the geo locaton of user
$geoURL = "http://freegeoip.net/json/". $_SERVER['REMOTE_ADDR'] .'';
$geo = json_decode(file_get_contents($geoURL), true);
// Geocode input value + users country code
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($_POST['where'])."+".$geo[country_code]."&sensor=false";
$location = json_decode(file_get_contents($url), true);
// store lat and long of searched location
$Slat = $location[results][0][geometry][location][lat];
$Slng = $location[results][0][geometry][location][lng];
// if use hasn't unput a location
else :
// get location of user
$url = "http://freegeoip.net/json/". $_SERVER['REMOTE_ADDR'] .'';
$geo = json_decode(file_get_contents($url), true);
// store lat and long of user location
$Slat = $geo[latitude];
$Slng = $geo[longitude];
endif;
// Specify the co-ordinates that will form
// the centre of our search
$lat = $Slat;
$lng = $Slng;
$radius = $_POST['distance']; // (in miles)
// Append our radius calculation to the WHERE
$where .= " AND wp_posts.ID IN (SELECT post_id FROM lat_lng_post WHERE
( 3959 * acos( cos( radians(" . $lat . ") )
* cos( radians( lat ) )
* cos( radians( lng )
- radians(" . $lng . ") )
+ sin( radians(" . $lat . ") )
* sin( radians( lat ) ) ) ) <= " . $radius . ")";
// Return the updated WHERE part of the query
return $where;
}
This code works fine, however, I've used the wp_geo_posts plugin before, and that lets you output onto the screen the distance each event is from the users location using <?php echo $post->distance; ?>
With this code, there is no 'distance' output to the $post variable. Is there a way of getting this to output to $post so it can be displayed on the front end?
Related
I want to show Merchant details approximately 60 miles distance through the User current location,
Below My coding,
$criteria = new CDbCriteria;
$criteria->select = '*, ( 3959 * acos( cos( radians(' . $currentlatval . ') ) * cos( radians( lat ) ) '
. '* cos( radians( lng ) - radians(' . $currentlngval . ') ) '
. '+ sin( radians(' . $currentlatval . ') ) * sin( radians( lat ) ) ) ) AS distance ';
$criteria->having = ("distance < 60");
$criteria->group = 'uid';
$results2 = Merchant::model()->findAll($criteria);
Its Working Properly,In the above code it check only attribute lat and lng,But I want to also check attribute city_lat and city_lng in above code How to write to check both attribute?
I am making a site in which I have to show all stores on a list sorted in a way that the nearer stores, to the users current location, come first and far ones come later.
I need a MySQL query that selects all stores from database ORDER BY users current position.
I have searched on Google a lot but could not find any query that matches my case.
You can try this:
SELECT temp1.* FROM (SELECT s.shop_id, s.shop_name, s.address, 3959 * ACOS( COS( RADIANS( 40.7127 ) ) * COS( RADIANS( s.latitude ) ) * COS( RADIANS( s.longitude ) - RADIANS( 74.0059 ) ) + SIN( RADIANS( 40.7127 ) ) * SIN( RADIANS( s.latitude ) ) ) AS distance FROM shop s) as temp1 WHERE temp1.distance <= 20 ORDER BY temp1.distance
it will give shop listing within 20 miles.
40.7127 is latitude and 74.0059 is longitude
I think that you'll find that you'll just need to get all the stores from your database (or potentially filtered by something like state to make for a smaller data-set) and then let your application handle ordering them by distance.
You should go with the ip address of the stores with the ip helper to find (host,country,town,region) of the store and map them so that any can find nearby stores. you can find these from ip
<?php
require_once("userip/ip.codehelper.io.php");
require_once("userip/php_fast_cache.php");
$_ip = new ip_codehelper();
$real_client_ip_address = $_ip->getRealIP();
$visitor_location = $_ip->getLocation($real_client_ip_address);
$guest_ip = $visitor_location['IP'];
$guest_country = $visitor_location['CountryName'];
$guest_city = $visitor_location['CityName'];
$guest_state = $visitor_location['RegionName'];
echo "IP Address: ". $guest_ip. "<br/>";
echo "Country: ". $guest_country. "<br/>";
echo "State: ". $guest_state. "<br/>";
echo "City: ". $guest_city. "<br/>";
?>
You can also find
$ip = $visitor_location['IP'];
$Continent_Code = $$$visitor_location['ContinentCode'];
$Continent_Name = $visitor_location['ContinentName'];
$Country_Code2 = $visitor_location['CountryCode2'];
$Country_Code3 = $visitor_location['CountryCode3'];
$Country = $visitor_location['Country'];
$Country_Name = $visitor_location['CountryName'];
$State_Name = $visitor_location['RegionName'];
$City_Name = $visitor_location['CityName'];
$City_Latitude = $visitor_location['CityLatitude'];
$City_Longitude = $visitor_location['CityLongitude'];
$Country_Latitude = $visitor_location['CountryLatitude'];
$Country_Longitude = $visitor_location['CountryLongitude'];
$Country_Longitude = $visitor_location['CountryLongitude'];
$LocalTimeZone = $visitor_location['LocalTimeZone'];
$Calling_Code = $visitor_location['CallingCode'];
$Population = $visitor_location['Population'];
$Area_SqKm = $visitor_location['AreaSqKm'];
$Capital = $visitor_location['Capital'];
$Electrical = $visitor_location['Electrical'];
$Languages = $visitor_location['Languages'];
$Currency = $visitor_location['Currency'];
$Flag = $visitor_location['Currency'];
I am running the following query in a PHP script:
$radius_query = "SELECT zip, ( 3959 * acos( cos( radians(" . $latitude .") ) * cos( radians( lat ) ) * cos( radians( lng ) - radians( " . $longitude . ") ) + sin( radians(" . $latitude .") ) * sin( radians( lat ) ) ) ) AS distance
FROM ZIP HAVING distance < ". $radius;
$radius_result = $db_zipcode->query($radius_query);
if (!$radius_result){
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = $radius_result->fetch(PDO::FETCH_ASSOC);
While($row = $radius_result->fetch(PDO::FETCH_ASSOC))
{
$zip[] = $row['zip'];
}
foreach ($zip as $zip_display){
echo $zip_display . ", " . '';
}
The query itself works with one minor error - it does not return the first row of data. It should return a list of zip codes similar to this:
40324, 40339, 40340, 40347, 40356...
This is the result I get when I run the same query in phpMyAdmin.
However when I run the query above in a PHP script, the result set starts with 40339, and then includes all the remaining zip codes. Its not a mileage issue (i.e. the missing zip is well within the radius - as it shows up when I run the query in phpMyAdmin).
What am I doing wrong in the PHP query to miss that first row of data? Its not just a display problem because when I insert the query results in a DB, it is also missing the first row.
Thanks!
Problem is in the first fetch, they take your first row...
Run this without
$row = $radius_result->fetch(PDO::FETCH_ASSOC);
I had the same problem about a day ago.
There's no need to do an implicit loop in the PHP, try
$zip = $radius_result->fetchAll(PDO::FETCH_ASSOC);
I have a SELECT SQL statement that returns a Latitude, Longitude and Distance as result (using the Haversine formula). Now I need to store these values as variables within the PHP script as I need to do further processing on the results. Can anyone tell me how I can do this?
Here is my SQL Statement
UPDATED
$query = $db->prepare("SELECT `Latitude`, `Longitude`, (6378160 * acos( cos( radians(:latitude) ) * cos( radians( Latitude ) ) * cos( radians( Longitude ) - radians(:longitude) ) + sin( radians(:latitude) ) * sin( radians( Latitude ) ) ) ) AS distance FROM `mytable` HAVING distance < :radius ORDER BY distance;");
// Assign parameters
$query->bindParam(':latitude',$newLatitude);
$query->bindParam(':longitude',$newLongitude);
$query->bindParam(':radius',$radius);
//Execute query
$query->execute();
$q = $db->query($query);
$q->setFetchMode(PDO::FETCH_ASSOC);
// fetch
while($r = $q->fetch()){
$eLatitude = $r->Latitude;
$eLongitude = $r>Longitude;
$distance = $r->Distance;
}
I updated my php code above. Is this code's syntax correct? Or the way I'm doing it is all wrong?
PDO::FETCH_ASSOC: returns an array indexed by column name Manual
while($r = $q->fetch()){
echo $r['Latitude']. "\n"; //Or do what ever instead of echo
echo $r['Longitude']. "\n";
echo $r['Distance']. "\n";
}
ie XML
while($r = $q->fetch()){
$node = $dom->createElement("marker");
$newnode->setAttribute("lat", $r['Latitude']);
$newnode->setAttribute("lng", $r['Longitude']);
$newnode->setAttribute("distance", $r['Distance']);
}
ie JSON
while($r = $q->fetch()){
data[] = $r;
}
you can use
$queryresult = mysql_query("SELECT `Latitude`, `Longitude`, (6378160 * acos( cos( radians(:latitude) ) * cos( radians( Latitude ) ) * cos( radians( Longitude ) - radians(:longitude) ) + sin( radians(:latitude) ) * sin( radians( Latitude ) ) ) ) AS distance FROM `mytable` HAVING distance < :radius ORDER BY distance;");
if (!$queryresult) {
echo 'Error ' . mysql_error();
exit;
}
$resultrow = mysql_fetch_row($queryresult);
echo $resultrow[0]; // this will be latitude
echo $resultrow[1]; // this will be longitude
I'm following this tutorial when I found out, I can't view the expected output because I can't view my data in xml format. I have change the configuration data a little bit, didn't know if it was the cause of malfunction?
<?php
// Get parameters from URL
$center_lat = $_GET["lat"];
$center_lng = $_GET["lng"];
$radius = $_GET["radius"];
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a mySQL server
$connection=mysql_connect (localhost, 'root', '12345678');
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Set the active mySQL database
$db_selected = mysql_select_db('demo', $connection);
if (!$db_selected) {
die ("Can\'t use db : " . mysql_error());
}
// Search the rows in the markers table
$query = sprintf("SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
mysql_real_escape_string($center_lat),
mysql_real_escape_string($center_lng),
mysql_real_escape_string($center_lat),
mysql_real_escape_string($radius));
$result = mysql_query($query);
if (!$result) {
die("Invalid query: " . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name", $row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("distance", $row['distance']);
}
echo $dom->saveXML();
?>
I am expecting to get a similar result like this http://gmaps-samples.googlecode.com/svn/trunk/articles-phpsqlsearch/phpsqlsearch_expectedoutput.xml but nothing appears. It seems like it doesn't have any data but I have already imported the data in my mysql.
First pass for issues:
<?php
// Get parameters from URL
$center_lat = ( isset( $_GET["lat"] ) ? $_GET["lat"] : 0 ); # You could replace these "0"s with the
$center_lng = ( isset( $_GET["lng"] ) ? $_GET["lng"] : 0 ); # Lat/Lng of a default location.
$radius = ( isset( $_GET["radius"] ) ? $_GET["radius"] : 10 ); # Again, default radius.
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a mySQL server
if( !( $connection = mysql_connect( 'localhost' , 'root' , '12345678' ) ) ) # The SQL Server address must be a string or IP address
die( "MySQL Error - Failed to connect to Server : " . mysql_error() );
// Set the active mySQL database
if( !mysql_select_db( 'demo' , $connection ) );
die( "MySQL Error - Failed to connect to Database : " . mysql_error() );
// Search the rows in the markers table
$query = sprintf( "SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
mysql_real_escape_string( $center_lat ),
mysql_real_escape_string( $center_lng ),
mysql_real_escape_string( $center_lat ),
mysql_real_escape_string( $radius ) );
$result = mysql_query( $query );
if( !$result )
die( "MySQL Error - Invalid query: " . mysql_error() . ' "'.$query.'"' ); # During debugging, echo the SQL Statement on Error
if( !headers_sent() )
header( "Content-type: text/xml" );
// Iterate through the rows, adding XML nodes for each
if( mysql_num_rows( $result ) ){
while ($row = #mysql_fetch_assoc($result)){
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name", $row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("distance", $row['distance']);
}
}else
die( 'MySQL Error - No Records Returned "'.$query.'"' );
echo $dom->saveXML();
?>
Give that a go, and let us know any further error messages you are seeing.
I have the same problem, there're no data, here'is the error
MySQL Error - No Records Returned "SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('37') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('-122') ) + sin( radians('37') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '25' ORDER BY distance LIMIT 0 , 20"
database is populated and I send get vars, like this:
http://localhost/superga/lib/phpsqlsearch_genxml.php?lat=37&lng=-122&radius=25
thanks
I am following the same tutorial and have hit a bend in the road at the same point.
I have followed all suggestions above and still have no resolve.
My error is;
This page contains the following errors:
error on line 1 at column 1: Document is empty
Below is a rendering of the page up to the first error.
Anyone get it to work?
Paula