I'm trying to get the longitude and latitude of the user but I'm seeing that in Codepen the navigator.geolocation.getCurrentPosition is not working.
$(document).ready(function() {
if(navigator.geolocation){
function success(position){
var lat = position.coords.latitude;
var long = position.coords.longitude;
$("p").html("latitude: " + lat + "<br>longitude: " + long);
};
function failure(){
$("p").html("Not working");
};
navigator.geolocation.getCurrentPosition(success,failure);
};
});
Output:
Not Working
So, is there a way around it or do I have to use another API for this?
This is a repeat of javascript - geolocation not working in codepen.
Chrome excerpt:
getCurrentPosition() and watchPosition() are deprecated on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS.
Related
I have an app with google maps link like this
const url = Platform.select({
ios: `https://www.google.com/maps/search/?api=1&query=${label}`,
android: `${scheme}${latLng}(${label})`
});
Linking.canOpenURL(url)
What I want to do is to query google maps using query=${lat},${lon} and using the name described as label above, because when I do the query, google maps open at the location but the pin displays the lat and long, and I want to display the label string
Please help!
I just figured it out. If you have google maps installed it will open the app with the desired location and pin correctly. If you don't have google maps installed it will open the browser with google maps and location! :)
const scheme = Platform.select({ ios: 'maps:0,0?q=', android: 'geo:0,0?q=' });
const latLng = `${your Lat},${your Long}`;
const label = this.state.clinic.name;
const url = Platform.select({
ios: `https://www.google.com/maps/search/?api=1&query=${label}¢er=${lat},${long}`,
android: `${scheme}${latLng}(${label})`
});
Linking.canOpenURL(url)
.then((supported) => {
if (!supported) {
browser_url =
"https://www.google.de/maps/#" +
latitude +
"," +
longitude +
"?q=" +
label;
return Linking.openURL(browser_url);
} else {
return Linking.openURL(url);
}
})
.catch((err) => console.log('error', err));
I am facing issue using Geolocation pluggin with Ionic and Cordova framework.
Using Visual Studio Community 2015, with Cordova CLI version :4.3.0 and added the org.apache.cordova.geolocation pluggin to VSC-2015
My controller.js
.controller('MapCtrl', function ($scope) {
function onSuccess(position) {
console.log(position.timestamp);
console.log(position.coords.latitude + " " + position.coords.longitude);
}
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
})
Added the google maps into the index.html
<script src="https://maps.googleapis.com/maps/api/js?sensor=true&v=3.exp"></script>
Added a Map to my Map.html file
<div id="map" data-tap-disabled="true" map> </div>
The problem is I always get a fixed value of Lat/Long
ie Lat = 43.465187 and Long = -80.522372
This is not my correct Geolocation in terms of Lat/Long.I need my current Geolocation in terms of Lat/Long
Please help me identity the fault.
Also I am using Ripple -Nexus (Galaxy) on Browser.
Any help is appreciated...
Thanks,
Download the Latest version of GeoLocation pluggin from https://github.com/apache/cordova-plugin-geolocation
Then inject the $cordovaGeolocation into the controller.
Code is as below:
.controller('HomeCtrl', function($scope,$cordovaGeolocation) {
$scope.getLocation = function() {
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
//these are your your lat long values
var lat = position.coords.latitude
var long = position.coords.longitude
}, function(err) {
// error
});
}
})
Note: The device need to be connected to internet or wifi and also need to keep the GPS location ON in the device for getting the correct Lat/Long Values.
I am not sure why you get fixed lat/long values. However to get the device's position using Ionic, the following works for me:
ionic.Platform.ready($scope.getLocation);
$scope.getLocation = function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition($scope.showPosition, $scope.showError);
}
else {
console.log('Geolocation is not supported by this browser.');
}
}
$scope.showPosition = function (position) {
console.log(position.timestamp);
console.log(position.coords.latitude + ' ' + position.coords.longitude);
}
$scope.showError = function (error) {
switch (error.code) {
case error.PERMISSION_DENIED:
console.log('User denied the request for Geolocation.');
break;
case error.POSITION_UNAVAILABLE:
console.log('Location information is unavailable.');
break;
case error.TIMEOUT:
console.log('The request to get user location timed out.');
break;
case error.UNKNOWN_ERROR:
console.log('An unknown error occurred.');
break;
}
}
Note that the call to:
ionic.Platform.ready($scope.getLocation);
Is crucial, as you can only guarantee you'll get an accurate GPS fix once the device is ready/initialised.
In ionic angularjs
I'm trying to get the Latitude and Longitude of my current location.
It is giving my current location correctly when I'm running it on the browser , but when I run it on IOS emulator it is giving some sanfransisco address.
COntroller.js
ionic.Platform.ready(function() {
LocationService.GetLocation().then(function(data){
console.log(data.latitude,data.longitude);
var code="https://maps.googleapis.com/maps/api/geocode/json?latlng="+data.latitude+","+data.longitude;
$http.get(code).success(function(dataval){
//console.log(dataval.results[0]);
$("#Locationval").text(dataval.results[0]["formatted_address"])
});
});
});
Service.js
appnService.factory('LocationService', function($q){
var currentLocation = {
latitude:"",
longitude:""
}
return {
GetLocation : function(){
var d = $q.defer();
//console.log(d);
navigator.geolocation.getCurrentPosition(function (pos) {
currentLocation.latitude = pos.coords.latitude;
currentLocation.longitude = pos.coords.longitude;
d.resolve(currentLocation);
});
return d.promise
}
};
});
On browser I'm Getting latitude=11.9384867 Longitude=79.8352657(These are correct)
On IOS emulator I'm getting latitude=37.785834 Longitude= -122.406417 (These are wrong)
Please help me with this
Thankyou
The Setup
Currently building my phone gap iOS app which includes geolocation in addition to sending the results to a database and getting back nearby locations. Because I am using jQuery Mobile and Phonegap, I was testing on a browser to perfection, geolocation was success and everything returned was as well. On the iOS device, not so much. When sending a set latitude and longitude, everything returned successfully, but when using the google maps geolocation, and eventually the cordova plugin for geolocation, both failed as unable to find my location, even though they are the exact same code, minus the phone gap initializer on the website.
The Code
jQuery
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
$(document).ready(function () {
//Load Google Map & Geolocate
$(document).on("pagecreate", "#game", function () {
// keep as separate function call to allow for DOM to update after a tag
loadGoogleMap();
});
function loadGoogleMap() {
var defaultLatLng = new google.maps.LatLng(34.0983425, -118.3267434); //default location is Hollywood, CA
if (navigator.geolocation) {
function success(pos) {
//set fields for current user latitude and longitude
$("#lat_in").val(pos.coords.latitude);
$("#lon_in").val(pos.coords.longitude);
//location found
drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
}
function fail(error) {
//try cordova geolocation plugin
function onSuccess(position) {
alert("CDV position success");
//alert(position.coords.latitude);
//alert(position.coords.longitude);
}
function onError(error) {
alert("CDV position error");
//alert("code: " + error.code + "\n" + "message: " + error.message);
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
alert("CDV position fail. Google geolocate fail"); //WHERE THE ERROR IS THROWN. THIS IS ALWAYS THE OUTCOME
//drawMap(defaultLatLng); //Failed to find location. Show default location
}
//Geolocate. Cache location for 5 mins. Timeout after 6 seconds
navigator.geolocation.getCurrentPosition(success, fail, {
maximumAge: 500000,
enableHighAccuracy: true,
timeout: 6000
});
} else {
drawMap(defaultLatLng); //No geolocation support, show default map
}
function drawMap(latlng) {
//Collect Data to Send
var uname = $("#unm_in").val();
var lat = $("#lat_in").val();
var lon = $("#lon_in").val();
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
//update latitude and longitude on DB for logged in user && get nearby users
$.post("PHP_ON_SERVER", {
uname: uname,
lat: lat,
lon: lon
}, function (data) {
$.each(data, function (key, value) {
//Define variables
var allUsrLoc = new google.maps.LatLng(value.lat, value.lon);
var contentString = value.uname;
var mkrImg = "inUsrIcon.png"; //icon for logged in user
var inUserName = value.fname + " " + value.lname;
//if info belongs to current user
if (contentString === uname) {
var marker = new google.maps.Marker({
position: allUsrLoc,
map: map,
title: "Player",
icon: mkrImg
});
//change header to name and points
$("#inUserInfo").text("Hi " + inUserName + " || You have " + value.points + " points");
//disable tag button if not it
if (value.isit === "notit") {
$("#tagBtn").addClass("ui-state-disabled");
}
}
//if not current user and is not it
else if (contentString != uname && value.isit != "it") {
var marker = new google.maps.Marker({
position: allUsrLoc,
map: map,
title: "Player"
});
google.maps.event.addListener(marker, 'click', function () {
//Change selected player hidden field to match marker
$("#unm_sel").val(contentString);
$("#lat_sel").val(value.lat);
$("#lon_sel").val(value.lon);
$("#isit_sel").val(value.isit);
//Change tag button to selected player's username
$("#tagBtn").text("Tag " + contentString);
});
}
//no condition for if not current user and is it. TBD if anything will come
});
}, "json");
} //end drawMap
} // end loadGoogleMap
}
HTML
<div data-role="content" role="main" id="map-canvas">
<!-- Map loads here -->
</div>
Some More to Know
I have been reading up on other related questions, but none of the others do work. Either they say use the plugin, which I am to no avail, or set <access origin="*" /> which I am doing already. In addition, most of the other questions revolve around pre-3.0.0 versions of phone gap, which was its own monster. Also, the map loads, just no markers display. On the DB, the user who's location is being updated is set to (0,0). Lastly, when using geolocation in any other app, the iOS device I test on is successfully finding my location. In addition, I am testing on the same WiFi network as the browser which worked, so anything relating to internally being unable to locate due to network or hardware is ruled out.
If you want to see the working example, just ask.
What i need is the lat/long of the client(via browser)
Found some articles on the net,found some in stack overflow itself(an old article) Get GPS location from the web browser. it was answered almost 18months ago -- wondering if there's any other(more efficient) way of getting the information of the location of the user from the browser.
Soo far,found 2
using Maxmind
http://coding.smashingmagazine.com/2010/03/08/entering-the-wonderful-world-of-geo-location/
Other,using google's api
http://briancray.com/2009/05/29/find-web-visitors-location-javascript-google-api/
w3c's geo api will have downward compatibility issues: http://dev.w3.org/geo/api/spec-source.html ,so not choosing that.
Found a site, www.drumaroo.com -- requests for the location to be shared the 1st time when we drop into the site.Needed something similar
The user can be located by using following ways:-
Using the IP addr.
easiest to achieve but most unreliable due to the uncertainty of network addresses /
topologies.
Using the latitude, longitude pair
most accurate solution, but most of the end users don’t know about their latitude,
longitude value.
Using the zipcodes
nice to think but quite difficult to achieve, although ZipCodes are being used for
quite a long time but this is not a standard yet. (see link
http://en.wikipedia.org/wiki/Postal_code ). ZipCode alone is not sufficient for
calculation of distance we need to convert it to latitude, longitude pair which is an
overhead.
Using user’s address
most compelling thought since each user will have at least one geographic address.
Address alone is not sufficient for calculation of distance we need to convert it to
latitude, longitude pair which is an overhead.
The Best option will be to use options 2,3.4 together, You can do that in two steps:-
First determine the latitude, longitude from the address.
Then use this lat, long value for further processing i.e. storing in
database etc.
For various options available for this see the answer of this question
Try HTML5 geolocation
function init() {
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}
} else {
alert('Geolocation not detected');
}
}
Here is geolocation described:
http://www.w3schools.com/htmL/html5_geolocation.asp
The lat/lng can then be reverse-geocoded to find the country, address. etc.
https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse
https://developers.google.com/maps/documentation/javascript/examples/map-geolocation . simply click on javascript+html and copy the code into an html file.
<!DOCTYPE html>
<html>
<head>
<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) {
var location_timeout = setTimeout("geolocFail()", 10000);
navigator.geolocation.getCurrentPosition(function(position) {
clearTimeout(location_timeout);
var lat = position.coords.latitude;
var lng = position.coords.longitude;
geocodeLatLng(lat, lng);
}, function(error) {
alert("inside error ");
clearTimeout(location_timeout);
geolocFail();
});
} else {
alert("Turn on the location service to make the deposit");
// Fallback for no geolocation
geolocFail();
}
function geolocFail(){
alert("Turn on the location service to make the deposit");
document.write("Turn on the location service to make the deposit");
}
/*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 geocodeLatLng(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
var add= results[0].formatted_address
alert(add);
//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>
This is HTML code to trace the device(Browser/Mobile) location .Just save the above file as .html extension and browse it from any browser on your system or Mobile ,it will display the user current location.