How to do reverse geocoding with Cordova Geolocation API to get City and Country? - javascript

I am building a hybrid mobile application using Intel's App Framework for user interface and Cordova to access the native device functionalities.
As a part of the development, I need to get the user's location(City and Country) and show it in a text box.
By using the code below, I am able to get the Latitude and Longitude and show it in two different text boxes(with ID latitude and longitude respectively). How can I translate the latitude and longitude to City and Country.
function Geolocation() {
var onSuccess = function(position) {
document.getElementById('latitude').value = position.coords.latitude;
document.getElementById('longitude').value = position.coords.longitude;
};
var onFail = function() {
navigator.notification.alert('Cannot get the location');
};
navigator.geolocation.getCurrentPosition(onSuccess, onFail, {maximumAge:0, timeout:5000, enableHighAccuracy: true});
}
Note - I don't use any other plugin other than Cordova's Geolocation to handle location services in my app. This is a hybrid app but currently I am working on the Android version of the app.

This is called reverse geocoding are there are many services out there to do that - eg. Google Maps, OpenStreetMaps and many more.
I love OpenStreetMaps because it's very easy to do. Just a JSONP callback:
http://nominatim.openstreetmap.org/reverse?lat=-23.5880894&lon=-46.6321951&format=json&json_callback=my_callback
So you can just make an Ajax request to this URL and get the desired values. For example:
function showCountry(lat, lon) {
$.getJSON('//nominatim.openstreetmap.org/reverse?json_callback=?&format=json', {lat: lat, lon: lon}, function(data) {
alert(data.address.country);
});
}

Related

Script not working on inactive tab

I have script for geolocalization. It's working only when user is on website. When browser is miminalized or tab is inactive, script is not working. How can I fix it?
var int=self.setInterval(function(){getLocation()},2000);
function getLocation()
{
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position)
{
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
console.log('Position: '+latitude+' '+longitude);
$.ajax({
type : "POST",
data : { latitude : latitude, longitude : longitude },
url : "mylinktosaveposition",
success : function(data){}
});
}
This is a security feature built into browsers, there is no way to get around this! Browsers simply freeze or shut down scripts when they go inactive to increase performance on active tabs and reduce power usage on battery powered devices. I would recommend creating an app if you are looking into geotracing people for whatever reason. Take a look at ionic which is a framework on cordova which uses angular to built apps for ios and android in javascript/html like language.

Google Chrome: Override geolocation via console

So a little background for my question; I am writing a simple driving instructions web application using Google Maps directions API which provides me with a LatLng path along with text instructions.
In order to test this application (without driving around in a car) I need to simulate a geolocation-path. Google Chrome supports overriding geolocation data via the sensors developer settings, which works fine with one coordinate at the time.
So my question is - is it possible to set the browsers navigator.geolocation data via the console (i.e. javascript api) instead manually updating the value in the sensors settings menu?
I know that in this case I could just use another input source than the browser geolocation data and use a static array of LatLng's, or override the browsers navigator.geolocation.getCurrentPosition, but I figured that it would be more sophisticated to override the sensors instead.
Thanks in advance.
One way is to override the function navigator.geolocation.getCurrentPosition with your own custom function. Inside the custom function you can customize the value of latitude & longitude.
var customPosition = {};
customPosition.coords = {};
customPosition.coords.latitude = 41.89;
customPosition.coords.longitude = 2.89;
navigator.geolocation.getCurrentPosition = function(success, error){
success(customPosition);
};
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
console.log("latitude: " + latitude);
console.log("longitude: " + longitude);
}

How to search for nearby (getting coordinates from browser automatically) with Google Places Javascript API?

I am developing a website and I need a textbox prefilled with the nearest city from Google Places. I am currently using autocomplete to search for nearby, which does ask for browser's location permission, but how do I search for nearby cities using the API itself, without bothering to get user's location from browser and passing it into the Google Places API call? As Google already gets my location from browser anyway, shouldn't it (logically) just search for nearby places in respect to my current location in nearbySearch, or is there another way?
Okay,
I've ended up getting location from the browser natively and then passing the location to Places API, as Places API apparently doesn't have such (very basic) functionality. Here is how I got the location:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
//service is a PlacesService instance.
var req = {
location: pos,
radius: '50000',
types: ['(cities)']
};
service.nearbySearch(req, function (results, status) {
...
});
}

Geolocation doesn't work with cordova

I'm currently working on a mobile application with Intel XDK (In background it's Cordova finally, that's why I put Cordova in title.)
With an Ajax request, I get some adresses and with these adresses I want to calculate the distance between them and the current position of user.
So, I get adresses, I convert them and I make the difference.
But actually, nothing is working !
function codeAddress(id, addresse) {
geocoder.geocode( { 'address': addresse}, function(results, status) {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function(){}, 100);
}
console.log(id);
console.log(addresse);
//document.addEventListener("intel.xdk.device.ready",function(){
if (navigator.geolocation)
{
if (status == google.maps.GeocoderStatus.OK)
{
navigator.geolocation.getCurrentPosition(function(position) {
addressEvent = results[0].geometry.location;
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var position = new google.maps.LatLng(pos.lat, pos.lng)
var resultat = google.maps.geometry.spherical.computeDistanceBetween(addressEvent, position);
console.log(resultat);
console.log(addressEvent);
console.log(pos);
console.log(position);
var convert = Math.floor(resultat);
var finalConvert = convert + " m";
var distance = document.createElement('span');
distance.innerHTML = finalConvert;
distance.className = "geo";
document.getElementsByClassName('meta-info-geo')[id].appendChild(distance);
}, function() {
handleLocationError(true, infoWindow);
});
}
}
//},false);
});
}
In the console.log(id), console.log(addresse), I HAVE results !
Actually i'm getting 4 IDs and 4 adresses.
I checked on all the topics I could find on StackOverFlow, and I had normally to add the line in // with the addEventListener but it changes nothing.
Is there someone who knows how to change that ?
ps : Of course, cordova geoloc is in the build and permissions are granted !
EDIT : I'm targeting Android 4.0 min and iOS 5.1.1. I'm using SDK.
EDIT 2 :
Geolocation frequently does not work the way people expect it to work, for a variety of reasons that have been expressed here and here.
You can experiment with geo by using the "Hello, Cordova" sample app that is in the XDK and also available on GitHub. Try using it on a variety of devices to see how things work. Push the "fine" button to initiate a single geo call for a "fine" location and push the "coarse" button to initiate a single geo call for a "coarse" location. Push the "watch" button to initiate a request for a series of geo data points (set to coarse or fine by pushing one of the single buttons first).
The behavior you get in the Emulate tab will be dramatically different than what you get on a real device. The type of device (Android, iOS, etc.) and the version of that device will influence your results; the manufacturer of the device and your location (inside or outside) will influence your results. Do not assume that making a call to the geo APIs will always give you immediate and reliable data, geolocation hardware does not work that way... In fact, you cannot assume that you can even get a valid result! See the two links I pointed to earlier in the post for some reasons why.

Google maps api v3, defining user current location

function onPositionUpdate(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var markerPoint = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: markerPoint,
map: map,
title: 'Your Location'
});
}
function button_clicked() {
if (navigator.geolocation)
navigator.geolocation.getCurrentPosition(onPositionUpdate);
else
alert("navigator.geolocation is not available");
}
This code is running correctly and shows user location. when I try this at home this shows correct address but when I try this at another location this code doesn't show correct address. why? I dont know how this code run exactly(does this code define for IP or other information)
You can check if another program can find you. If not, it might be that its not your code which is incorrect:
http://html5demos.com/geo
Some security measures might cause that the client won't share location informations automatically.
Have you tried :
navigator.geolocation.getCurrentPosition(onPositionUpdate() );
Not sure if your callback has to have brackets or not. It's something I would try.
I also noticed that geolocation takes a little while to narrow down the approximation to a smaller radius. Might have to call position update.

Categories