I have a site with a directory of businesses which has links of cities that the user can click and find businesses near that city.
Up until now I have accomplished this simply using a GET variable on the links and processing the location with PHP and Google Maps API. Unfortunately, the site is starting to generate more than 2500 queries per day so I decided to try using the Javascript API to retrieve the lat/lng client side when the user clicks the link and then set it to the SESSION using AJAX. I thought I was on the right track but it's not working. It seems to either not work at all or only change the SESSION variables after clicking on a link several times. I thought setting async:false
would fix it, but it didn't
Any Ideas?
Here is my test page:
<?php
session_start();
require_once('../includes/header.php');
echo $_SESSION["address"] . "<br>";
echo $_SESSION["lat"] . "<br>";
echo $_SESSION["lng"] . "<br>";
?>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<a href="test.php" id="Orlando" class="loc">Orlando</a><br /><br />
<a href="test.php" id="Tampa" class="loc">Tampa</a><br /><br />
<a href="test.php" id="Daytona" class="loc">Daytona</a><br /><br />
<script type="text/javascript">
function setLoc(lat,lng,address){
$.ajax({
async: false,
type: 'POST',
url: 'setLoc.php',
data: {lat: lat,lng: lng,address: address}
});
}
$('.loc').each(function() {
$(this).click(function() {
var address = $(this).attr('id');
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address+'FL'}, function(results, status) {
var location = results[0].geometry.location;
lat=location.lat();
lng=location.lng();
setLoc(lat,lng,address);
});
});
});
</script>
<?php
require_once('../includes/footer.php');
?>
And this is the setLoc.php file:
<?php
session_start();
unset($_SESSION["address"]);
unset($_SESSION["lat"]);
unset($_SESSION["lng"]);
$_SESSION["lat"] = $_POST["lat"];
$_SESSION["lng"] = $_POST["lng"];
$_SESSION["address"] = $_POST["address"]
?>
I added the unsets because I thought clearing it each time would make a difference but it didn't
I was able to achieve my desired result using this:
<script type="text/javascript">
function setLoc(lat,lng,address,href){
$.ajax({
type: 'POST',
url: 'setLoc.php',
data: {lat: lat,lng: lng,address: address},
success: function(){
location.href=href;
}
});
}
$('.loc').each(function() {
$(this).click(function(e) {
var href=$(this).attr('href');
e.preventDefault();
var address = $(this).attr('id');
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address+'FL'}, function(results, status) {
var location = results[0].geometry.location;
var lat=location.lat();
var lng=location.lng();
setLoc(lat,lng,address,href);
});
});
});
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.