I'm trying to figure out if the user is near a city ( within a 50 mile radius ) using geolocation.
Here is what I have. It is a script that checks if I am in any of the cities in the array. I am in a city in the New York City array of cities, but it is evaluating to the else as I see the function taking place.
Here is the script:
if('geolocation' in navigator){
var lat, lon;
var SFlocations = ['richmond', 'berkely', 'daly city', 'oakland', 'san francisco'];
var NYlocations = ['new york', 'new york city', 'new jersey', 'newark', 'kendall park', 'fraklin park', 'new brunswick', 'east brunswick', 'edison', 'manhattan', 'queen', 'staten island', 'bronx'];
navigator.geolocation.getCurrentPosition(function(pos){
lat = pos.coords.latitude;
lon = pos.coords.longitude;
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+lon+'&sensor=true').done(function(res){
var results = res.results;
var address = results[2].address_components;
var city = address[1].long_name.toLowerCase();
if(jQuery.inArray(city, SFlocations) !== -1) $('#input').css('backgroundImage', 'url(/cityBackground/SanFrancisco/day.png)').css('backgroundPosition', 'bottom left').css('backgroundSize', 'cover');
else if(jQuery.inArray(city, NYlocations) !== -1) $('#input').css('backgroundImage', 'url(/cityBackgrounds/NYC/night.png)');
else setBGPerTime();
});
});
}
else alert("don't supports geolocation");
Here is a JS Fiddle: http://jsfiddle.net/s9VrT/
It seems logical and I can't figure out why it is evaluating to false.
I would greatly appreciate any and all help!
EDIT: So it seems I am grabbing the wrong part of the results array. It seems like the city is located here: results[0][address_components][2]. Is that true for anyone else that tests it from a different location? But when I try to grab that part of the array, it says address_components is not defined. Here is a fiddle: http://jsfiddle.net/s9VrT/4/
EDIT: Okay, I got the city using this var results = res.results; var city = results[0].address_components[2].long_name.toLowerCase();
. However, I don't think this is the proper way. This gets the city for this location, but I don't think it will work for every location. How can I get the city regardless of what location the user is at?