Send geolocation data to php and display query

I really need help to wrap my head around this and figure out how to proceed with a geolocation function Im creating. I have a custom post type with posts that contain fields for latitude and longitude. I want the users to be able to click “Get posts by my location” and display to nearest posts to the user using geolocation. These are the steps that I have done so far, and now im stuck.

1. Fetch geolocation using html onClick and send to getLocation.php using this code:

jQuery(document).ready(function(){
jQuery(‘#findLocation’).click(function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showLocation);
} else {
jQuery(‘#location’).html(‘Geolocation is not supported by this browser.’);
}
});
});

function showLocation(position) {

var latitude = position.coords.latitude;
var longitude = position.coords.longitude;

jQuery.ajax({
type:’POST’,
url:'<?php echo get_template_directory_uri(); ?>/partials/getLocation.php’,
data:’latitude=’+latitude+’&longitude=’+longitude,
success:function(msg){
if(msg){
jQuery(“#location”).html(msg);
}else{
jQuery(“#location”).html(‘Not Available’);
}
}
});

}

2. Collect gelocation data and output variable for latitude and longitude using this code in getLocation.php

<?php
if(!empty($_POST[‘latitude’]) && !empty($_POST[‘longitude’])){
//Send request and receive json data by latitude and longitude
$json = @file_get_contents($url);
$data = json_decode($json);
$lat = $_POST[‘latitude’];
$long = $_POST[‘longitude’];
$status = $data->status;

if($status==”OK”){
//Get address from json data
$location = $data->results[0]->formatted_address;

}else{
$location = ”;
}

echo $lat;
echo $long;
}
?>

3. This is where my problem comes in. I want to be able to run this query when the variables $lat $long exsist and put them in the query below to render the loop. How do I runt the query once the information exists?:

$query = new WP_GeoQuery(array(
‘latitude’ => $lat, // User’s Latitude (optional)
‘longitude’ => $long, // User’s Longitude (optional)
‘radius’ =>15, // Radius to select for in miles (optional)
‘posts_per_page’ => 250, // Any regular options available via WP_Query
‘fields’ => ‘all’,

));

foreach($query->posts as $post)
{
$stationCity = get_field(‘stationcity’);

echo ” {$stationCity}<br />n”;
echo ” {$post->post_title}<br />n”;
// returned only if latitude and longitude are passed into WP_GeoQuery
echo ” {$post->distance} miles<br />n”;
// Always returned by WP_GeoQuery
echo ” {$post->location}<br />n”;
echo ” {$post->latitude}<br />n”;
echo ” {$post->longitude}<br />n”;
echo “<br />n”;
}

Read more here:: Send geolocation data to php and display query

Leave a Reply

Your email address will not be published. Required fields are marked *