Search code examples
google-mapsappceleratortitanium-mobileappcelerator-mobilereverse-geocoding

get city name, address using latitude and longitude in appcelerator


I have a doubt in the mentioned Title. I can get current latitude and longitude. But when i am using reverse geoCoding to convert to corresponding city name or address, nothing shows. Does anybody have any idea about this ?. Here is my code

 Titanium.Geolocation.getCurrentPosition(function(e) {

            if (!e.success || e.error) {
                alert('Could not find the device location');
                return;
            } else {
                longitude = e.coords.longitude;
                latitude = e.coords.latitude;

                Titanium.Geolocation.reverseGeocoder(latitude, longitude, function(e) {
                    if (e.success) {
                        var places = e.places;
                        if (places && places.length) {
                            driverCity = places[0].city;
                            // Current city
                            driverState = places[0].address;
                            // Current State
                            annotation.title = e.places[0].displayAddress;
                            // Whole address
                            // Ti.API.info("\nReverse Geocode address == " + JSON.stringify(places));
                        } else {
                            // address = "No address found";
                        }
                    }
                });
            }
        });

Solution

  • I would suggest firstly using different variables for your return parameters in the functions and use negative conditions to reduce indentation:

    Titanium.Geolocation.getCurrentPosition(function(position) {
    
        if (!position.success || position.error) {
            alert('Could not find the device location');
            return;
        }
        longitude = position.coords.longitude;  //  -88.0747875
        latitude = position.coords.latitude;    //  41.801141
    
        Titanium.Geolocation.reverseGeocoder(latitude, longitude, function(result) {
           if (!result.success || !result.places || result.places.length == 0) {
               alert('Could not find any places.');
               return;
           }
           var places = result.places;
           Ti.API.info("\nReverse Geocode address == " + JSON.stringify(places));
           driverCity = places[0].city;
           // Current city
           driverState = places[0].address;
           // Current State
           annotation.title = places[0].displayAddress;
           // Whole address
           // Ti.API.info("\nReverse Geocode address == " + JSON.stringify(places));
        });
    });
    

    Then see what is being returned from your calls.