First of all, please apologize my English.
Hi! I need to print with PHP the current user´s address, i have this small script:
<?
function getaddress($lat,$lng)
{
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($lat).','.trim($lng).'&sensor=false';
$json = #file_get_contents($url);
$data=json_decode($json);
$status = $data->status;
if($status=="OK")
{
return $data->results[0]->formatted_address;
}
else
{
return false;
}
}
?>
<?php
$lat= 21.884766199999998; //latitude
$lng= -102.2996459; //longitude
$address= getaddress($lat,$lng);
if($address)
{
echo $address;
}
else
{
echo "Not found";
}
?>
of course it works, but I don't know how to change the $lat and $long variables to the current users location.
In few words; how I can pass the current user lat and long location to the PHP variables to let this script works?
<html>
<body>
<p id="demo">Click the button to get your coordinates:</p>
<button onclick="getLocation()">Try It</button>
<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>
</body>
</html>
this is an javascript based search. you can try it in html browser and pass the lat long to the php scripts.
if it helps you its ok or you can tell , i have other ways too.
You need to get this using JavaScript or other google api. Which you can place lat & lang in an separate hidden field and then assign to your php variables from that hidden fields.
Here is an example script to get this using html 5 and java-script
<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>
This is another script using google Geo-location API
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
Related
I have a script which I can't get working. I keep getting the error 'Geocoder failed' but I am not sure why. It is supposed to get the long/lat and then reverse geocode it to show the street address in an alert box. I have tried ensuring that the browser is letting it share the location. I have also tried accessing via HTTPS as I read that this was needed now but it still doesn't work.
If anyone can help me to get this working I would be most grateful!
Thanks in advance.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Current Location Address</title>
<style>
</style>
</head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
alert(results[0].formatted_address)
//find country name
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
//city data
alert(city.short_name + " " + city.long_name)
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
</head>
<body onload="initialize()"> <font face="verdana">
<!DOCTYPE html>
If available, your current address will have been displayed in a message window. Please press 'Back' when finished.
</body>
</html>
Your errorFunction is automatically passed an error parameter that you can take a look at:
function errorFunction(error){
alert("Geocoder failed: "+error.message);
}
See the MDN docs for more background and examples.
This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 6 years ago.
I'm trying to build a small site that tracks the location of a car, and stores the data in a database. At the moment, I have it all set up with a .php file, with the Javascript smooshed in - I'm really not sure if this is advisable, I'm pretty new to programming for the web.
I need the "lati" variable, within the big script, to be sent to the PHP script (bottom of the code).
The code all works, it tracks the user and submits data to the database, but the field that it populates in the database is blank :( See my code -
<!DOCTYPE html>
<?php
$username = "ishuttle";
$password = "m7elH07yO2";
$hostname = "localhost";
$dbname = "ishuttle_taxi-location";
//connection to the database
$conn = mysqli_connect($hostname, $username, $password, $dbname)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 100;
}
#map {
height: 70%;
width: 100%;
}
</style>
</head>
<body>
<center>
<h1>DANKCATT DRIVER SIDE APP</h1>
</center>
<div id="map"></div>
<div id="capture"></div>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
var Lati;
var Longi;
Lati = 3;
Longi = 3;
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 15
});
var timerID = setInterval(function() {
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var lati = {
lat: position.coords.latitude
};
var longi = {
lng: position.coords.longitude
};
console.log(lati, "Lol");
infoWindow.setPosition(pos);
infoWindow.setContent('lati');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
//in a loop (setInterval) get coords and apply them to database
}, 10 * 1000);
}
//reverse this for the home page - drag the coords out of the db and display them on a loop
google.maps.event.addDomListener(window, 'load', getLocation);
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDONVV6mCAgATiPAanIbdfY55_felLGHHk&callback=initMap">
</script>
<?php
$lati = $_GET['Lati'];
$sql = "UPDATE driver_location SET Latitude = '$lati' WHERE ID_No = 1111;";
echo "$lati";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
?>
</body>
</html>
You may want to separate your php database code into another file so that you can do an ajax post from your javascript file to the php file.
Here is an example of an ajax post using jquery. This is the javascript that would allow you to post from javascript into a php page:
$.ajax({
method: 'POST',
url: 'likeComment.php',
data: {'commentId': commentId},
success: afterLikeComment,
dataType: 'json'});
Learn Jquery is a site for learning jquery and here is the jquery site itself Jquery site. jQuery is a Javascript wrapper that makes doing things like selecting dom elements and posting to php much easier.
When i am running the following code, which i have taken from this answer, i am getting Uncaught TypeError: Cannot read property 'geocode' of undefined error in browser's console, why its happening because on the body load here initialize function has to be called, and instead of calling initialize function here codeLatLng(lat, lng) is calling first.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Reverse Geocoding</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
alert(results[0].formatted_address)
//find country name
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
//city data
alert(city.short_name + " " + city.long_name)
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
</body>
</html>
There is no need to wait for the onload-event until you initialize the Geocoder-instance. You load the maps-API synchronously, so the API(including google.maps.Geocoder) is available immediately after loading the API.
The issue: when geolocation runs too fast, and the callback of navigator.geolocation.getCurrentPosition will be executed before the onload-event, geocoder is undefined.
Replace this line:
var geocoder;
with this line:
var geocoder = new google.maps.Geocoder();
I want to display on screen the var longitude en latitude but I think that the function is executing last and I'am stuck with the initial values.
The objective is to print on screen the exact values of the geolocation that the browser returns.
Thanks !!!
<!DOCTYPE html>
<head>
<script>
var longitude = "10";
var latitude = "20";
</script>
</head>
<html>
<body onload="getLocation()">
<script>
var longitude = "30";
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
alert('aaab:' +longitude);
});
}else {
alert("Geolocation API is not supported in your browser.");
}
}
</script>
<script>
alert("ccc");
document.write (longitude);
document.write (latitude);
</script>
</body>
</html>
i know that it's working within the function, but there is any way to use those variable outside? I just want to be able to store them in one global variable that cand be called wherever. Thanks
document.write is being executed before your code that updates it is being run. You need to do the document.write in the callback like so:
<!DOCTYPE html>
<head>
<script type='text/javascript'>
var longitude = "10";
var latitude = "20";
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
document.write(latitude+" / "+longitude);
});
}else{
alert("Geolocation API is not supported in your browser.");
}
}
</script>
</head>
<body onload="getLocation()">
</body>
</html>
Try this:
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocation);
}else {
alert("Geolocation API is not supported in your browser.");
}
}
function displayLocation(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
alert('aaab:' +longitude);
}
The Geolocation Callback probably hasn't been called at the time you write your longitude and latitude. Maybe you can use jQuery to write the correct values to the screen...
<script>
var longitude = "30";
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
//alert('aaab:' +longitude);
// Use jQuery to write your values to the html
$("#longitude").html(longitude);
$("#latitude").html(latitude);
});
}else {
alert("Geolocation API is not supported in your browser.");
}
}
</script>
<html>
...
<body onload="getLocation()">
<div id="longitude"></div>
<div id="latitude"></div>
</body>
</html>
I did it in android but now i need to build app through phone-gap and i need to load map on the device and get current position coordinate(latitude and longitude) of the device.
So i need to have javascript code now and to be frank i am not much familiar with java script for now…Any code/help.
This is my code through which i am showing the map
Thanks
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key*****************&sensor=true">
</script>
<script type="text/javascript">
function initialize() {
var myOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
In the place of "*" i am having my google api key..
Now i need to get the coordinates…
modified and currently using this code got from the link http://docs.phonegap.com/en/1.0.0/phonegap_geolocation_geolocation.md.html but even then i am getting this error "KCLErrorDomain Error 0"
<!DOCTYPE html>
<html>
<head>
<title>Device Properties Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
var watchID = null;
function onDeviceReady() {
var options = { frequency: 5000 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
</script>
</head>
<body>
<p id="geolocation">locating coordinates...</p>
</body>
</html>
I am not getting how to solve this error…using xcode 4.0.1 for phonegap apps development and trying to run on 4.3 simulator..
Here a quote from the PhoneGap documentation on Geolocation (http://docs.phonegap.com/en/1.0.0/phonegap_geolocation_geolocation.md.html):
Geolocation provides location information for the device, such as latitude and longitude. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs. No guarantee is given that the API returns the device's actual location.
This API is based on the W3C Geo location API Specification. Some devices already provide an implementation of this spec. For those devices, the built-in support is used instead of replacing it with PhoneGap's implementation. For devices that don't have geolocation support, PhoneGap's implementation should be compatible with the W3C specification.
So basically, you can use the HTML5 Geolocation API without having to worry about any differences in PhoneGap. If you want to get the user's position once, use navigator.geolocation.getCurrentPosition() and if you want to periodically be sent the user's position, use navigator.geolocation.watchPosition():
navigator.geolocation.watchPosition(locationSuccess, locationError, {timeout: 30000});
function locationSuccess(position)
{
// this is your position as a LatLng object. use it however you need
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
}
function locationError(err)
{
if (err.code == 1)
alert("You must allow this website to use the Geolocation API to access your position.");
else if (err.code == 3)
alert("Unfortunately, your position request timed out.");
else
alert("Unfortunately, your position could not be determined.");
}