I'm trying to create a simple application that finds your location, sends the co-ordintes using AJAX to a PHP file and then calculates distances in the PHP to show nearby shops.
this is my Javascript and ajax:
$(document).ready(function($) {
// Check for GEOLOCATION support
if (navigator.geolocation) {
window.onload = function() {
var startPos;
var lat;
var lon;
navigator.geolocation.getCurrentPosition(function(position) {
startPos = position;
document.getElementById('currentLat').innerHTML = startPos.coords.latitude;
document.getElementById('currentLon').innerHTML = startPos.coords.longitude;
drawMap(startPos);
},
function(error) {
document.getElementById('locationSupport').innerHTML = "Error code: " + error.code;
// 0 unknown error
// 1 permission denied
// 2 position unavailable (error response from locaton provider)
// 3 timed out
});
};
}
else {
document.getElementById("locationSupport").innerHTML = 'Geolocation is not supported.';
}
});
function drawMap(position) {
var myLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var mapOptions = {
zoom: 15,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('mapCanvas'), mapOptions);
var userMarker = new google.maps.Marker({position: myLatLng, map: map});
}
var jQT = new $.jQTouch({
statusBar: 'black-translucent',
useFastTouch: false, //required for Android
preloadImages: []
});
$.ajax({
type : "POST",
url: "http://cs11ke.icsnewmedia.net/DVPrototype/external-data/location.php",
data : {lat: 'lat', lon: 'lon'},
dataType : "text",
success: function(data){
$("#shopsnotification").html(data);
}
});
and then in my PHP I am using:
<?php
$str_shopresult = '';
mysqli_select_db($db_server, $db_database);
$lat = $_POST['lat'];
$lon = $_POST['lon'];
$query = "SELECT name, address,
(6378.10 * ACOS(COS(RADIANS(latpoint)) * COS(RADIANS(lat)) * COS(RADIANS(longpoint) - RADIANS(lng)) + SIN(RADIANS(latpoint)) * SIN(RADIANS(lat))))
AS distance FROM shops JOIN (SELECT '$lat' AS latpoint, '$lon' AS longpoint) AS p ORDER BY distance LIMIT 10";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shopresult .= "<strong>" . $row['name'] . "</strong><br>" .
$row['address'] . "<br><br>";
}
mysqli_free_result($result);
echo $str_shopresult;
mysqli_close($db_server);
?>
Can anyone see why this isn't working? It just seems to be displaying the shops in a random order rather than using the $lat and $lon variables. Am I retrieving the data wrong? the ajax is displaying the data therefore should be sending the variables correctly (I think)
Any help would be greatly appreciated!