Mohaideen
Mohaideen

Reputation: 303

How to get address from lat and lng?

I have two set of lat and lng.

I want both address and stored in some variable:

var geocoder = new google.maps.Geocoder();
        for(var i=0; i<json_devices.length; i++)
        {
            var lat = json_devices[i].latitude;
            var lng = json_devices[i].longitude;
            console.log(lat);
            console.log(lng);
            var latlng =  new google.maps.LatLng(lat,lng);
            geocoder.geocode({'latLng': latlng}, function(results, status) {
             if (status == google.maps.GeocoderStatus.OK) {
              if (results[1]) {
                address=results[1].formatted_address;
                   } else {
                    alert('No results found');
                  }
                } else {
                  alert('Geocoder failed due to: ' + status);
                }
            });
            console.log(address);
        }

In this, lat & lan get correctly. But address are not stored in variable. What is the mistake?

Upvotes: 2

Views: 323

Answers (2)

Praveen
Praveen

Reputation: 56529

Here the Google geocode is asynchonous type of function call.

From DOCS:

Accessing the Geocoding service is asynchronous, since the Google Maps API needs to make a call to an external server. For that reason, you need to pass a callback method to execute upon completion of the request. This callback method processes the result(s). Note that the geocoder may return more than one result.

So you can't get the address like that, instead use the common approach called callback.

Here I have created a sample code to explain the process, which can be altered by yourself.

var geocoder;

function codeLatLng(callback) {
    geocoder = new google.maps.Geocoder();
    var input = document.getElementById("latlng").value;
    var latlngStr = input.split(",", 2);
    var lat = parseFloat(latlngStr[0]);
    var lng = parseFloat(latlngStr[1]);
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({
        'latLng': latlng
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
                address = results[1].formatted_address;
                callback(address);
            } else {
                alert("No results found");
            }
        } else {
            alert("Geocoder failed due to: " + status);
        }
    });
}

$('input[type="button"]').on('click', function () {
    codeLatLng(function (address) { //function call with a callback
        console.log(address);  // THE ADDRESS WILL BE OBTAINED
    })
});

JSFIDDLE

Upvotes: 1

Amit Gupta
Amit Gupta

Reputation: 1077

I am using this method and it is working perfect for me. Please have a look on it.

public String getAddressFromLatLong(GeoPoint point) { 
        String address = "Address Not Found";
        Geocoder geoCoder = new Geocoder(
                getBaseContext(), Locale.getDefault());
        try {
            List<Address> addresses = geoCoder.getFromLocation(
                    point.getLatitudeE6()  / 1E6, 
                    point.getLongitudeE6() / 1E6, 1);

            if (addresses.size() > 0) {
                            address =addresses.get(0).getAddressLine(0);
                if(address.length()<=0)
                address =addresses.get(0).getSubLocality();
                 }
        }
        catch (Exception e) {                
            e.printStackTrace();
             }   
        return address;
    }

Upvotes: 1

Related Questions