I try to alert my latitude and longitude, but it's doesn't work.
I create a global variables, and change this variables in function. I my other functions not sees this global variables. I don't know, what is the error.
var latitdue;
var longitude;
navigator.geolocation.getCurrentPosition(
function coords(position) {
longitude = position.coords.longitude;
latitude = position.coords.latitude;
}, function (error) {
alert("Error: " + error.code);
},
{
enableHighAccuracy : false,
timeout : 10000,
maximumAge : 1000
});
function a(){
alert(longitude, latitude);
}
a();
its a typo error "latitude" not var latitdue
change
var latitdue;
to
var latitude
and "Allow" the popup or hint on browser bar for accessing computer's location
Try the below code:
<script type="text/javascript">
var latitude;
var longitude;
function a(){
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(
function coords(position) {
longitude = position.coords.longitude;
latitude = position.coords.latitude;
alert("Lat Long is : " + longitude +"," + latitude);
}, function (error) {
alert("Error: " + error.code);
},
{
enableHighAccuracy : true,
timeout : 10000,
maximumAge : 1000
});
}
else
{
alert ("GEOLOCATION NOT SUPPORTED....");
}
}
//a();
</script>
</head>
<body onLoad="a();">
TESTING GEOLOCATION
</body>
You will have to call the method after loading success.
Also, Allow for share location.
Related
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>
This is the error that I am getting while running below javascript file
getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https for more details.
This is my javascript file
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA4HSRrQSje--aI6ImtJF30s5ezaUWxsow&libraries=places"></script>
<script>
function getLocation()
{
console.log("In geolocation");
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else
{
print("Browser doesn't support geolocation");
}
function showPosition(position)
{
console.log("in show position");
dest_lat=position.coords.latitude;
dest_long=position.coords.longitude;
url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='+ dest_lat + ',' + dest_long + '&sensor=false';
$.get(url, function(data)
{
if (data.status == 'OK')
{
map.setCenter(data.results[0].geometry.location);
console.log("Dragaed lat "+marker.getPosition().lat());
console.log("Dragged lng "+marker.getPosition().lng());
console.log("Address "+data.results[0].formatted_address);
}
});
}
</script>
</head>
<body>
<input type="button" value="LocateMe" onclick="getLocation();"/>
</body>
</html>
You have to put it one a server with https://!
If you are using Visual Studio, you can configure to lunch the site with https:// see: https://dotnetcodr.com/2015/09/18/how-to-enable-ssl-for-a-net-project-in-visual-studio/
Alternativelyyou can test it on jsfiddler, which uses https per default.
Besides that your code has a lot of other errors.
Brackets don't match
map object is not defined in your example
varibles are not declared (they are added to the global namespace which can cause some really nasty problems later on and throws an error when you use "use strict")
Here is a working excample on jsfiddle: https://jsfiddle.net/3gkkvs50/
(stackoverflow doesn't use https for the examples)
HTML:
<input type="button" value="LocateMe" onclick="getLocation();" />
JS:
function getLocation() {
console.log("In geolocation");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
print("Browser doesn't support geolocation");
}
}
function showPosition(position) {
console.log("in show position");
var dest_lat = position.coords.latitude;
var dest_long = position.coords.longitude;
var url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + dest_lat + ',' + dest_long + '&sensor=false';
$.get(url, function(data) {
alert(JSON.stringify(data));
});
}
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.
I dont understand, how could this happen? I only got 1 variable but it seems like it has 2 different values. Please see the output below. Here's the code of the webpage:
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
var map;
var geocoder;
var center = new google.maps.LatLng(11.17840187,122.59643555);
var marker = new google.maps.Marker();
var info = new google.maps.InfoWindow();
var latitude = 0.00;
var longitude = 0.00;
var address = "NO ADDRESS";
var loaded = false;
function initialize() {
var mapProp = {
center : center,
zoom : 5,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
geocoder = new google.maps.Geocoder();
google.maps.event.addListener(map, "click", function (event) {
latitude = event.latLng.lat();
longitude = event.latLng.lng();
center = new google.maps.LatLng(latitude,longitude);
displayAddress();
moveToCenter();
console.log("Address : " + address)
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function moveToCenter(){
map.panTo(center);
marker.setPosition(center);
marker.setMap(map);
}
function displayAddress(){
geocoder.geocode( {'latLng': center},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if(results[0]) {
address = results[0].formatted_address;
}
else {
address = "";
}
info.setContent("<b>" + address + "</b>");
info.open(map,marker);
}
});
}
function setWidth(width){
document.getElementById('googleMap').style.width = width + "px";
google.maps.event.trigger(map, 'resize');
}
function setHeight(height){
document.getElementById('googleMap').style.height = height + "px";
google.maps.event.trigger(map, 'resize');
}
</script>
<style>
body
{
padding : 0;
margin : 0;
overlow : hidden;
}
#googleMap
{
width : 600px;
height : 600px;
overlow : hidden;
}
</style>
</head>
<body>
<div id="googleMap"></div>
</body>
</html>
I have a variable address in my code, but I dont understand why it has two different values. How does this happen? Is it a Javascript Bug?
Here's the output:
I see what you're asking now. Perhaps we can we rephrase the question.
Q: Why when I set address in displayAddress() does it display the address correctly in the map but still log "No address" in the console?
A: It's because you've introduced an asynchronous process into your code.
You think that the following should happen:
Set address to "No address"
Call displayAddress() which changes the value of address and
also displays it on the map
Log the changed address
What's actually happening is this:
Set address to "No address"
Call displayAddress() - the async process geocode starts
Log the address (this hasn't changed)
The async operation completes and the address is displayed on the map.
If you want to know more about async processes and how to return values from them this SO question has lots of relevant information.
I think the problem comes from the fact that the code which modifies your address variable is called after the console.log instruction.
As a matter of fact, all of the following code:
if(status == google.maps.GeocoderStatus.OK) {
if(results[0]) {
address = results[0].formatted_address;
}
else {
address = "";
}
info.setContent("<b>" + address + "</b>");
info.open(map,marker);
}
is contained in the callback function which is passed to the geocoder.geocode method, and which will then be executed once the remote request has been completed. Which, given the reponse time of the remote request (a few tens or hundreds of miiliseconds), occurs after the execution of the console.log statement.
Take a closer look at your code.
function displayAddress(){
geocoder.geocode( {'latLng': center},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if(results[0]) {
address = results[0].formatted_address; <------ Take a look at this
}
else {
address = "";
}
info.setContent("<b>" + address + "</b>");
info.open(map,marker);
}
});
}
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>