EzDevInfo.com

geolocation interview questions

Top geolocation frequently asked interview questions

Where am I? - Get country

An android mobile actually does know quite well where it is - but is there a way of retrieving the country by something like a country code?

No need of knowing the exact GPS position - the country is sufficient

I first thought of using the time zone, but actually I need more information than that since it makes a difference if the location is New York or Lima.

The background of the question: I have an application that uses temperature values, and I'd like to set the default unit either to Celsius or Fahrenheit, depending on whether the location is US or outside


Source: (StackOverflow)

How do I get the current GPS location programmatically in Android?

I need to get my current location using GPS programmatically. How do I do that?


Source: (StackOverflow)

Advertisements

SQlite Getting nearest locations (with latitude and longitude)

I have data with latitude and longitude stored in my SQLite database, and I want to get the nearest locations to the parameters I put in (ex. My current location - lat/lng, etc.).

I know that this is possible in MySQL, and I've done quite some research that SQLite needs a custom external function for the Haversine formula (calculating distance on a sphere), but I haven't found anything that is written in Java and works.

Also, if I want to add custom functions, I need the org.sqlite .jar (for org.sqlite.Function), and that adds unnecessary size to the app.

The other side of this is, I need the Order by function from SQL, because displaying the distance alone isn't that much of a problem - I already did it in my custom SimpleCursorAdapter, but I can't sort the data, because I don't have the distance column in my database. That would mean updating the database every time the location changes and that's a waste of battery and performance. So if someone has any idea on sorting the cursor with a column that's not in the database, I'd be grateful too!

I know there are tons of Android apps out there that use this function, but can someone please explain the magic.

By the way, I found this alternative: Query to get records based on Radius in SQLite?

It's suggesting to make 4 new columns for cos and sin values of lat and lng, but is there any other, not so redundant way?


Source: (StackOverflow)

HTML 5 Geo Location Prompt in Chrome

Just starting to get into HTML 5 and an testing out geo location...liking it so far. I am hitting a bit of a speed bump though...when I try to get my geo location, chrome automatically blocks the page from getting my location. This does not happen at other sites such as the site below:

http://html5demos.com/geo

The scripts I'm using:

<script type="text/javascript" JavaScript" SRC="geo.js"></script>   
<script type="text/javascript" JavaScript" SRC="Utility.js"></script> 
<script type="text/javascript" JavaScript" SRC="jquery.js"></script> 
<script type="text/javascript" JavaScript" SRC="modernizr.js"></script>  

function get_location() {

        if (geo_position_js.init()) {
            geo_position_js.getCurrentPosition(show_map, handle_error);
        }

    }
    function show_map(position) {
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;

        alert("lat:" + latitude + " long:" + longitude);


    }
    function handle_error(err) {
        alert(err.code);
        if (err.code == 1) {
            // user said no!
        }
    }

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(show_map, handle_error);
    } else {
        error('not supported');
    }

I am testing this out from a local directory on my machine, so there isn't really a "domain" like "http://whatever.com/mytestpage.html". Is this why I am not getting prompted? If so, is it possible to force the browswer to request permission to get the user's geo location and is it possible in my scenario?


Source: (StackOverflow)

Google Maps: how to get country, state/province/region, city given a lat/long value?

I need a list of countries, states & cities based on a collection of lat/long values I have. I need to store this information in a manner that hierarchy is preserve and without duplicates (e.g. "USA" and "United States" and "United States of America" are the same country; I only want one instance of this country in my database).

Is this possible to do with Google Map API?


Source: (StackOverflow)

Get Country of IP Address with PHP

Ideally I'm trying to put together a PHP script that I can query from any web browser and it returns the Country of the IP address that accessed the PHP script.

Is this possible or is there a better solution?


Source: (StackOverflow)

How to obtain longitude and latitude for a street address programmatically (and legally)

Supposedly, it is possible to get this from Google Maps or some such service. (US addresses only is not good enough.)


Source: (StackOverflow)

Get city name using geolocation

I managed to get the user's latitude and longitude using html5 geolocation.

//Check if browser supports W3C Geolocation API
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 
//Get latitude and longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
}

I want to display the city name, it seems the only way to get it is to use a reverse geolocation api. I read google's documentation for reverse geolocation but I don't know how to get the output on my site.

I don't know how to go use this: "http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+long+'&sensor=true" to display the city name on the page.

What is standard way to do it?


Source: (StackOverflow)

How does Google calculate my location on a desktop?

Right this is confusing me quite a bit, i'm not sure if any of you have noticed or used the "my location" feature on google maps using your desktop (or none GPS/none mobile device). If you have a browser with google gears (easiest to use is Google Chrome) then you will have a blue circle above the zoom function in Google Maps, when clicked (without being logged into my Google Account) using standard Wi Fi to my own personal router and a normal internet connection to my ISP, it somehow manages to pinpoint my exact location with a 100% accuracy (at this moment in time).

How does it do it? they breifly mention it here but it doesn't quite explain it, it says that my browser knows where i am...

...i am baffled, how?

I am intrigued because I would love to integrate it in the future of my programming projects, just like some background understanding and it doesn't seem too well documented at the moment.


Source: (StackOverflow)

Why use the SQL Server 2008 geography data type?

I am redesigning a customer database and one of the new pieces of information I would like to store along with the standard address fields (Street, City, etc.) is the geographic location of the address. The only use case I have in mind is to allow users to map the coordinates on Google maps when the address cannot otherwise be found, which often happens when the area is newly developed, or is in a remote/rural location.

My first inclination was to store latitude and longitude as decimal values, but then I remembered that SQL Server 2008 R2 has a geography data type. I have absolutely no experience using geography, and from my initial research, it looks to be overkill for my scenario.

For example, to work with latitude and longitude stored as decimal(7,4), I can do this:

insert into Geotest(Latitude, Longitude) values (47.6475, -122.1393)
select Latitude, Longitude from Geotest

but with geography, I would do this:

insert into Geotest(Geolocation) values (geography::Point(47.6475, -122.1393, 4326))
select Geolocation.Lat, Geolocation.Long from Geotest

Although it's not that much more complicated, why add complexity if I don't have to?

Before I abandon the idea of using geography, is there anything I should consider? Would it be faster to search for a location using a spatial index vs. indexing the Latitude and Longitude fields? Are there advantages to using geography that I am not aware of? Or, on the flip side, are there caveats that I should know about which would discourage me from using geography?


Update

@Erik Philips brought up the ability to do proximity searches with geography, which is very cool.

On the other hand, a quick test is showing that a simple select to get the latitude and longitude is significantly slower when using geography (details below). , and a comment on the accepted answer to another SO question on geography has me leery:

@SaphuA You're welcome. As a sidenote be VERY carefull of using a spatial index on a nullable GEOGRAPHY datatype column. There are some serious performance issue, so make that GEOGRAPHY column non-nullable even if you have to remodel your schema. – Tomas Jun 18 at 11:18

All in all, weighing the likelihood of doing proximity searches vs. the trade-off in performance and complexity, I've decided to forgo the use of geography in this case.


Details of the test I ran:

I created two tables, one using geography and another using decimal(9,6) for latitude and longitude:

CREATE TABLE [dbo].[GeographyTest]
(
    [RowId] [int] IDENTITY(1,1) NOT NULL,
    [Location] [geography] NOT NULL,
    CONSTRAINT [PK_GeographyTest] PRIMARY KEY CLUSTERED ( [RowId] ASC )
) 

CREATE TABLE [dbo].[LatLongTest]
(
    [RowId] [int] IDENTITY(1,1) NOT NULL,
    [Latitude] [decimal](9, 6) NULL,
    [Longitude] [decimal](9, 6) NULL,
    CONSTRAINT [PK_LatLongTest] PRIMARY KEY CLUSTERED ([RowId] ASC)
) 

and inserted a single row using the same latitude and longitude values into each table:

insert into GeographyTest(Location) values (geography::Point(47.6475, -122.1393, 4326))
insert into LatLongTest(Latitude, Longitude) values (47.6475, -122.1393)

Finally, running the following code shows that, on my machine, selecting the latitude and longitude is approximately 5 times slower when using geography.

declare @lat float, @long float,
        @d datetime2, @repCount int, @trialCount int, 
        @geographyDuration int, @latlongDuration int,
        @trials int = 3, @reps int = 100000

create table #results 
(
    GeographyDuration int,
    LatLongDuration int
)

set @trialCount = 0

while @trialCount < @trials
begin

    set @repCount = 0
    set @d = sysdatetime()

    while @repCount < @reps
    begin
        select @lat = Location.Lat,  @long = Location.Long from GeographyTest where RowId = 1
        set @repCount = @repCount + 1
    end

    set @geographyDuration = datediff(ms, @d, sysdatetime())

    set @repCount = 0
    set @d = sysdatetime()

    while @repCount < @reps
    begin
        select @lat = Latitude,  @long = Longitude from LatLongTest where RowId = 1
        set @repCount = @repCount + 1
    end

    set @latlongDuration = datediff(ms, @d, sysdatetime())

    insert into #results values(@geographyDuration, @latlongDuration)

    set @trialCount = @trialCount + 1

end

select * 
from #results

select avg(GeographyDuration) as AvgGeographyDuration, avg(LatLongDuration) as AvgLatLongDuration
from #results

drop table #results

Results:

GeographyDuration LatLongDuration
----------------- ---------------
5146              1020
5143              1016
5169              1030

AvgGeographyDuration AvgLatLongDuration
-------------------- ------------------
5152                 1022

What was more surprising is that even when no rows are selected, for example selecting where RowId = 2, which doesn't exist, geography was still slower:

GeographyDuration LatLongDuration
----------------- ---------------
1607              948
1610              946
1607              947

AvgGeographyDuration AvgLatLongDuration
-------------------- ------------------
1608                 947

Source: (StackOverflow)

How to Get GPS location from the web browser

I am developing a mobile based web-site, there I have integrated google maps, I need to fill the 'From' field of google maps dynamically.

Is it possible to get the 'GPS' location from web-browser and fill it up in the 'From' field of a google map dynamically.


Source: (StackOverflow)

J2ME/Android/BlackBerry - driving directions, route between two locations

On Android 1.0 there was a com.google.googlenav namespace for driving directions:
Route - Improved Google Driving Directions
But in newer SDK it was removed by some reason...
Android: DrivingDirections removed since API 1.0 - how to do it in 1.5/1.6? On BlackBerry there is also lack of APIs for such stuff:
how to find the route between two places in Blackberry?

csie-tw gives a workaround (query gmaps for kml file and parse it):
Android - Driving Direction (Route Path)
Also Andrea made a DrivingDirections helper classes for Android.
I wrote a little helper for this functionality, in j2me, so I would like to share my samples on Android and BlackBerry.

UPDATE
As it was stated in comments, it's not officially allowed Google Maps APIs Terms of Service :

Google Maps/Google Earth APIs Terms of Service
Last updated: May 27, 2009
...
10. License Restrictions. Except as expressly permitted under the Terms, or unless you have received prior written authorization from Google (or, as applicable, from the provider of particular Content), Google's licenses above are subject to your adherence to all of the restrictions below. Except as explicitly permitted in Section 7 or the Maps APIs Documentation, you must not (nor may you permit anyone else to):
...
10.9 use the Service or Content with any products, systems, or applications for or in connection with:
(a) real time navigation or route guidance, including but not limited to turn-by-turn route guidance that is synchronized to the position of a user's sensor-enabled device;

and may be disabled for certain apps (somehow, at least on Android)... From Geocode scraping in .NET conversation:

This is not allowed by the API terms of use. You should not scrape Google Maps to generate geocodes. We will block services that do automated queries of our servers.

Bret Taylor
Product Manager, Google Maps

Would be grateful for any alternatives and/or suggestions!
Thanks!


Source: (StackOverflow)

How to get a time zone from a location using latitude and longitude coordinates?

There are too many questions on StackOverflow about resolving a time zone from a location. This community wiki is an attempt at consolidating all of the valid responses.

Please update my answer, or add your own as you see fit.

The Question
Given the latitude and longitude of a location, how does one know what time zone is in effect in that location?

In most cases, we are looking for an IANA/Olson time zone id, although some services may return just a UTC offset, or some other time zone identifier. Please read the timezone tag info for details.


Source: (StackOverflow)

Getting visitors country from their IP

I want to get visitors country via their IP... Right now I'm using this (http://api.hostip.info/country.php?ip=...... )

Here is my code:

<?php

if (isset($_SERVER['HTTP_CLIENT_IP']))
{
    $real_ip_adress = $_SERVER['HTTP_CLIENT_IP'];
}

if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
{
    $real_ip_adress = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
    $real_ip_adress = $_SERVER['REMOTE_ADDR'];
}

$cip = $real_ip_adress;
$iptolocation = 'http://api.hostip.info/country.php?ip=' . $cip;
$creatorlocation = file_get_contents($iptolocation);

?>

Well, it's working properly, but the thing is, this returns the country code like US or CA., and not the whole country name like United States or Canada.

So, is there any good alternative to hostip.info offers this?

I know that I can just write some code that will eventually turn this two letters to whole country name, but I'm just too lazy to write a code that contains all countries...

P.S: For some reason I don't want to use any ready made CSV file or any code that will grab this information for me, something like ip2country ready made code and CSV.


Source: (StackOverflow)

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

So I have a pretty simple bit of JS using the navigator.geolocation.getCurrentPosition jammy.

$(document).ready(function(){
  $("#business-locate, #people-locate").click(function() {
    navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
  });

  navigator.geolocation.getCurrentPosition(foundLocation, noLocation);

  function foundLocation(position) {
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
    var userLocation = lat + ', ' + lon;
    $("#business-current-location, #people-current-location").remove();
    $("#Near-Me")
      .watermark("Current Location")
      .after("<input type='hidden' name='business-current-location' id='business-current-location' value='"+userLocation+"' />");
    $("#people-Near-Me")
      .watermark("Current Location")
      .after("<input type='hidden' name='people-current-location' id='people-current-location' value='"+userLocation+"' />");
  }
  function noLocation() {
    $("#Near-Me").watermark("Could not find location");
    $("#people-Near-Me").watermark("Could not find location");
  }
})//end DocReady

Basically what's happening here is we get the current position, if it's obtained, two "watermarks" are placed in two fields that say "Current Position" and two hidden fields are created with the lat-long data as their value (they're removed in the beginning so they don't get duplicated every time). There are also two buttons that have a click function tied to them that do the same thing. Unfortunately, every third time or so, it works. What's the problem here???


Source: (StackOverflow)