Iam having some problems with a function I wrote. I want to wrap this whole thing into a function called myClosestCity that returns the name of the city based on a JSON feed that gives coordinates from users IP. As far as I can see the problem is within the getJSON function. I've tried with global variables, getters and setters (which didnt work at all) and just about everything I could think of Googling.
By the way, for the code to run you'll need to include a script from Google Maps: http://maps.google.com/maps/api/js?sensor=false&libraries=geometry
Anyway, here's my whole code:
var stavanger = new google.maps.LatLng(58.96998, 5.73311);
var oslo = new google.maps.LatLng(59.91387, 10.75225);
var trondheim = new google.maps.LatLng(63.43051, 10.39505);
var bergen = new google.maps.LatLng(60.39126, 5.32205);
function calcDistance(p1, p2){
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
$.getJSON("http://www.geoplugin.net/json.gp?jsoncallback=?", function(data) {
myLocation = new google.maps.LatLng(data.geoplugin_latitude,data.geoplugin_longitude);
var distances = new Array();
distances[0] = calcDistance(myLocation, stavanger);
distances[1] = calcDistance(myLocation, oslo);
distances[2] = calcDistance(myLocation, trondheim);
distances[3] = calcDistance(myLocation, bergen);
maxValue = Math.min.apply(this, distances);
var findThisIndex = maxValue + "";
var placeNo = $.inArray(findThisIndex, distances);
if(placeNo == 0) {
closestCity = "Stavanger";
}
else if (placeNo == 1){
closestCity = "Oslo";
}
else if(placeNo == 2) {
closestCity = "Trondheim";
}
else if(placeNo == 3){
closestCity = "Bergen";
}
else {
closestCity = "Ukjent"; // Unknown in Norwegian
}
alert(closestCity);
});
Update: It's the closestCity variable I'd like to return!