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.
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')
...
Image of Firebase database.
This is my Firebase database. The data in there are pictures with Geolocation tags. I want to be able to have the location where each picture was taken pop up on Google Maps using the Google Map API on my website.
I did some research and it looks like the only thing Firebase has in relation to this is creating heat maps. I tried following through and this is what I was able to come up with:
var map, infoWindow, db;
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.
db =firebase.firestore();
// if (navigator.geolocation)
if(db.collection("signs").where("type", "==", 'geopoint')) {
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=APIKEY&callback=initMap">
</script>
I am sure i have structured this wrong, but the event listener for "dragend" is not firing. When I change the event to bounds_changed or center_changed then it only fires on the initial page load. Is there anything that stands out as to why it is behaving like this?
I basically just want to call my searchStores() function everytime the map is repositioned so it becomes reactive to the user.
var map;
$(document).ready(function () {
var latlng = new google.maps.LatLng(36.2994410, -82.3409052);
var myOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// create the new map with options
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
$("#btnSearch").click(function(){
//Convert Address Into LatLng and Retrieve Address Near by
convertAddressToLatLng($("#txtAddress").val());
});
//send user to print/save view on click
$("#saveAs").click(function() {
window.location.href = "https://54.90.210.118/test.html?address=" + $("#txtAddress").val() + '&radius=' + $("#radiusO").val();
});
//WHAT IS GOING ON WITH THIS GUY???
google.maps.event.addListener(map, "dragend", function() {
alert('map dragged');
});
});
$(document).one('ready', function(){
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
latlngloc = new google.maps.LatLng(pos.lat, pos.lng);
map.setCenter(pos);
$("#divStores").html('');
searchStores(latlngloc);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
});
Thanks for the help! I found the issue was on another function that ended up clearing the map object and then recreating it. Therefore removing the listener.
Sorry for the confusion, and thanks for pointing out that it worked on Jfiddle. I thought it was something to do with how I was calling it.
I am really new to Javascript and having to teach myself bit by bit. Thanks for all the help! =)
I'm trying to build a tracker that only requires a browser window be open, on mobile devices. All of the code seems to work, other than navigator.gelocation.getCurrentPosition. As you can see, I'm using a timer to cycle my code every few seconds. I was expecting the code within the time to output real-time location information, but instead, it seems to resort to using the last known location - or if there isn't one, it will find the location and then keep using the same one.
I'm not sure if this is an issue with Android or my code, but it seemed to work well on an iPhone - but it wasn't me who tested it, so I can't really be sure.
Thanks in advance!
var lati = " ";
var longi = " ";
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 15
});
var timerID = setInterval(function() {
// Try HTML5 geolocation.
if (navigator.geolocation) {
var infoWindow = new google.maps.InfoWindow({map: map});
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
lati = (position.coords.latitude);
longi = (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
{
$.ajax({ url: 'php_test.php',
data: {'Lati': lati, 'Longi': longi},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
}
});
}
}, 2 * 1000);
}
I'm facing the same issue but I realize debugging that getCurrentPosition is deprecated on insecure origins.
https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins
Maybe you can achieve something like How do I get the current GPS location programmatically in Android?
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);
}