In my app user types a location and I have to get latitude and longitude for that location. So here I don't have Location
object but a String
.
I thought of an option to create a Location
object using this String
but it is not possible.
I know using Google's places API it is possible and I know how to use that, but I prefer using any method available in SDK.
Is there any way to do so?
You can use Geocoder. Like this :
Geocoder geocoder = new Geocoder(App.getContext(), Locale.US);
List<Address> listOfAddress;
try {
listOfAddress = geocoder.getFromLocation(theLatitude, theLongitude, 1);
if(listOfAddress != null && !listOfAddress.isEmpty()){
Address address = listOfAddress.get(0);
String country = address.getCountryCode();
String adminArea= address.getAdminArea();
String locality= address.getLocality();
}
} catch (IOException e) {
e.printStackTrace();
}
Updated : to get location from address use :
listOfAddress = geocoder.getFromLocationName("Address", 1);
and to get lat, lon :
double latitude = address.getLatitude();
double longitude = address.getLongitude();
Updated : using this snippet to get Location when Geocoder returns null:
private static final String URL = "http://maps.googleapis.com/maps/api/geocode/xml";
public static RemoteCommand getLocation(String theAddress){
RemoteCommand result = new RemoteCommand();
result.setType(Type.GET);
result.setUrl(URL);
result.addGetParam("address", theAddress);
result.addGetParam("sensor", "false");
result.addGetParam("language", "en");
// See description about GeocoderXMLHandler
result.setXmlHandler(new GeocoderXMLHandler());
return result;
}
Best wishes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With