I am writing a Java script for HTML 5 geolocation but it doesnt seem to work and when I try to output the contents in another scope, it says undefined. Below is the code.
<script>
var lat;
var lng;
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{}
}
function showPosition(position)
{
lat = position.coords.latitude;
lng = position.coords.longitude;
document.write(lat); // Doesnt output anything
}
</script>
<script type="text/javascript">
document.write(lat); // It says undefined
$(document).ready(function()
{
//some scripts here
}
</script>
The success callback functions are called only when the html page is hosted on a web server, not in localhost. Are you testing locally or on a webserver?
Related
I'm bad with Javascript and would like your help!
Hi, I'm building a Rails application and would like to add some features related to geoloction. For that I get the current location of the user with JS and then print it with HTML.
As you guys will see, my code runs every time the page loads, but when my routes change, for example: /about, /settings, /events, it simply disappear and I have to load the page again to print the HTML element.
/* CURRENT LOCATION */
function geolocationSuccess(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var geocoder = new google.maps.Geocoder();
var latlng = {lat: latitude, lng: longitude};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[0]){
var user_address = results[0].formatted_address;
document.getElementById("current_location").innerHTML = user_address;
}else {
console.log('No results found for these coords.');
}
}else {
console.log('Geocoder failed due to: ' + status);
}
});
}
function geolocationError() {
console.log("please enable location for this feature to work!");
}
$(document).ready(function() {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
} else {
alert("Geolocation not supported!");
}
});
How can I have the current location printed on this element in all my application routes?
I wouldn't like to request this information every time.
Maybe a cookie? I don't know...
or request just once every some time
What do you guys recommend? Please help me :)
You can use localStorage for this purpose: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
localStorage allows you to save data between browser sessions and windows.
An example usage might be:
...
// Somewhere in geocode request callback
localStorage.setItem('user_address', results[0].formatted_address)
...
// Somewhere in your render code
document.getElementById("current_location").innerHTML =
localStorage.getItem('user_address')
...
I am using the google geolocation's getCurrentPosition() function for get the current position of the user.
It works fine for me in firefox but not working on chrome.
My code is as below ::
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<p id="demo">Click the button to get your position.</p>
<button onclick="getLocation()">Try It</button>
<div id="mapholder"></div>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showtemp);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var latlon = position.coords.latitude + "," + position.coords.longitude;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?center="
+latlon+"&key=AIzaSyDOgvRydLLNrztjgagobYS_sROK1u3r4M4&zoom=14&size=400x300&sensor=false";
document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}
function showtemp(temp) {
alert("test");
}
function showError(error) {
$.get("http://ipinfo.io", function (response) {
var array = (response.loc).split(',');
console.log(array[0]);
var latlon = array[0] + "," + array[1];
var img_url = "http://maps.googleapis.com/maps/api/staticmap?center="
+latlon+"&zoom=14&size=400x300&sensor=false";
document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}, "jsonp");
}
</script>
</body>
</html>
Please help me solve this.
It Gives me error :: " getCurrentPosition() and watchPosition() are deprecated on insecure origins, and support will be removed in the future. You should consider switching your application to a secure origin, such as HTTPS."
Thanks in advance
getcurrentposition() is deprected and there is no replacement of it. read this answer :- getcurrentposition-and-watchposition-are-deprecated-on-insecure-origins
Click on this google updated api's example link it's working example. : https://developers.google.com/maps/documentation/javascript/examples/map-geolocation.
Hover at top right of the code block to copy the code or open it in JSFiddle.
Use this functions :
// 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.
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
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
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
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.');
}
</script>
Geolocation is not deprecated per se, but limited to sites served via HTTPS.
The warning itself reads "getCurrentPosition() and watchPosition() are deprecated on insecure origins", which boilds down to pages served via HTTP and not HTTPS.
See, your code works fine here in the latest Chrome.
The easiest way to get SSL is probably to use Github pages for hosting your content or using something surge.
You could use the https://ipinfo.io API (it's my service) as an alternative to getCurrentLocation(). It's free for up to 1,000 req/day (with or without SSL support). It gives you coordinates, name and more, works on non-SSL sites, and doesn't prompt the user for permission. Here's an example:
curl ipinfo.io
{
"ip": "172.56.39.47",
"hostname": "No Hostname",
"city": "Oakland",
"region": "California",
"country": "US",
"loc": "37.7350,-122.2088",
"org": "AS21928 T-Mobile USA, Inc.",
"postal": "94621"
}
Here's an example which constructs a coords object with the API response that matches what you get from getCurrentPosition():
$.getJSON('https://ipinfo.io/geo', function(response) {
var loc = response.loc.split(',');
var coords = {
latitude: loc[0],
longitude: loc[1]
};
});
And here's a detailed example that shows how you can use it as a fallback for getCurrentPosition():
function do_something(coords) {
// Do something with the coords here
}
navigator.geolocation.getCurrentPosition(function(position) {
do_something(position.coords);
},
function(failure) {
$.getJSON('https://ipinfo.io/geo', function(response) {
var loc = response.loc.split(',');
var coords = {
latitude: loc[0],
longitude: loc[1]
};
do_something(coords);
});
};
});
See http://ipinfo.io/developers/replacing-navigator-geolocation-getcurrentposition for more details.
For some reason, the code in the same script tag work well, but calling the function that contains the same code from other script tag doesn't.
In my code I have a google map script in the header and it works very well let's call this script tag (A).
The problem is that when I'm not in the script tag A and want to call a function that is in the script A from another script tag to reuse it. it will not work. however if I copied the code from that function and put it directly in the same tag it will work.
I want to be able to call it not to write it again. what is the wrong thing in my code??
The complete code:
<html>
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script
src="http://maps.googleapis.com/maps/api/js">
</script>
<script>
//this is the function that I want call
function getAddress(location) {
var geocoder = new google.maps.Geocoder();
var latLng = new google.maps.LatLng(location.lat(), location.lng());
geocoder.geocode({
latLng: latLng
},
function (responses) {
if (responses && responses.length > 0) {
$("#addressResult").text(responses[0].formatted_address);
// alert(responses[0].formatted_address);
} else {
alert('Cannot determine address at this location.');
}
});
}
var map;
var myCenter = new google.maps.LatLng(51.508742, -0.120850);
function initialize() {
var mapProp = {
center: myCenter,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
google.maps.event.addListener(map, 'click', function (event) {
placeMarker(event.latLng);
});
}
var marker
function placeMarker(location) {
if (marker) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map
});
}
//calling it inside and it's working
getAddress(location);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<label>Location: </label>
<label id="addressResult"></label>
<input type="button" value="Current Location" onclick="getLocation()" />
<script>
var x = document.getElementById("addressResult");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
//here where I want to call it
getAddress(position);
}
</script>
<div id="googleMap" style="width: 500px; height: 380px;"></div>
<div>
</body>
</html>
As Ed mentioned, the problem is probably due to the fact that you put the function call directly in the <script> -- such code executes before the page has finished loading, and may break if something your code depends on is not yet available.
To fix that, put the code in a function that executes after the page is loaded. If you only care about relatively modern browsers, use the DOMContentLoaded event listener, and if you're using a JS framework it likely provides a way to do it while supporting older browsers.
(Obligatory jQuery plug: if you're using it, the syntax is $(function() { /* your code here */ });)
Update
It seems you don't convert the results from navigator.geolocation.getCurrentPosition() to a google.maps.LatLng value properly. Here's an example from the Google documentation:
navigator.geolocation.getCurrentPosition(function(position) {
var initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
Update #2 (from the OP):
Changing showPosition as follows fixed the problem:
function showPosition(position) {
var initialLocation = new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude);
getAddress(initialLocation);
}
I'm implementing some welcome messages to my site that show up at the beginning if the user hasn't enabled the Gps.
The thing is that after enabling the GPS via chrome UI js still can't access the gps postion (keep getting unables alerts on my web page). If page is reloaded then I can.
Is there a way to update the state of the blocking/nonblocking option without refreshing the whole web page ?
<script>
var button = document.getElementById("button");
button.onclick = function() {
var geoSuccess = function (position) {
var startPos = position;
alert("longlat" + startPos.coords.longitude);
};
var geoError = function (error) {
alert("unable");
};
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
};
</script>
Please check out this link :- GPS I do not know whether that is what you asked for but I can just tell it to you .It might help Please forgive me if that is irrelevant. The code is here :
<span id="demo" />
<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>
The code above does the following :
Check if Geolocation is supported
If supported, run the getCurrentPosition() method. If not, display a message to the user .
If the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter ( showPosition )
NOTE : The showPosition() function gets the displays the Latitude and Longitude
I got strange behavior when I tried to test my
"navigator.geolocation.getCurrentPosition" web page. Here is my
testing result and code:
my code:
function detectLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(geocodePosition, onError, { timeout: 30000 });
navigator.geolocation.watchPosition(watchGeocodePosition);
}
else
{
onError();
}
}
this function was run when "body" onload event was called. I had tried to change the timeout to 10000 and 20000, but I still got same result. I also allowed crome and firefox to get my location.
result:
Using chrome (v 17.0.963.79 m), result always went to onError
function when navigator.geolocation.getCurrentPosition was called.
Using Firefox (v 10.0.2), result always went to onError function
when navigator.geolocation.getCurrentPosition was called.
Using IE (v 9), result was fantastic, I got my current location.
can anyone help me in this strange situation? I really didn't have any idea to solve this problem and I was in hurry on my project deadline. Thanks before.
EDIT :
For this couple days I got some progress, the error code code is 2 with a message "Network location provider at 'https://maps.googleapis.com/maps/api/browserlocation/json?browser=chromium&sensor=true' : Response was malformed". Still unsolved, does anyone know how to solve this?
I simulated this problem and found that the success callback functions were only called when the html page was hosted on a web server and not when opened from a filesystem.
To test I opened the file directly from my C: drive and it the callbacks didn't work and then hosted the file on Internet Information Services (IIS) and the callbacks did work.
<html>
<body onload="detectLocation()">
<!-- This html must be hosted on a server for navigator.geolocation callbacks to work -->
<div id="status"></div>
<script type="text/javascript">
function detectLocation()
{
log("detectLocation() starting");
if (navigator.geolocation)
{
log("navigator.geolocation is supported");
navigator.geolocation.getCurrentPosition(geocodePosition, onError, { timeout: 30000 });
navigator.geolocation.watchPosition(watchGeocodePosition);
}
else
{
log("navigator.geolocation not supported");
}
}
function geocodePosition(){
log("geocodePosition() starting");
}
function watchGeocodePosition(){
log("watchGeocodePosition() starting");
}
function onError(error){
log("error " + error.code);
}
function log(msg){
document.getElementById("status").innerHTML = new Date() + " :: " + msg + "<br/>" + document.getElementById("status").innerHTML;
}
</script>
</body>
</html>
I also got this message:
message: "Network location provider at 'https://www.googleapis.com/' : Returned error code 404.", code: 2
I could solve it by switching on my wifi adapter
I had the same issue. Chrome browser wan not returning a position on 30000 miliseconds timeout. Firefox was not returning a position too. I added the option enableHighAccuracy and set it to false but nothing changed(false is the default option). When i change it to true then geolocation started working!
This is my final code,
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(position) {
// Get current cordinates.
positionCords = {"lat": position.coords.latitude, "lng": position.coords.longitude};
},
function(error) {
// On error code..
},
{timeout: 30000, enableHighAccuracy: true, maximumAge: 75000}
);
}
You need to be using https, not http.
The Chrome reference for this is here - https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only
I know this is old topic but recently I had this error also:
message: "Network location provider at 'https://www.googleapis.com/' : Returned error code 404.", code: 2
The fix is to get api key for google maps and use it in your code
<script src='https://maps.googleapis.com/maps/api/jscallback=initMap
&signed_in=true&key=YOUR-API-KEY' async defer></script>
Here you can get API KEY: https://developers.google.com/maps/documentation/javascript/get-api-key#key
I had same issue and solution was to increase the timeout duration as mobile network are slower than wired network
{timeout: 30000, enableHighAccuracy: true, maximumAge: 75000}
along with enabling cellular positioning
In the Device Settings turn on "Wifi and Cellular positioning" option.
This will print the Latitude and Longitude of your Location
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
document.getElementById('idLatitude').value = position.coords.latitude;
document.getElementById('idLongitude').value = position.coords.longitude;
}
</script>
</head>
<body onload="getLocation()">
<form action="HelloWorld" method="post">
<input id="idLatitude" type="text" name="strLatitude">
<input id="idLongitude" type="text" name="strLongitude">
</form>
</body>
</html>