Getting users city and country info using Google GeoApi - javascript

I am using this code to get users full address info
function getGeo() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (a) {
$("#geoLoc").html("Determing your location..");
$.post("https://mysite.com/getloc.php?l=" + a.coords.latitude + "," + a.coords.longitude, function (b) {
var c = jsonParse(b);
geo_adres = c.results[0].formatted_address;
latitude = a.coords.latitude;
longitude = a.coords.longitude;
$("#geoLoc").html(c.results[0].formatted_address);
$("#geoLoc").show("slow")
})
}, function (a) {
alert(geolocationErrorMessages[a.code])
}, {
enableHighAccuracy: true,
maximumAge: 12e4
});
return false
} else {
alert("Your browser doesn't support geo-location feature...")
}
}
EDIT:
getloc.php contains this codes (c var in javascript)
$data = file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?latlng=". $_GET['l'] ."&sensor=false");
print $data;
Actually all i want is to get users city and country info like that city, country
How should i change this one c.results[0].formatted_address to achieve that ?

Try this working php code, i hope this is going to help you a lot :) and let mew know in case of any query --
<?php
$data = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false");
$jsonnew =json_decode($data,true);
echo "<pre>";
print_r($jsonnew['results'][7]['address_components'][2]['long_name']);
echo "<pre>";
print_r($jsonnew['results'][6]['address_components'][2]['long_name']);

You shouldn't need your getloc PHP script. The Maps Javascript API includes a Geocoder class.

Related

Geolocation script not returning value

I am trying to use Javascript for finding user location but it is not giving me any value, my code is below
<script>
window.onload = function() {
var startPos;
var geoSuccess = function(position) {
startPos = position;
document.getElementById('startLat').innerHTML = startPos.coords.latitude;
document.getElementById('startLon').innerHTML = startPos.coords.longitude;
};
navigator.geolocation.getCurrentPosition(geoSuccess);
};
</script>
<?php echo "<script> getCurrentPosition('startLat') </script>"; ?>
The HTML5 Geolocation API allows you to get a user's Latitude/Longitude with some JavaScript (if the browser is compatible, and if the user allows access to his/her location).
You can then reverse-geocode the location to get an address, there are several free reverse-geocoding services other than Google's API.
you can also check out this link How to get geographical location of an IP address in PHP for more understanding
Example:
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
If you have elements with id's "startLat" and "startLon" in your HTML, it'll work
Just add in HTML:
<p id="startLat"></p>
<p id="startLon"></p>
You can delete this line, actually:
<?php echo "<script> getCurrentPosition('startLat') </script>"; ?>
To use Latitude/Longitude in your PHP you can send the values via JS
In HTML
<script>
function sendData(value) {
var request = new XMLHttpRequest();
request.open('post', 'DESTINATION.PHP', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send('data=' + value);
}
</script>
Or as a hidden form input
and access in PHP
if(isset($_POST['data'])){
$data = $_POST['data'];
// Do stuff...
}

Geolocation is working in local but doesn't on remote server

I uploaded the web app that I'm working on to a remote server.
Everything is working good, except for the geolocation. I can't understand what is the problem, beacuse I didn't receive any error message.
this the HTML code where geolocation is involved.
<tr>
<td>Ti trovi qui: <span id="location"></span></td>
</tr>
</table>
<input type="hidden" id="latitude" name="latitude">
<input type="hidden" id="longitude" name="longitude">
</form>
These are the scripts that I use: (i'm not very prepared with javascript and jQuery)
function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
jQuery.ajax({
type:'POST',
url:'getLocation.php',
data:'latitude='+latitude+'&longitude='+longitude,
success:function(msg){
if(msg){
jQuery("#location").html(msg);
}else{
jQuery("#location").html('Not Available');
}
}
});
}
function getUserCoordinates(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
document.getElementById('latitude').value=latitude
document.getElementById('longitude').value=longitude
}
jQuery(document).ready(function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getUserCoordinates);
navigator.geolocation.getCurrentPosition(showLocation);
} else {
jQuery('#location').html('Geolocation is not supported by this browser.');
}
});
This is getLocation.php file (but I don't think it's the problem):
<?php
require_once 'metodi.php';
sec_session_start();
if(login_check() == true){
if(!empty($_POST['latitude']) && !empty($_POST['longitude'])){
$_SESSION['latitude'] = $_POST['latitude'];
$_SESSION['longitude'] = $_POST['longitude'];
//Send request and receive json data by latitude and longitude
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($_POST['latitude']).','.trim($_POST['longitude']).'&sensor=false';
$json = #file_get_contents($url);
$data = json_decode($json);
$status = $data->status;
if($status=="OK"){
//Get address from json data
$location = $data->results[0]->formatted_address;
}else{
$location = '';
}
//Print address
echo $location;
}
} else {
echo "Non sei autorizzato a visualizzare questa pagina. Effettua il login.";
}
?>
Then I grab the value of hidden inputs in another php file.
If your website is running in https, you also need to change this
http://maps.googleapis.com/maps/api/geocode/json?latlng=
to this
https://maps.googleapis.com/maps/api/geocode/json?latlng=
getCurrentPosition() is asynchronous. When you call it twice there is no guarantee that the first call will complete before the second one does. It also makes no sense to call it twice back to back
Also it relies on third party service to return the data
Only call it once, and pass the response values to both of your functions inside one callback
Change
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getUserCoordinates);
navigator.geolocation.getCurrentPosition(showLocation);
} else {
To
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
getUserCoordinates(position);
showLocation(position);
});
} else {
Also check that you haven't disabled geolocation in your browser for the the remote domain. Add some console logging to see what is and isn't running within the code

Getting user IP when using Jquery

Okay, so I am using a jquery script to use a get method to pull information from another file like so:
$(document).ready(function() {
$('#calculate').click(function(){
$.ajax({
type: 'GET',
url: '/system/calculate.php',
data: 'amount=' + $('#buyamount').val() + '&coin=<?php echo $coin; ?>' ,
success: function(msg) {
$('#totalprice').html(msg);
}
});
});
});
I want to inert their ip address in the database, but I can't set it in that calculate file because they aren't actually visiting that page to set the IP address. Now, I don't want to use the get function to send their IP address because they could simply edit the ?ip= to whatever they want.
I tried setting it in the calcuate file, but their ip is set as ::1
tl;dr: using jquery to run scrip from another file, can't set IP because they don't visit that page personally.
you can get client ip in php and that ip can insert in your db.
function getIp() {
$ip = '';
if (isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR'])) {
$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
}
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
if (strpos(filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP), ',') !== false) {
$temp_ips = explode(',', filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP));
}
if (!empty($temp_ips)) {
$ip = $temp_ips[count($temp_ips) - 1];
} else {
$ip = filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP);
}
}
if (isset($_SERVER['HTTP_CF_CONNECTING_IP']) && !empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
$ip = filter_var($_SERVER['HTTP_CF_CONNECTING_IP'], FILTER_VALIDATE_IP);
}
return $ip;
}

How do you use a php variable for directory path?

I am getting userid from the url.
This is what I have at the moment. I want to replace the one with $userid but I don't know how. It doesn't work and I can't seem to find the right syntax, please can someone help?
function returnimages($dirname = "Photos/1")
Basically I am trying to create a photo slideshow using html, php and javascript. I had something working before I started adding php into my code. I had html and an external javascript that changes the photos and they fade in and out in a loop. I have a photo array in javascript. Right now I am trying to add php to my html. I want to be able to get userid via url and then from that get the photos from a specific path to the userid in the directory. Then I am hoping to create an array of these photos and use them in my javascript. Here is my php code embedded in my html:
<?php
$user_id = $_GET['userid'];
print " Hi, $user_id ";
function returnimages($dirname = "Photos/1") { //will replace 1 with userid once something starts working
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
And my javascript:
$ (document).ready(function(){
var photodisplay =
[
$("#photo1"),
$("#photo2"),
$("#photo3"),
$("#photo4"),
$("#photo5"),
];
//photodisplay[0].hide().fadeIn(3000);
var user = new Array();
[1, 2, 3, 4, 5];
// List of images for user one
/*var userphoto = new Array();
userphoto[0] = "Photos/1/1.jpg";
userphoto[1] = "Photos/1/2.jpg";
userphoto[2] = "Photos/1/1.jpg";
userphoto[3] = "Photos/1/1.jpg";
userphoto[4] = "Photos/1/1.jpg";*/
//preloading photos
var userphoto = <? echo json_encode($galleryarray); ?>;
function preloadingPhotos() {
for (var x=0; x<5; x++)
{
photodisplay[x].attr("src", "Photos/1" + userphoto[x]);
photodisplay[x].hide();
console.log("preloaded photos");
}
displayPhoto();
}
function displayPhoto(){
photodisplay[0].fadeIn(3000);
photodisplay[0].delay(3000).fadeOut(3000, function() { //first callback func
photodisplay[1].fadeIn(3000);
photodisplay[1].delay(3000).fadeOut(3000, function() { //second callback func
photodisplay[2].fadeIn(3000);
photodisplay[2].delay(3000).fadeOut(3000, function() { //third callback func
photodisplay[3].fadeIn(3000);
photodisplay[3].delay(3000).fadeOut(3000, function() { // fourth callback func
photodisplay[4].fadeIn(3000);
photodisplay[4].delay(3000).fadeOut(3000, function() {
setTimeout(displayPhoto(), 3000);
});
});
});
});
});
}// end of function displayPhoto
window.onload = preloadingPhotos;
}); //end ready
My url to get userid:
http://example.com/code.php?user_id=1
Thank you for your time!
The problem is that you are always setting the dirname instead of letting calling the function set it. You could change:
function returnimages($dirname = "Photos/1") {
to
function returnimages($dirname) {
because otherwise the $dirname is always Photo/1. Then, when you call the function, use:
returnimages('Photos/'.$user_id);
You can concatenate in PHP by using the dot '.'. This will concatenate two string and then assign them to the variable $dirname. For example:
$dirname = "Photos/" . $_GET['ID'];
The variable $dirname can then be placed in the function returnimages, like:
returnimages($dirname);

Trouble using jQuery post inside non jQuery function

I have the following script inside a HTML page:
<script>
function Test(){
alert("i got here");
var username = document.registration_form.username.value;
alert(username);
$.post("checkname.php", { name: username }, function(data) {
alert("and here");
alert(data);
if (data = "0"){
alert('That username is already in use, please choose another');
return false;
};
if (data = "1") {
return true;
};
});
};
</script>
I'm trying to get the function test to return true or false if a username is already in my database.
checkname.php contains the following:
<?
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$myusername=$_POST['name'];
$sql="SELECT * FROM members WHERE username='".$myusername."'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count >= 1){
echo "0";
}
else {
echo "1";
}
?>
I've tried hardcoding a name and running the PHP and it works fine.
For some reason though when I run Test() the first 2 alerts come through fine, showing me the username enetered, but none of the subsequent alerts appear.
Oooo and jQuery has been added in the header like so:
<script src="create/js/jquery-1.4.4.min.js" type="text/javascript" ></script>
<script src="create/js/jquery-ui-1.8.7.custom.min.js" type="text/javascript"></script>
Any help much appreciated :)
First of all, your return statements from the callback to $.post will not return from your Test() function. You should call Test with a callback function that deals with the data from the server, something like this:
function Test(username, callback) {
$.post("checkname.php", {name: username}, callback);
}
Test(document.registration_form.username.value, function(data) {
if(data == "0") {
// Do something
} else {
// Do something else
}
});
Brad is also correct about the comparison - you're currently assigning "0" to data. You should get the alerts though, I think, even with the other errors. Maybe you need the absolute path to the checkname.php script? E.g. "/checkname.php" (note the slash)?
Off-hand, you should be using == for comparison in javascript. A single = is an assignment, == is a comparison. So having said that, if (data = "0"){ would become if (data == "0"){.
Other than that, I don't see anything too fishy. You're allowed to use jQuery functions within "traditional" javascript function(){}'s.
Also, make sure you sanitize the input from the $_POST['name'] using something like mysql_real_escape_string.
The problem may be that the PHP script is returning a new line before or after it prints 0 or 1. So the string returned wouldn't equal "0" or "1".
Try to change it to output JSON instead.
if($count >= 1){
$ret = 0;
}
else{
$ret = 1;
}
echo json_encode(array('status' => $ret));
And then change your $.post to:
$.post("checkname.php", { name: username }, function(data) {
alert("and here");
alert(data);
if(data.status = 0){
alert('That username is already in use, please choose another');
}
if(data.status = 1) {
alert('That username is not already in use');
}
}, 'json');
NOTE: The return false and return true don't do anything. You cannot return from an AJAX call.

Categories