Use js variable in api request - javascript

I'm building an app where i want to use the users location in the api request.
I fetch the user position with
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} else {
alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}
function successFunction(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
console.log('Your latitude is :'+lat+' and longitude is '+long);
}
I then need to use the lat and long variables in the api call render(<Main source="https://api.darksky.net/forecast/[key]/[latitude],[longitude]"/>, document.getElementById('app'));
I haven't been able to figure this out since i obviously can't just put the variable in the url

Related

Reverse Geocoding does not return a post code

I am trying to use HTML5 geolocation functionality with some google map APIs, for a mobile web app, as follows...
I have a MYSQL table that holds address records for properties including post code, but no coordinates. I am successfully using HTML5 Geolocation to get the current coordinates using this code...
<script>
window.onload = function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var latlng = position.coords.latitude + "," + position.coords.longitude;
var lat = position.coords.latitude;
var lng = position.coords.longitude;
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
</script>
...The DB table is large and I want to restrict the results of a query on post code, and so I need to do some kind of reverse geocoding to convert my current latlng into a post code to feed my query.
Using the corodinates returned in 'var latlng' testing at my home address, I have then tested this 'latlng' in the Reverse Geocoding sample in google dev examples here https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse but it only returns 'town, country' and no post code. Is there a way for me to get the post code every time, or perhaps find the nearest post code?
I then want to create my SQL e.g. "SELECT * FROM tblProperties WHERE tblProperties.postCode = 'geocodingPostalCode';"
I have tested the google dev example using other random coordinates that do return full addresses including post code but not at my home address, I need it to work all the time.
Any help much appreciated. Thank you.
The example you are using for reverse geocoding uses the second result, which may be to broad for a postcode. You won't necessarily always get a postcode, but the first result (results[0], rather than results[1]) would be more likely to have a postcode.

Check if user device's GPS is on

I am developing an app using jQuery Mobile with PHP. I am not using Phonegap or other frameworks. I need to find user's geolocation. If user device's GPS is off, then I cant get a location. now I need to find user device's GPS is on or off.
this is what i using now.
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var lat=position.coords.latitude;
var long=position.coords.longitude;
}
You can call this function on load
// Function to get location
function getLocation(){
navigator.geolocation.getCurrentPosition(function (pos) {
var lat = pos.coords.latitude;
var lng = pos.coords.longitude;
if (lat == null) {
alert("GPS not activated!");
} else {
alert("Latitude: "+ lat + " , Longitude: " + lng );
}
});
}
There is no way to check if the device has a GPS module or if it has it enabled through the browser's API. Your laptop will, for example, try to estimate the position based on the IP address with very poor accuracy.
You can, however, use a trick that will likely be good enough for many applications: instead of using the getCurrentPosition(), use the watchPosition() function with an options object { enableHighAccuracy: true } and set a threshold of accuracy that the measurement has to reach for you to accept it as most likely a result based on the GPS module.
What happens when you start to listen to the watchPosition() with enableHighAccuracy set to true is that if GPS module is available, the API will let it know that you're trying to get a measurement and after up to a few seconds the accuracy distance will go from very high (often thousands of meters - based on IP address, cell tower triangulation, etc.) to a very low (few meters - based on the GPS) and that means that the GPS kicked in. If the accuracy stays at hundreds or thousands of meters, it probably means that there is no GPS module available.
Here's the documentation for the GeolocationCoordinates object (the result within the callback passed to the watchPosition()) which comes with the accuracy field. I wrote a longer post that also contains a code snippet showing how I use the API within React.
I just solved this one. I am using:
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, {maximumAge: 60000});
In the successCallback i written the codes for what it should do once I got the positions and in the error callback i wrote a simple alert message to prompt the user to turn the GPS on.
I Implemented This In Real World Project
KMaps-API GPS.js
<script>
function getLocationw() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPositionw);
} else {
x.innerHTML = "Something Is Wrong";
}
}
function showPositionw(position) {
lat = position.coords.latitude;
if(lat != null){
document.write('<center><div class="alert alert-info" role="alert"> Please Turn On Your GPS </div></center>')
}
}
getLocationw();
</script>

Get coordinates from Hardware GPS

I've found a lot of questions about GPS Coordinates but not one that confirms using the mobile hardware GPS instead of Web GPS like geoLocation and such like.
My actual method:
I'm using navigator.geolocation.getCurrentPosition(), the Lat/Long comes from the Web, here's the code:
function getGPS(funcCallBack)
{
if (navigator.geolocation)
{
var timeoutVal = getCookie("GPSTimeout");
navigator.geolocation.getCurrentPosition(sucess
,error
,{enableHighAccuracy: true
,timeout: timeoutVal
,maximumAge: 0}
);
}
else{
alert('GPS is turned off, or was not possible to find it. Now, doing the login without localization.');
window.gpsLat = 0;
window.gpsLng = 0;
window.gpsAcc = 0;
funcCallBack();
}
function sucess(position) //sucess
{
window.gpsLat = position.coords.latitude;
window.gpsLng = position.coords.longitude;
window.gpsAcc = position.coords.accuracy;
funcCallBack();
}
function error() //error
{
window.gpsLat = 0;
window.gpsLng = 0;
window.gpsAcc = 0;
funcCallBack();
}
}
My problem:
Sometimes when I do the login I am not getting the GPS Coordinates (they come 0) and sometimes I am getting coordinates with more than 2,000 Accuracy (that is not precise).
By the way, I am testing the GPS on a data internet service, when I do use a Wi-Fi connection it works perfectly with less than 100 Accuracy.
Details:
Maybe you are complaining about:
timeoutVal: it is a cookie with the number 5000 inside it.
funcCallBack: it is a function that continues the login operation.
window.gpsLat: it is a global var containing the Latitude value got from the geoLocation.
window.gpsLng: it is a global var containing the Longitude value got from the geoLocation.
window.gpsAcc: it is a global var containing the Accuracy value got from the geoLocation.
What do I want?
I want a solution in JavaScript or PHP that can get coordinates from the mobile hardware device, the Native GPS, not the geolocation, and when the Native GPS is turned off, ask the user to turn it on.
You should get the location with javascript not PHP. PHP is only capable of doing an IP lookup which is the least accurate method for determining location.
The way navigator.geolocation.getCurrentPosition() works is it uses the most accurate data currently available. In the case of a mobile device it will use GPS first if enabled, then wi-fi.
If native GPS is enabled javascript will access that data instead of the wi-fi data, but there is no way of preventing a check against the wi-fi data if the GPS data isn't available.
Your best solution is to check the accuracy field and if it's not within a range you're happy with ask the user to enable GPS.
Alternatively if you're building a hybrid app, most of the frameworks (PhoneGap .etc.) have APIs to query the device GPS directly. Use PhoneGap to Check if GPS is enabled
Geolocation API does not expose a direct way to check whether GPS is on or off, but you can catch the errors of geolocation and base on error type can draw conclusions from there.
E.g. POSITION_UNAVAILABLE (2) if the network is down or the positioning satellites can’t be contacted.
But its not sure short way you have to handle some conditions!
I will suggest use watchPostion { i agree its meant to watch and continuous to locate position} u can keep it on and if GPS throw the error u can prompt custom alert to make user turn on the GPS device/wifi/internet .. and if its come to success callback u can clear the watch.
var watch =null;
function success(position)
{
var lat = position.coords.latitude;
var lon= position.coords.longitude;
if (watch != null )
/*Need to take care .. as maybe there is no gps and user
want it off so keep attempt 3 times or some kind a way out otherwise it will
infinite loop */
{
navigator.geolocation.clearWatch(watch);
watch = null;
}
}
function getLatLon()
{
var geolocOK = ("geolocation" in navigator);
if ( geolocOK )
{
var option = {enableHighAccuracy:true, maximumAge: 0,timeout:10000 };
watch = navigator.geolocation.watchPosition(success, fails, option);
}
else {
//disable the current location?
}
}
function fails()
{
alert("please turn on the GPS !");
}
getLatLon();

navigator.geolocation.getCurrentPosition() doesn't work

I am trying to get the latitude and longitude of my current location using geolocation. Extremely similar code was working until recently, and I can't figure out why it stopped working. It is no longer setting the variables latitude or longitude. When I walk through the js code, the getCurrentPosition() method is skipped and I'm not sure why. Bizarrely, if I put an alert box in the getCurrentPosition() method, it will get and display the latitude and longitude correctly... I have no idea why it does that.
var gl;
try {
if (typeof navigator.geolocation === 'undefined'){
gl = google.gears.factory.create('beta.geolocation');
} else {
gl = navigator.geolocation;
}
} catch(e) {}
var latitude;
var longitude;
if (gl) {
gl.getCurrentPosition(
function (position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
//alert("got the lat & long - lat=" + latitude + ", lng=" + longitude);
},
function (error) {
alert("Error getting geolocation:" + error);
}
);
} else {
alert("Geolocation services are not supported by your web browser.");
}
I then go on to set some markers on a map using the Google Maps API.
Thank you very much,
Peter
EDIT
Here the code on JSFiddle showing the weird behavior:
http://jsfiddle.net/JtmCV/
I just tried your jsfiddle and it worked fine (Chrome 19 on Win 7), so I can't see why it should be causing problems.
Having said that, I'd strongly recommend switching to use navigator.geolocation.watchPosition instead of navigator.geolocation.getCurrentPosition. I recently did some work on a geolocation system and found getCurrentPosition can return unreliable cached positions, even if you use the options parameter to specify a low maximumAge value.
My latest version stops the watch after one of the following is true:
the fifth position has been returned
the accuracy is under 100m
the time since the watch began is over 30 seconds

Center Google Map Based on geocoded IP

Basically whenever someones opens up my (Google) map I want it default to their approximate location.
Is there an easy way to do it with Google's API or do I have to write a custom code (this is python based app)?
You can use Google API's built-in ClientLocation object:
if (GBrowserIsCompatible())
{
var map = new google.maps.Map2(document.getElementById("mapdiv"));
if (google.loader.ClientLocation)
{
var center = new google.maps.LatLng(
google.loader.ClientLocation.latitude,
google.loader.ClientLocation.longitude
);
var zoom = 8;
map.setCenter(center, zoom);
}
}
Check out http://www.ipinfodb.com/. You can get a latitude and longitude value by passing their services an IP address. I did something recently where I created a simple service that grabbed the current IP address and then passed it to the service ("api/location/city" is just a service that curls the ipinfodb service). Using jquery:
$.get("api/location/city", null, function(data, textStatus)
{
if (data != null)
{
if (data.Status == "OK")
{
var lat = parseFloat(data.Latitude);
var lng = parseFloat(data.Longitude);
$.setCenter(lat, lng, $.settings.defaultCityZoom);
manager = new MarkerManager(map, {trackMarkers : true });
var e = $.createUserMarker(map.getCenter());
e.bindInfoWindowHtml($("#marker-content-event").html());
var m = [];
m.push(e);
// map.addOverlay(e);
manager.addMarkers(m, 10);
manager.refresh();
}
else
{
$.setCenter($.settings.defaultLat, $.settings.defaultLng, $.settings.defaultZoom);
}
}
}, "json");
The key here is this line:
$.setCenter(lat, lng, $.settings.defaultCityZoom);
Just setting the center to the lat/lng of the result of the service call.
Per the docs, just map.setCenter(new GLatLng(37.4419, -122.1419), 13); or whatever other coordinates. Doing it in the page's Javascript is normally preferred.
If you mean translating an IP to lat and long, I don't think the Google API supports that, but there are other web services that do, such as maxmind, hostip, and many, many others. I don't know which one(s) to recommend -- try out a few, would be my suggestion!
If the user uses FireFox 3.5/google gears, you can retrieve the lat and lng from the browser itself.
You'll find details on another stackoverflow post here
IP Address Geocoding API for Google Maps: http://web3o.blogspot.com/2011/06/ip-address-geocoding-api-for-google.html

Categories

Resources