0

What is making the following code get the country and not the city, and how can I change it to get the city instead of country?

function get_visitor_country() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position){ 
            var lat = position.coords.latitude;
            var lon = position.coords.longitude;
            var latlng = new google.maps.LatLng(lat, lon);
            geocoder = new google.maps.Geocoder();

            geocoder.geocode({'latLng': latlng}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) { 
                    if (results[1]) {
                        var country = results[results.length-1].formatted_address;
                        $("#location-detection .location-name").html(country);
                        $("#geolocation-worked").css("display", "block");
                        $("#no-geolocation").css("display", "none");

                        $geolocation_fix.hide().css({ height : 0 });

                        init_geolocation_switch();
                    }
                }
            });
        });
    }
}

The script is also loading http://maps.google.com/maps/api/js?sensor=false at the end of the file, if that might be affecting it.

Rick Rhodes
  • 151
  • 1
  • 11

1 Answers1

1

Your script currently is not getting anything special(like a city or a country) , it gets something out of the results.

To get the city search inside the results for an entry with types set to ["locality", "political"]

When you found it you got the city.


Creation of an object labeled with addressTypes for convenient access:

var components={};
jQuery.each(results,function(i,v){
  components[jQuery.camelCase(v.types.join('-'))]=v;
})

//test it
alert((components.localityPolitical)
        ? components.localityPolitical.formatted_address
        : 'n/a');

See: Address Component Types

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201